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