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 
00493   // DIType is abstract, it should be a BasicType, a DerivedType or
00494   // a CompositeType.
00495   if (isBasicType())
00496     return DIBasicType(DbgNode).Verify();
00497   else if (isCompositeType())
00498     return DICompositeType(DbgNode).Verify();
00499   else if (isDerivedType())
00500     return DIDerivedType(DbgNode).Verify();
00501   else
00502     return false;
00503 }
00504 
00505 /// Verify - Verify that a basic type descriptor is well formed.
00506 bool DIBasicType::Verify() const {
00507   return isBasicType() && DbgNode->getNumOperands() == 10;
00508 }
00509 
00510 /// Verify - Verify that a derived type descriptor is well formed.
00511 bool DIDerivedType::Verify() const {
00512   // Make sure DerivedFrom @ field 9 is TypeRef.
00513   if (!fieldIsTypeRef(DbgNode, 9))
00514     return false;
00515   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
00516     // Make sure ClassType @ field 10 is a TypeRef.
00517     if (!fieldIsTypeRef(DbgNode, 10))
00518       return false;
00519 
00520   return isDerivedType() && DbgNode->getNumOperands() >= 10 &&
00521          DbgNode->getNumOperands() <= 14;
00522 }
00523 
00524 /// Verify - Verify that a composite type descriptor is well formed.
00525 bool DICompositeType::Verify() const {
00526   if (!isCompositeType())
00527     return false;
00528 
00529   // Make sure DerivedFrom @ field 9 and ContainingType @ field 12 are TypeRef.
00530   if (!fieldIsTypeRef(DbgNode, 9))
00531     return false;
00532   if (!fieldIsTypeRef(DbgNode, 12))
00533     return false;
00534 
00535   // Make sure the type identifier at field 14 is MDString, it can be null.
00536   if (!fieldIsMDString(DbgNode, 14))
00537     return false;
00538 
00539   // A subroutine type can't be both & and &&.
00540   if (isLValueReference() && isRValueReference())
00541     return false;
00542 
00543   return DbgNode->getNumOperands() == 15;
00544 }
00545 
00546 /// Verify - Verify that a subprogram descriptor is well formed.
00547 bool DISubprogram::Verify() const {
00548   if (!isSubprogram())
00549     return false;
00550 
00551   // Make sure context @ field 2 is a ScopeRef and type @ field 7 is a MDNode.
00552   if (!fieldIsScopeRef(DbgNode, 2))
00553     return false;
00554   if (!fieldIsMDNode(DbgNode, 7))
00555     return false;
00556   // Containing type @ field 12.
00557   if (!fieldIsTypeRef(DbgNode, 12))
00558     return false;
00559 
00560   // A subprogram can't be both & and &&.
00561   if (isLValueReference() && isRValueReference())
00562     return false;
00563 
00564   return DbgNode->getNumOperands() == 20;
00565 }
00566 
00567 /// Verify - Verify that a global variable descriptor is well formed.
00568 bool DIGlobalVariable::Verify() const {
00569   if (!isGlobalVariable())
00570     return false;
00571 
00572   if (getDisplayName().empty())
00573     return false;
00574   // Make sure context @ field 2 is an MDNode.
00575   if (!fieldIsMDNode(DbgNode, 2))
00576     return false;
00577   // Make sure that type @ field 8 is a DITypeRef.
00578   if (!fieldIsTypeRef(DbgNode, 8))
00579     return false;
00580   // Make sure StaticDataMemberDeclaration @ field 12 is MDNode.
00581   if (!fieldIsMDNode(DbgNode, 12))
00582     return false;
00583 
00584   return DbgNode->getNumOperands() == 13;
00585 }
00586 
00587 /// Verify - Verify that a variable descriptor is well formed.
00588 bool DIVariable::Verify() const {
00589   if (!isVariable())
00590     return false;
00591 
00592   // Make sure context @ field 1 is an MDNode.
00593   if (!fieldIsMDNode(DbgNode, 1))
00594     return false;
00595   // Make sure that type @ field 5 is a DITypeRef.
00596   if (!fieldIsTypeRef(DbgNode, 5))
00597     return false;
00598 
00599   // Variable without a complex expression.
00600   if (DbgNode->getNumOperands() == 8)
00601     return true;
00602 
00603   // Make sure the complex expression is an MDNode.
00604   return (DbgNode->getNumOperands() == 9 && fieldIsMDNode(DbgNode, 8));
00605 }
00606 
00607 /// Verify - Verify that a location descriptor is well formed.
00608 bool DILocation::Verify() const {
00609   if (!DbgNode)
00610     return false;
00611 
00612   return DbgNode->getNumOperands() == 4;
00613 }
00614 
00615 /// Verify - Verify that a namespace descriptor is well formed.
00616 bool DINameSpace::Verify() const {
00617   if (!isNameSpace())
00618     return false;
00619   return DbgNode->getNumOperands() == 5;
00620 }
00621 
00622 /// \brief Retrieve the MDNode for the directory/file pair.
00623 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
00624 
00625 /// \brief Verify that the file descriptor is well formed.
00626 bool DIFile::Verify() const {
00627   return isFile() && DbgNode->getNumOperands() == 2;
00628 }
00629 
00630 /// \brief Verify that the enumerator descriptor is well formed.
00631 bool DIEnumerator::Verify() const {
00632   return isEnumerator() && DbgNode->getNumOperands() == 3;
00633 }
00634 
00635 /// \brief Verify that the subrange descriptor is well formed.
00636 bool DISubrange::Verify() const {
00637   return isSubrange() && DbgNode->getNumOperands() == 3;
00638 }
00639 
00640 /// \brief Verify that the lexical block descriptor is well formed.
00641 bool DILexicalBlock::Verify() const {
00642   return isLexicalBlock() && DbgNode->getNumOperands() == 6;
00643 }
00644 
00645 /// \brief Verify that the file-scoped lexical block descriptor is well formed.
00646 bool DILexicalBlockFile::Verify() const {
00647   return isLexicalBlockFile() && DbgNode->getNumOperands() == 4;
00648 }
00649 
00650 /// \brief Verify that the template type parameter descriptor is well formed.
00651 bool DITemplateTypeParameter::Verify() const {
00652   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 7;
00653 }
00654 
00655 /// \brief Verify that the template value parameter descriptor is well formed.
00656 bool DITemplateValueParameter::Verify() const {
00657   return isTemplateValueParameter() && DbgNode->getNumOperands() == 8;
00658 }
00659 
00660 /// \brief Verify that the imported module descriptor is well formed.
00661 bool DIImportedEntity::Verify() const {
00662   return isImportedEntity() &&
00663          (DbgNode->getNumOperands() == 4 || DbgNode->getNumOperands() == 5);
00664 }
00665 
00666 /// getObjCProperty - Return property node, if this ivar is associated with one.
00667 MDNode *DIDerivedType::getObjCProperty() const {
00668   return getNodeField(DbgNode, 10);
00669 }
00670 
00671 MDString *DICompositeType::getIdentifier() const {
00672   return cast_or_null<MDString>(getField(DbgNode, 14));
00673 }
00674 
00675 #ifndef NDEBUG
00676 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
00677   for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
00678     // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
00679     if (i == 0 && isa<ConstantInt>(LHS->getOperand(i)))
00680       continue;
00681     const MDNode *E = cast<MDNode>(LHS->getOperand(i));
00682     bool found = false;
00683     for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
00684       found = E == RHS->getOperand(j);
00685     assert(found && "Losing a member during member list replacement");
00686   }
00687 }
00688 #endif
00689 
00690 /// \brief Set the array of member DITypes.
00691 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
00692   TrackingVH<MDNode> N(*this);
00693   if (Elements) {
00694 #ifndef NDEBUG
00695     // Check that the new list of members contains all the old members as well.
00696     if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(10)))
00697       VerifySubsetOf(El, Elements);
00698 #endif
00699     N->replaceOperandWith(10, Elements);
00700   }
00701   if (TParams)
00702     N->replaceOperandWith(13, TParams);
00703   DbgNode = N;
00704 }
00705 
00706 /// Generate a reference to this DIType. Uses the type identifier instead
00707 /// of the actual MDNode if possible, to help type uniquing.
00708 DIScopeRef DIScope::getRef() const {
00709   if (!isCompositeType())
00710     return DIScopeRef(*this);
00711   DICompositeType DTy(DbgNode);
00712   if (!DTy.getIdentifier())
00713     return DIScopeRef(*this);
00714   return DIScopeRef(DTy.getIdentifier());
00715 }
00716 
00717 /// \brief Set the containing type.
00718 void DICompositeType::setContainingType(DICompositeType ContainingType) {
00719   TrackingVH<MDNode> N(*this);
00720   N->replaceOperandWith(12, ContainingType.getRef());
00721   DbgNode = N;
00722 }
00723 
00724 /// isInlinedFnArgument - Return true if this variable provides debugging
00725 /// information for an inlined function arguments.
00726 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
00727   assert(CurFn && "Invalid function");
00728   if (!getContext().isSubprogram())
00729     return false;
00730   // This variable is not inlined function argument if its scope
00731   // does not describe current function.
00732   return !DISubprogram(getContext()).describes(CurFn);
00733 }
00734 
00735 /// describes - Return true if this subprogram provides debugging
00736 /// information for the function F.
00737 bool DISubprogram::describes(const Function *F) {
00738   assert(F && "Invalid function");
00739   if (F == getFunction())
00740     return true;
00741   StringRef Name = getLinkageName();
00742   if (Name.empty())
00743     Name = getName();
00744   if (F->getName() == Name)
00745     return true;
00746   return false;
00747 }
00748 
00749 unsigned DISubprogram::isOptimized() const {
00750   assert(DbgNode && "Invalid subprogram descriptor!");
00751   if (DbgNode->getNumOperands() == 15)
00752     return getUnsignedField(14);
00753   return 0;
00754 }
00755 
00756 MDNode *DISubprogram::getVariablesNodes() const {
00757   return getNodeField(DbgNode, 18);
00758 }
00759 
00760 DIArray DISubprogram::getVariables() const {
00761   return DIArray(getNodeField(DbgNode, 18));
00762 }
00763 
00764 Value *DITemplateValueParameter::getValue() const {
00765   return getField(DbgNode, 4);
00766 }
00767 
00768 // If the current node has a parent scope then return that,
00769 // else return an empty scope.
00770 DIScopeRef DIScope::getContext() const {
00771 
00772   if (isType())
00773     return DIType(DbgNode).getContext();
00774 
00775   if (isSubprogram())
00776     return DIScopeRef(DISubprogram(DbgNode).getContext());
00777 
00778   if (isLexicalBlock())
00779     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
00780 
00781   if (isLexicalBlockFile())
00782     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
00783 
00784   if (isNameSpace())
00785     return DIScopeRef(DINameSpace(DbgNode).getContext());
00786 
00787   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
00788   return DIScopeRef(nullptr);
00789 }
00790 
00791 // If the scope node has a name, return that, else return an empty string.
00792 StringRef DIScope::getName() const {
00793   if (isType())
00794     return DIType(DbgNode).getName();
00795   if (isSubprogram())
00796     return DISubprogram(DbgNode).getName();
00797   if (isNameSpace())
00798     return DINameSpace(DbgNode).getName();
00799   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
00800           isCompileUnit()) &&
00801          "Unhandled type of scope.");
00802   return StringRef();
00803 }
00804 
00805 StringRef DIScope::getFilename() const {
00806   if (!DbgNode)
00807     return StringRef();
00808   return ::getStringField(getNodeField(DbgNode, 1), 0);
00809 }
00810 
00811 StringRef DIScope::getDirectory() const {
00812   if (!DbgNode)
00813     return StringRef();
00814   return ::getStringField(getNodeField(DbgNode, 1), 1);
00815 }
00816 
00817 DIArray DICompileUnit::getEnumTypes() const {
00818   if (!DbgNode || DbgNode->getNumOperands() < 13)
00819     return DIArray();
00820 
00821   return DIArray(getNodeField(DbgNode, 7));
00822 }
00823 
00824 DIArray DICompileUnit::getRetainedTypes() const {
00825   if (!DbgNode || DbgNode->getNumOperands() < 13)
00826     return DIArray();
00827 
00828   return DIArray(getNodeField(DbgNode, 8));
00829 }
00830 
00831 DIArray DICompileUnit::getSubprograms() const {
00832   if (!DbgNode || DbgNode->getNumOperands() < 13)
00833     return DIArray();
00834 
00835   return DIArray(getNodeField(DbgNode, 9));
00836 }
00837 
00838 DIArray DICompileUnit::getGlobalVariables() const {
00839   if (!DbgNode || DbgNode->getNumOperands() < 13)
00840     return DIArray();
00841 
00842   return DIArray(getNodeField(DbgNode, 10));
00843 }
00844 
00845 DIArray DICompileUnit::getImportedEntities() const {
00846   if (!DbgNode || DbgNode->getNumOperands() < 13)
00847     return DIArray();
00848 
00849   return DIArray(getNodeField(DbgNode, 11));
00850 }
00851 
00852 /// copyWithNewScope - Return a copy of this location, replacing the
00853 /// current scope with the given one.
00854 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
00855                                         DILexicalBlockFile NewScope) {
00856   SmallVector<Value *, 10> Elts;
00857   assert(Verify());
00858   for (unsigned I = 0; I < DbgNode->getNumOperands(); ++I) {
00859     if (I != 2)
00860       Elts.push_back(DbgNode->getOperand(I));
00861     else
00862       Elts.push_back(NewScope);
00863   }
00864   MDNode *NewDIL = MDNode::get(Ctx, Elts);
00865   return DILocation(NewDIL);
00866 }
00867 
00868 /// computeNewDiscriminator - Generate a new discriminator value for this
00869 /// file and line location.
00870 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
00871   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
00872   return ++Ctx.pImpl->DiscriminatorTable[Key];
00873 }
00874 
00875 /// fixupSubprogramName - Replace contains special characters used
00876 /// in a typical Objective-C names with '.' in a given string.
00877 static void fixupSubprogramName(DISubprogram Fn, SmallVectorImpl<char> &Out) {
00878   StringRef FName =
00879       Fn.getFunction() ? Fn.getFunction()->getName() : Fn.getName();
00880   FName = Function::getRealLinkageName(FName);
00881 
00882   StringRef Prefix("llvm.dbg.lv.");
00883   Out.reserve(FName.size() + Prefix.size());
00884   Out.append(Prefix.begin(), Prefix.end());
00885 
00886   bool isObjCLike = false;
00887   for (size_t i = 0, e = FName.size(); i < e; ++i) {
00888     char C = FName[i];
00889     if (C == '[')
00890       isObjCLike = true;
00891 
00892     if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' ||
00893                        C == '+' || C == '(' || C == ')'))
00894       Out.push_back('.');
00895     else
00896       Out.push_back(C);
00897   }
00898 }
00899 
00900 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is
00901 /// suitable to hold function specific information.
00902 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) {
00903   SmallString<32> Name;
00904   fixupSubprogramName(Fn, Name);
00905   return M.getNamedMetadata(Name.str());
00906 }
00907 
00908 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
00909 /// to hold function specific information.
00910 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) {
00911   SmallString<32> Name;
00912   fixupSubprogramName(Fn, Name);
00913   return M.getOrInsertNamedMetadata(Name.str());
00914 }
00915 
00916 /// createInlinedVariable - Create a new inlined variable based on current
00917 /// variable.
00918 /// @param DV            Current Variable.
00919 /// @param InlinedScope  Location at current variable is inlined.
00920 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
00921                                        LLVMContext &VMContext) {
00922   SmallVector<Value *, 16> Elts;
00923   // Insert inlined scope as 7th element.
00924   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
00925     i == 7 ? Elts.push_back(InlinedScope) : Elts.push_back(DV->getOperand(i));
00926   return DIVariable(MDNode::get(VMContext, Elts));
00927 }
00928 
00929 /// cleanseInlinedVariable - Remove inlined scope from the variable.
00930 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
00931   SmallVector<Value *, 16> Elts;
00932   // Insert inlined scope as 7th element.
00933   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
00934     i == 7 ? Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)))
00935            : Elts.push_back(DV->getOperand(i));
00936   return DIVariable(MDNode::get(VMContext, Elts));
00937 }
00938 
00939 
00940 /// getEntireVariable - Remove OpPiece exprs from the variable.
00941 DIVariable llvm::getEntireVariable(DIVariable DV) {
00942   if (!DV.isVariablePiece())
00943     return DV;
00944 
00945   SmallVector<Value *, 8> Elts;
00946   for (unsigned i = 0; i < 8; ++i)
00947     Elts.push_back(DV->getOperand(i));
00948 
00949   return DIVariable(MDNode::get(DV->getContext(), Elts));
00950 }
00951 
00952 /// getDISubprogram - Find subprogram that is enclosing this scope.
00953 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
00954   DIDescriptor D(Scope);
00955   if (D.isSubprogram())
00956     return DISubprogram(Scope);
00957 
00958   if (D.isLexicalBlockFile())
00959     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
00960 
00961   if (D.isLexicalBlock())
00962     return getDISubprogram(DILexicalBlock(Scope).getContext());
00963 
00964   return DISubprogram();
00965 }
00966 
00967 /// getDICompositeType - Find underlying composite type.
00968 DICompositeType llvm::getDICompositeType(DIType T) {
00969   if (T.isCompositeType())
00970     return DICompositeType(T);
00971 
00972   if (T.isDerivedType()) {
00973     // This function is currently used by dragonegg and dragonegg does
00974     // not generate identifier for types, so using an empty map to resolve
00975     // DerivedFrom should be fine.
00976     DITypeIdentifierMap EmptyMap;
00977     return getDICompositeType(
00978         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
00979   }
00980 
00981   return DICompositeType();
00982 }
00983 
00984 /// Update DITypeIdentifierMap by going through retained types of each CU.
00985 DITypeIdentifierMap
00986 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
00987   DITypeIdentifierMap Map;
00988   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
00989     DICompileUnit CU(CU_Nodes->getOperand(CUi));
00990     DIArray Retain = CU.getRetainedTypes();
00991     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
00992       if (!Retain.getElement(Ti).isCompositeType())
00993         continue;
00994       DICompositeType Ty(Retain.getElement(Ti));
00995       if (MDString *TypeId = Ty.getIdentifier()) {
00996         // Definition has priority over declaration.
00997         // Try to insert (TypeId, Ty) to Map.
00998         std::pair<DITypeIdentifierMap::iterator, bool> P =
00999             Map.insert(std::make_pair(TypeId, Ty));
01000         // If TypeId already exists in Map and this is a definition, replace
01001         // whatever we had (declaration or definition) with the definition.
01002         if (!P.second && !Ty.isForwardDecl())
01003           P.first->second = Ty;
01004       }
01005     }
01006   }
01007   return Map;
01008 }
01009 
01010 //===----------------------------------------------------------------------===//
01011 // DebugInfoFinder implementations.
01012 //===----------------------------------------------------------------------===//
01013 
01014 void DebugInfoFinder::reset() {
01015   CUs.clear();
01016   SPs.clear();
01017   GVs.clear();
01018   TYs.clear();
01019   Scopes.clear();
01020   NodesSeen.clear();
01021   TypeIdentifierMap.clear();
01022   TypeMapInitialized = false;
01023 }
01024 
01025 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
01026   if (!TypeMapInitialized)
01027     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
01028       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
01029       TypeMapInitialized = true;
01030     }
01031 }
01032 
01033 /// processModule - Process entire module and collect debug info.
01034 void DebugInfoFinder::processModule(const Module &M) {
01035   InitializeTypeMap(M);
01036   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
01037     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
01038       DICompileUnit CU(CU_Nodes->getOperand(i));
01039       addCompileUnit(CU);
01040       DIArray GVs = CU.getGlobalVariables();
01041       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
01042         DIGlobalVariable DIG(GVs.getElement(i));
01043         if (addGlobalVariable(DIG)) {
01044           processScope(DIG.getContext());
01045           processType(DIG.getType().resolve(TypeIdentifierMap));
01046         }
01047       }
01048       DIArray SPs = CU.getSubprograms();
01049       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
01050         processSubprogram(DISubprogram(SPs.getElement(i)));
01051       DIArray EnumTypes = CU.getEnumTypes();
01052       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
01053         processType(DIType(EnumTypes.getElement(i)));
01054       DIArray RetainedTypes = CU.getRetainedTypes();
01055       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
01056         processType(DIType(RetainedTypes.getElement(i)));
01057       DIArray Imports = CU.getImportedEntities();
01058       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
01059         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
01060         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
01061         if (Entity.isType())
01062           processType(DIType(Entity));
01063         else if (Entity.isSubprogram())
01064           processSubprogram(DISubprogram(Entity));
01065         else if (Entity.isNameSpace())
01066           processScope(DINameSpace(Entity).getContext());
01067       }
01068     }
01069   }
01070 }
01071 
01072 /// processLocation - Process DILocation.
01073 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
01074   if (!Loc)
01075     return;
01076   InitializeTypeMap(M);
01077   processScope(Loc.getScope());
01078   processLocation(M, Loc.getOrigLocation());
01079 }
01080 
01081 /// processType - Process DIType.
01082 void DebugInfoFinder::processType(DIType DT) {
01083   if (!addType(DT))
01084     return;
01085   processScope(DT.getContext().resolve(TypeIdentifierMap));
01086   if (DT.isCompositeType()) {
01087     DICompositeType DCT(DT);
01088     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
01089     if (DT.isSubroutineType()) {
01090       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
01091       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
01092         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
01093       return;
01094     }
01095     DIArray DA = DCT.getElements();
01096     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
01097       DIDescriptor D = DA.getElement(i);
01098       if (D.isType())
01099         processType(DIType(D));
01100       else if (D.isSubprogram())
01101         processSubprogram(DISubprogram(D));
01102     }
01103   } else if (DT.isDerivedType()) {
01104     DIDerivedType DDT(DT);
01105     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
01106   }
01107 }
01108 
01109 void DebugInfoFinder::processScope(DIScope Scope) {
01110   if (Scope.isType()) {
01111     DIType Ty(Scope);
01112     processType(Ty);
01113     return;
01114   }
01115   if (Scope.isCompileUnit()) {
01116     addCompileUnit(DICompileUnit(Scope));
01117     return;
01118   }
01119   if (Scope.isSubprogram()) {
01120     processSubprogram(DISubprogram(Scope));
01121     return;
01122   }
01123   if (!addScope(Scope))
01124     return;
01125   if (Scope.isLexicalBlock()) {
01126     DILexicalBlock LB(Scope);
01127     processScope(LB.getContext());
01128   } else if (Scope.isLexicalBlockFile()) {
01129     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
01130     processScope(LBF.getScope());
01131   } else if (Scope.isNameSpace()) {
01132     DINameSpace NS(Scope);
01133     processScope(NS.getContext());
01134   }
01135 }
01136 
01137 /// processSubprogram - Process DISubprogram.
01138 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
01139   if (!addSubprogram(SP))
01140     return;
01141   processScope(SP.getContext().resolve(TypeIdentifierMap));
01142   processType(SP.getType());
01143   DIArray TParams = SP.getTemplateParams();
01144   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
01145     DIDescriptor Element = TParams.getElement(I);
01146     if (Element.isTemplateTypeParameter()) {
01147       DITemplateTypeParameter TType(Element);
01148       processScope(TType.getContext().resolve(TypeIdentifierMap));
01149       processType(TType.getType().resolve(TypeIdentifierMap));
01150     } else if (Element.isTemplateValueParameter()) {
01151       DITemplateValueParameter TVal(Element);
01152       processScope(TVal.getContext().resolve(TypeIdentifierMap));
01153       processType(TVal.getType().resolve(TypeIdentifierMap));
01154     }
01155   }
01156 }
01157 
01158 /// processDeclare - Process DbgDeclareInst.
01159 void DebugInfoFinder::processDeclare(const Module &M,
01160                                      const DbgDeclareInst *DDI) {
01161   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
01162   if (!N)
01163     return;
01164   InitializeTypeMap(M);
01165 
01166   DIDescriptor DV(N);
01167   if (!DV.isVariable())
01168     return;
01169 
01170   if (!NodesSeen.insert(DV))
01171     return;
01172   processScope(DIVariable(N).getContext());
01173   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
01174 }
01175 
01176 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
01177   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
01178   if (!N)
01179     return;
01180   InitializeTypeMap(M);
01181 
01182   DIDescriptor DV(N);
01183   if (!DV.isVariable())
01184     return;
01185 
01186   if (!NodesSeen.insert(DV))
01187     return;
01188   processScope(DIVariable(N).getContext());
01189   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
01190 }
01191 
01192 /// addType - Add type into Tys.
01193 bool DebugInfoFinder::addType(DIType DT) {
01194   if (!DT)
01195     return false;
01196 
01197   if (!NodesSeen.insert(DT))
01198     return false;
01199 
01200   TYs.push_back(DT);
01201   return true;
01202 }
01203 
01204 /// addCompileUnit - Add compile unit into CUs.
01205 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
01206   if (!CU)
01207     return false;
01208   if (!NodesSeen.insert(CU))
01209     return false;
01210 
01211   CUs.push_back(CU);
01212   return true;
01213 }
01214 
01215 /// addGlobalVariable - Add global variable into GVs.
01216 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
01217   if (!DIG)
01218     return false;
01219 
01220   if (!NodesSeen.insert(DIG))
01221     return false;
01222 
01223   GVs.push_back(DIG);
01224   return true;
01225 }
01226 
01227 // addSubprogram - Add subprgoram into SPs.
01228 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
01229   if (!SP)
01230     return false;
01231 
01232   if (!NodesSeen.insert(SP))
01233     return false;
01234 
01235   SPs.push_back(SP);
01236   return true;
01237 }
01238 
01239 bool DebugInfoFinder::addScope(DIScope Scope) {
01240   if (!Scope)
01241     return false;
01242   // FIXME: Ocaml binding generates a scope with no content, we treat it
01243   // as null for now.
01244   if (Scope->getNumOperands() == 0)
01245     return false;
01246   if (!NodesSeen.insert(Scope))
01247     return false;
01248   Scopes.push_back(Scope);
01249   return true;
01250 }
01251 
01252 //===----------------------------------------------------------------------===//
01253 // DIDescriptor: dump routines for all descriptors.
01254 //===----------------------------------------------------------------------===//
01255 
01256 /// dump - Print descriptor to dbgs() with a newline.
01257 void DIDescriptor::dump() const {
01258   print(dbgs());
01259   dbgs() << '\n';
01260 }
01261 
01262 /// print - Print descriptor.
01263 void DIDescriptor::print(raw_ostream &OS) const {
01264   if (!DbgNode)
01265     return;
01266 
01267   if (const char *Tag = dwarf::TagString(getTag()))
01268     OS << "[ " << Tag << " ]";
01269 
01270   if (this->isSubrange()) {
01271     DISubrange(DbgNode).printInternal(OS);
01272   } else if (this->isCompileUnit()) {
01273     DICompileUnit(DbgNode).printInternal(OS);
01274   } else if (this->isFile()) {
01275     DIFile(DbgNode).printInternal(OS);
01276   } else if (this->isEnumerator()) {
01277     DIEnumerator(DbgNode).printInternal(OS);
01278   } else if (this->isBasicType()) {
01279     DIType(DbgNode).printInternal(OS);
01280   } else if (this->isDerivedType()) {
01281     DIDerivedType(DbgNode).printInternal(OS);
01282   } else if (this->isCompositeType()) {
01283     DICompositeType(DbgNode).printInternal(OS);
01284   } else if (this->isSubprogram()) {
01285     DISubprogram(DbgNode).printInternal(OS);
01286   } else if (this->isGlobalVariable()) {
01287     DIGlobalVariable(DbgNode).printInternal(OS);
01288   } else if (this->isVariable()) {
01289     DIVariable(DbgNode).printInternal(OS);
01290   } else if (this->isObjCProperty()) {
01291     DIObjCProperty(DbgNode).printInternal(OS);
01292   } else if (this->isNameSpace()) {
01293     DINameSpace(DbgNode).printInternal(OS);
01294   } else if (this->isScope()) {
01295     DIScope(DbgNode).printInternal(OS);
01296   }
01297 }
01298 
01299 void DISubrange::printInternal(raw_ostream &OS) const {
01300   int64_t Count = getCount();
01301   if (Count != -1)
01302     OS << " [" << getLo() << ", " << Count - 1 << ']';
01303   else
01304     OS << " [unbounded]";
01305 }
01306 
01307 void DIScope::printInternal(raw_ostream &OS) const {
01308   OS << " [" << getDirectory() << "/" << getFilename() << ']';
01309 }
01310 
01311 void DICompileUnit::printInternal(raw_ostream &OS) const {
01312   DIScope::printInternal(OS);
01313   OS << " [";
01314   unsigned Lang = getLanguage();
01315   if (const char *LangStr = dwarf::LanguageString(Lang))
01316     OS << LangStr;
01317   else
01318     (OS << "lang 0x").write_hex(Lang);
01319   OS << ']';
01320 }
01321 
01322 void DIEnumerator::printInternal(raw_ostream &OS) const {
01323   OS << " [" << getName() << " :: " << getEnumValue() << ']';
01324 }
01325 
01326 void DIType::printInternal(raw_ostream &OS) const {
01327   if (!DbgNode)
01328     return;
01329 
01330   StringRef Res = getName();
01331   if (!Res.empty())
01332     OS << " [" << Res << "]";
01333 
01334   // TODO: Print context?
01335 
01336   OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
01337      << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
01338   if (isBasicType())
01339     if (const char *Enc =
01340             dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
01341       OS << ", enc " << Enc;
01342   OS << "]";
01343 
01344   if (isPrivate())
01345     OS << " [private]";
01346   else if (isProtected())
01347     OS << " [protected]";
01348   else if (isPublic())
01349     OS << " [public]";
01350 
01351   if (isArtificial())
01352     OS << " [artificial]";
01353 
01354   if (isForwardDecl())
01355     OS << " [decl]";
01356   else if (getTag() == dwarf::DW_TAG_structure_type ||
01357            getTag() == dwarf::DW_TAG_union_type ||
01358            getTag() == dwarf::DW_TAG_enumeration_type ||
01359            getTag() == dwarf::DW_TAG_class_type)
01360     OS << " [def]";
01361   if (isVector())
01362     OS << " [vector]";
01363   if (isStaticMember())
01364     OS << " [static]";
01365 
01366   if (isLValueReference())
01367     OS << " [reference]";
01368 
01369   if (isRValueReference())
01370     OS << " [rvalue reference]";
01371 }
01372 
01373 void DIDerivedType::printInternal(raw_ostream &OS) const {
01374   DIType::printInternal(OS);
01375   OS << " [from " << getTypeDerivedFrom().getName() << ']';
01376 }
01377 
01378 void DICompositeType::printInternal(raw_ostream &OS) const {
01379   DIType::printInternal(OS);
01380   DIArray A = getElements();
01381   OS << " [" << A.getNumElements() << " elements]";
01382 }
01383 
01384 void DINameSpace::printInternal(raw_ostream &OS) const {
01385   StringRef Name = getName();
01386   if (!Name.empty())
01387     OS << " [" << Name << ']';
01388 
01389   OS << " [line " << getLineNumber() << ']';
01390 }
01391 
01392 void DISubprogram::printInternal(raw_ostream &OS) const {
01393   // TODO : Print context
01394   OS << " [line " << getLineNumber() << ']';
01395 
01396   if (isLocalToUnit())
01397     OS << " [local]";
01398 
01399   if (isDefinition())
01400     OS << " [def]";
01401 
01402   if (getScopeLineNumber() != getLineNumber())
01403     OS << " [scope " << getScopeLineNumber() << "]";
01404 
01405   if (isPrivate())
01406     OS << " [private]";
01407   else if (isProtected())
01408     OS << " [protected]";
01409   else if (isPublic())
01410     OS << " [public]";
01411 
01412   if (isLValueReference())
01413     OS << " [reference]";
01414 
01415   if (isRValueReference())
01416     OS << " [rvalue reference]";
01417 
01418   StringRef Res = getName();
01419   if (!Res.empty())
01420     OS << " [" << Res << ']';
01421 }
01422 
01423 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
01424   StringRef Res = getName();
01425   if (!Res.empty())
01426     OS << " [" << Res << ']';
01427 
01428   OS << " [line " << getLineNumber() << ']';
01429 
01430   // TODO : Print context
01431 
01432   if (isLocalToUnit())
01433     OS << " [local]";
01434 
01435   if (isDefinition())
01436     OS << " [def]";
01437 }
01438 
01439 void DIVariable::printInternal(raw_ostream &OS) const {
01440   StringRef Res = getName();
01441   if (!Res.empty())
01442     OS << " [" << Res << ']';
01443 
01444   OS << " [line " << getLineNumber() << ']';
01445 
01446   if (isVariablePiece())
01447     OS << " [piece, size " << getPieceSize()
01448        << ", offset " << getPieceOffset() << ']';
01449 }
01450 
01451 void DIObjCProperty::printInternal(raw_ostream &OS) const {
01452   StringRef Name = getObjCPropertyName();
01453   if (!Name.empty())
01454     OS << " [" << Name << ']';
01455 
01456   OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
01457      << ']';
01458 }
01459 
01460 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
01461                           const LLVMContext &Ctx) {
01462   if (!DL.isUnknown()) { // Print source line info.
01463     DIScope Scope(DL.getScope(Ctx));
01464     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
01465     // Omit the directory, because it's likely to be long and uninteresting.
01466     CommentOS << Scope.getFilename();
01467     CommentOS << ':' << DL.getLine();
01468     if (DL.getCol() != 0)
01469       CommentOS << ':' << DL.getCol();
01470     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
01471     if (!InlinedAtDL.isUnknown()) {
01472       CommentOS << " @[ ";
01473       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
01474       CommentOS << " ]";
01475     }
01476   }
01477 }
01478 
01479 void DIVariable::printExtendedName(raw_ostream &OS) const {
01480   const LLVMContext &Ctx = DbgNode->getContext();
01481   StringRef Res = getName();
01482   if (!Res.empty())
01483     OS << Res << "," << getLineNumber();
01484   if (MDNode *InlinedAt = getInlinedAt()) {
01485     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
01486     if (!InlinedAtDL.isUnknown()) {
01487       OS << " @[";
01488       printDebugLoc(InlinedAtDL, OS, Ctx);
01489       OS << "]";
01490     }
01491   }
01492 }
01493 
01494 /// Specialize constructor to make sure it has the correct type.
01495 template <> DIRef<DIScope>::DIRef(const Value *V) : Val(V) {
01496   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
01497 }
01498 template <> DIRef<DIType>::DIRef(const Value *V) : Val(V) {
01499   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
01500 }
01501 
01502 /// Specialize getFieldAs to handle fields that are references to DIScopes.
01503 template <>
01504 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
01505   return DIScopeRef(getField(DbgNode, Elt));
01506 }
01507 /// Specialize getFieldAs to handle fields that are references to DITypes.
01508 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
01509   return DITypeRef(getField(DbgNode, Elt));
01510 }
01511 
01512 /// Strip debug info in the module if it exists.
01513 /// To do this, we remove all calls to the debugger intrinsics and any named
01514 /// metadata for debugging. We also remove debug locations for instructions.
01515 /// Return true if module is modified.
01516 bool llvm::StripDebugInfo(Module &M) {
01517 
01518   bool Changed = false;
01519 
01520   // Remove all of the calls to the debugger intrinsics, and remove them from
01521   // the module.
01522   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
01523     while (!Declare->use_empty()) {
01524       CallInst *CI = cast<CallInst>(Declare->user_back());
01525       CI->eraseFromParent();
01526     }
01527     Declare->eraseFromParent();
01528     Changed = true;
01529   }
01530 
01531   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
01532     while (!DbgVal->use_empty()) {
01533       CallInst *CI = cast<CallInst>(DbgVal->user_back());
01534       CI->eraseFromParent();
01535     }
01536     DbgVal->eraseFromParent();
01537     Changed = true;
01538   }
01539 
01540   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
01541          NME = M.named_metadata_end(); NMI != NME;) {
01542     NamedMDNode *NMD = NMI;
01543     ++NMI;
01544     if (NMD->getName().startswith("llvm.dbg.")) {
01545       NMD->eraseFromParent();
01546       Changed = true;
01547     }
01548   }
01549 
01550   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
01551     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
01552          ++FI)
01553       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
01554            ++BI) {
01555         if (!BI->getDebugLoc().isUnknown()) {
01556           Changed = true;
01557           BI->setDebugLoc(DebugLoc());
01558         }
01559       }
01560 
01561   return Changed;
01562 }
01563 
01564 /// Return Debug Info Metadata Version by checking module flags.
01565 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
01566   Value *Val = M.getModuleFlag("Debug Info Version");
01567   if (!Val)
01568     return 0;
01569   return cast<ConstantInt>(Val)->getZExtValue();
01570 }
01571 
01572 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
01573 llvm::makeSubprogramMap(const Module &M) {
01574   DenseMap<const Function *, DISubprogram> R;
01575 
01576   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
01577   if (!CU_Nodes)
01578     return R;
01579 
01580   for (MDNode *N : CU_Nodes->operands()) {
01581     DICompileUnit CUNode(N);
01582     DIArray SPs = CUNode.getSubprograms();
01583     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
01584       DISubprogram SP(SPs.getElement(i));
01585       if (Function *F = SP.getFunction())
01586         R.insert(std::make_pair(F, SP));
01587     }
01588   }
01589   return R;
01590 }