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