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