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