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