LLVM  mainline
DIBuilder.cpp
Go to the documentation of this file.
00001 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
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 DIBuilder.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/DIBuilder.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/IR/Constants.h"
00017 #include "llvm/IR/DebugInfo.h"
00018 #include "llvm/IR/IntrinsicInst.h"
00019 #include "llvm/IR/Module.h"
00020 #include "llvm/Support/Debug.h"
00021 #include "llvm/Support/Dwarf.h"
00022 
00023 using namespace llvm;
00024 using namespace llvm::dwarf;
00025 
00026 namespace {
00027 class HeaderBuilder {
00028   /// \brief Whether there are any fields yet.
00029   ///
00030   /// Note that this is not equivalent to \c Chars.empty(), since \a concat()
00031   /// may have been called already with an empty string.
00032   bool IsEmpty;
00033   SmallVector<char, 256> Chars;
00034 
00035 public:
00036   HeaderBuilder() : IsEmpty(true) {}
00037   HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {}
00038   HeaderBuilder(HeaderBuilder &&X)
00039       : IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {}
00040 
00041   template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
00042     if (IsEmpty)
00043       IsEmpty = false;
00044     else
00045       Chars.push_back(0);
00046     Twine(X).toVector(Chars);
00047     return *this;
00048   }
00049 
00050   MDString *get(LLVMContext &Context) const {
00051     return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
00052   }
00053 
00054   static HeaderBuilder get(unsigned Tag) {
00055     return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag));
00056   }
00057 };
00058 }
00059 
00060 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
00061     : M(m), VMContext(M.getContext()), TempEnumTypes(nullptr),
00062       TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr),
00063       DeclareFn(nullptr), ValueFn(nullptr),
00064       AllowUnresolvedNodes(AllowUnresolvedNodes) {}
00065 
00066 void DIBuilder::trackIfUnresolved(MDNode *N) {
00067   if (!N)
00068     return;
00069   if (N->isResolved())
00070     return;
00071 
00072   assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
00073   UnresolvedNodes.emplace_back(N);
00074 }
00075 
00076 void DIBuilder::finalize() {
00077   TempEnumTypes->replaceAllUsesWith(MDTuple::get(VMContext, AllEnumTypes));
00078 
00079   SmallVector<Metadata *, 16> RetainValues;
00080   // Declarations and definitions of the same type may be retained. Some
00081   // clients RAUW these pairs, leaving duplicates in the retained types
00082   // list. Use a set to remove the duplicates while we transform the
00083   // TrackingVHs back into Values.
00084   SmallPtrSet<Metadata *, 16> RetainSet;
00085   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
00086     if (RetainSet.insert(AllRetainTypes[I]).second)
00087       RetainValues.push_back(AllRetainTypes[I]);
00088   TempRetainTypes->replaceAllUsesWith(MDTuple::get(VMContext, RetainValues));
00089 
00090   DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
00091   TempSubprograms->replaceAllUsesWith(SPs.get());
00092   for (auto *SP : SPs) {
00093     if (MDTuple *Temp = SP->getVariables().get()) {
00094       const auto &PV = PreservedVariables.lookup(SP);
00095       SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
00096       DINodeArray AV = getOrCreateArray(Variables);
00097       TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
00098     }
00099   }
00100 
00101   TempGVs->replaceAllUsesWith(MDTuple::get(VMContext, AllGVs));
00102 
00103   TempImportedModules->replaceAllUsesWith(MDTuple::get(
00104       VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
00105                                              AllImportedModules.end())));
00106 
00107   // Now that all temp nodes have been replaced or deleted, resolve remaining
00108   // cycles.
00109   for (const auto &N : UnresolvedNodes)
00110     if (N && !N->isResolved())
00111       N->resolveCycles();
00112   UnresolvedNodes.clear();
00113 
00114   // Can't handle unresolved nodes anymore.
00115   AllowUnresolvedNodes = false;
00116 }
00117 
00118 /// If N is compile unit return NULL otherwise return N.
00119 static DIScope *getNonCompileUnitScope(DIScope *N) {
00120   if (!N || isa<DICompileUnit>(N))
00121     return nullptr;
00122   return cast<DIScope>(N);
00123 }
00124 
00125 DICompileUnit *DIBuilder::createCompileUnit(
00126     unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
00127     bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
00128     DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) {
00129 
00130   assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
00131           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
00132          "Invalid Language tag");
00133   assert(!Filename.empty() &&
00134          "Unable to create compile unit without filename");
00135 
00136   // TODO: Once we make DICompileUnit distinct, stop using temporaries here
00137   // (just start with operands assigned to nullptr).
00138   TempEnumTypes = MDTuple::getTemporary(VMContext, None);
00139   TempRetainTypes = MDTuple::getTemporary(VMContext, None);
00140   TempSubprograms = MDTuple::getTemporary(VMContext, None);
00141   TempGVs = MDTuple::getTemporary(VMContext, None);
00142   TempImportedModules = MDTuple::getTemporary(VMContext, None);
00143 
00144   // TODO: Switch to getDistinct().  We never want to merge compile units based
00145   // on contents.
00146   DICompileUnit *CUNode = DICompileUnit::get(
00147       VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
00148       isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes.get(),
00149       TempRetainTypes.get(), TempSubprograms.get(), TempGVs.get(),
00150       TempImportedModules.get(), DWOId);
00151 
00152   // Create a named metadata so that it is easier to find cu in a module.
00153   // Note that we only generate this when the caller wants to actually
00154   // emit debug information. When we are only interested in tracking
00155   // source line locations throughout the backend, we prevent codegen from
00156   // emitting debug info in the final output by not generating llvm.dbg.cu.
00157   if (EmitDebugInfo) {
00158     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
00159     NMD->addOperand(CUNode);
00160   }
00161 
00162   trackIfUnresolved(CUNode);
00163   return CUNode;
00164 }
00165 
00166 static DIImportedEntity *
00167 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
00168                      Metadata *NS, unsigned Line, StringRef Name,
00169                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
00170   auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
00171   AllImportedModules.emplace_back(M);
00172   return M;
00173 }
00174 
00175 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
00176                                                   DINamespace *NS,
00177                                                   unsigned Line) {
00178   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
00179                                 Context, NS, Line, StringRef(), AllImportedModules);
00180 }
00181 
00182 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
00183                                                   DIImportedEntity *NS,
00184                                                   unsigned Line) {
00185   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
00186                                 Context, NS, Line, StringRef(), AllImportedModules);
00187 }
00188 
00189 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
00190                                                        DINode *Decl,
00191                                                        unsigned Line,
00192                                                        StringRef Name) {
00193   // Make sure to use the unique identifier based metadata reference for
00194   // types that have one.
00195   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
00196                                 Context, DINodeRef::get(Decl), Line, Name,
00197                                 AllImportedModules);
00198 }
00199 
00200 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
00201   return DIFile::get(VMContext, Filename, Directory);
00202 }
00203 
00204 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
00205   assert(!Name.empty() && "Unable to create enumerator without name");
00206   return DIEnumerator::get(VMContext, Val, Name);
00207 }
00208 
00209 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
00210   assert(!Name.empty() && "Unable to create type without name");
00211   return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
00212 }
00213 
00214 DIBasicType *DIBuilder::createNullPtrType() {
00215   return createUnspecifiedType("decltype(nullptr)");
00216 }
00217 
00218 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
00219                                         uint64_t AlignInBits,
00220                                         unsigned Encoding) {
00221   assert(!Name.empty() && "Unable to create type without name");
00222   return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
00223                           AlignInBits, Encoding);
00224 }
00225 
00226 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
00227   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
00228                             DITypeRef::get(FromTy), 0, 0, 0, 0);
00229 }
00230 
00231 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
00232                                             uint64_t SizeInBits,
00233                                             uint64_t AlignInBits,
00234                                             StringRef Name) {
00235   // FIXME: Why is there a name here?
00236   return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
00237                             nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
00238                             SizeInBits, AlignInBits, 0, 0);
00239 }
00240 
00241 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
00242                                                   DIType *Base,
00243                                                   uint64_t SizeInBits,
00244                                                   uint64_t AlignInBits) {
00245   return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
00246                             nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
00247                             SizeInBits, AlignInBits, 0, 0,
00248                             DITypeRef::get(Base));
00249 }
00250 
00251 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy) {
00252   assert(RTy && "Unable to create reference type");
00253   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
00254                             DITypeRef::get(RTy), 0, 0, 0, 0);
00255 }
00256 
00257 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
00258                                         DIFile *File, unsigned LineNo,
00259                                         DIScope *Context) {
00260   return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
00261                             LineNo,
00262                             DIScopeRef::get(getNonCompileUnitScope(Context)),
00263                             DITypeRef::get(Ty), 0, 0, 0, 0);
00264 }
00265 
00266 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
00267   assert(Ty && "Invalid type!");
00268   assert(FriendTy && "Invalid friend type!");
00269   return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
00270                             DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0,
00271                             0, 0);
00272 }
00273 
00274 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
00275                                             uint64_t BaseOffset,
00276                                             unsigned Flags) {
00277   assert(Ty && "Unable to create inheritance");
00278   return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
00279                             0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0,
00280                             BaseOffset, Flags);
00281 }
00282 
00283 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
00284                                            DIFile *File, unsigned LineNumber,
00285                                            uint64_t SizeInBits,
00286                                            uint64_t AlignInBits,
00287                                            uint64_t OffsetInBits,
00288                                            unsigned Flags, DIType *Ty) {
00289   return DIDerivedType::get(
00290       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
00291       DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty),
00292       SizeInBits, AlignInBits, OffsetInBits, Flags);
00293 }
00294 
00295 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
00296   if (C)
00297     return ConstantAsMetadata::get(C);
00298   return nullptr;
00299 }
00300 
00301 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
00302                                                  DIFile *File,
00303                                                  unsigned LineNumber,
00304                                                  DIType *Ty, unsigned Flags,
00305                                                  llvm::Constant *Val) {
00306   Flags |= DINode::FlagStaticMember;
00307   return DIDerivedType::get(
00308       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
00309       DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0,
00310       0, Flags, getConstantOrNull(Val));
00311 }
00312 
00313 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
00314                                          unsigned LineNumber,
00315                                          uint64_t SizeInBits,
00316                                          uint64_t AlignInBits,
00317                                          uint64_t OffsetInBits, unsigned Flags,
00318                                          DIType *Ty, MDNode *PropertyNode) {
00319   return DIDerivedType::get(
00320       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
00321       DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty),
00322       SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
00323 }
00324 
00325 DIObjCProperty *
00326 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
00327                               StringRef GetterName, StringRef SetterName,
00328                               unsigned PropertyAttributes, DIType *Ty) {
00329   return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
00330                              SetterName, PropertyAttributes, Ty);
00331 }
00332 
00333 DITemplateTypeParameter *
00334 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
00335                                        DIType *Ty) {
00336   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
00337   return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
00338 }
00339 
00340 static DITemplateValueParameter *
00341 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
00342                                    DIScope *Context, StringRef Name, DIType *Ty,
00343                                    Metadata *MD) {
00344   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
00345   return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
00346                                        MD);
00347 }
00348 
00349 DITemplateValueParameter *
00350 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
00351                                         DIType *Ty, Constant *Val) {
00352   return createTemplateValueParameterHelper(
00353       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
00354       getConstantOrNull(Val));
00355 }
00356 
00357 DITemplateValueParameter *
00358 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
00359                                            DIType *Ty, StringRef Val) {
00360   return createTemplateValueParameterHelper(
00361       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
00362       MDString::get(VMContext, Val));
00363 }
00364 
00365 DITemplateValueParameter *
00366 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
00367                                        DIType *Ty, DINodeArray Val) {
00368   return createTemplateValueParameterHelper(
00369       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
00370       Val.get());
00371 }
00372 
00373 DICompositeType *DIBuilder::createClassType(
00374     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
00375     uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
00376     unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
00377     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
00378   assert((!Context || isa<DIScope>(Context)) &&
00379          "createClassType should be called with a valid Context");
00380 
00381   auto *R = DICompositeType::get(
00382       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
00383       DIScopeRef::get(getNonCompileUnitScope(Context)),
00384       DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
00385       Elements, 0, DITypeRef::get(VTableHolder),
00386       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
00387   if (!UniqueIdentifier.empty())
00388     retainType(R);
00389   trackIfUnresolved(R);
00390   return R;
00391 }
00392 
00393 DICompositeType *DIBuilder::createStructType(
00394     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
00395     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
00396     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
00397     DIType *VTableHolder, StringRef UniqueIdentifier) {
00398   auto *R = DICompositeType::get(
00399       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
00400       DIScopeRef::get(getNonCompileUnitScope(Context)),
00401       DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
00402       RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
00403   if (!UniqueIdentifier.empty())
00404     retainType(R);
00405   trackIfUnresolved(R);
00406   return R;
00407 }
00408 
00409 DICompositeType *DIBuilder::createUnionType(
00410     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
00411     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
00412     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
00413   auto *R = DICompositeType::get(
00414       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
00415       DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
00416       AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
00417       UniqueIdentifier);
00418   if (!UniqueIdentifier.empty())
00419     retainType(R);
00420   trackIfUnresolved(R);
00421   return R;
00422 }
00423 
00424 DISubroutineType *DIBuilder::createSubroutineType(DIFile *File,
00425                                                   DITypeRefArray ParameterTypes,
00426                                                   unsigned Flags) {
00427   return DISubroutineType::get(VMContext, Flags, ParameterTypes);
00428 }
00429 
00430 DICompositeType *DIBuilder::createEnumerationType(
00431     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
00432     uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
00433     DIType *UnderlyingType, StringRef UniqueIdentifier) {
00434   auto *CTy = DICompositeType::get(
00435       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
00436       DIScopeRef::get(getNonCompileUnitScope(Scope)),
00437       DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
00438       0, nullptr, nullptr, UniqueIdentifier);
00439   AllEnumTypes.push_back(CTy);
00440   if (!UniqueIdentifier.empty())
00441     retainType(CTy);
00442   trackIfUnresolved(CTy);
00443   return CTy;
00444 }
00445 
00446 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
00447                                             DIType *Ty,
00448                                             DINodeArray Subscripts) {
00449   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
00450                                  nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
00451                                  AlignInBits, 0, 0, Subscripts, 0, nullptr);
00452   trackIfUnresolved(R);
00453   return R;
00454 }
00455 
00456 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
00457                                              uint64_t AlignInBits, DIType *Ty,
00458                                              DINodeArray Subscripts) {
00459   auto *R =
00460       DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
00461                            nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
00462                            DINode::FlagVector, Subscripts, 0, nullptr);
00463   trackIfUnresolved(R);
00464   return R;
00465 }
00466 
00467 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
00468                                    unsigned FlagsToSet) {
00469   auto NewTy = Ty->clone();
00470   NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
00471   return MDNode::replaceWithUniqued(std::move(NewTy));
00472 }
00473 
00474 DIType *DIBuilder::createArtificialType(DIType *Ty) {
00475   // FIXME: Restrict this to the nodes where it's valid.
00476   if (Ty->isArtificial())
00477     return Ty;
00478   return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
00479 }
00480 
00481 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
00482   // FIXME: Restrict this to the nodes where it's valid.
00483   if (Ty->isObjectPointer())
00484     return Ty;
00485   unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
00486   return createTypeWithFlags(VMContext, Ty, Flags);
00487 }
00488 
00489 void DIBuilder::retainType(DIType *T) {
00490   assert(T && "Expected non-null type");
00491   AllRetainTypes.emplace_back(T);
00492 }
00493 
00494 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
00495 
00496 DICompositeType *
00497 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
00498                              DIFile *F, unsigned Line, unsigned RuntimeLang,
00499                              uint64_t SizeInBits, uint64_t AlignInBits,
00500                              StringRef UniqueIdentifier) {
00501   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
00502   // replaceWithUniqued().
00503   auto *RetTy = DICompositeType::get(
00504       VMContext, Tag, Name, F, Line,
00505       DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
00506       AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
00507       nullptr, UniqueIdentifier);
00508   if (!UniqueIdentifier.empty())
00509     retainType(RetTy);
00510   trackIfUnresolved(RetTy);
00511   return RetTy;
00512 }
00513 
00514 DICompositeType *DIBuilder::createReplaceableCompositeType(
00515     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
00516     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
00517     unsigned Flags, StringRef UniqueIdentifier) {
00518   auto *RetTy = DICompositeType::getTemporary(
00519                     VMContext, Tag, Name, F, Line,
00520                     DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
00521                     SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
00522                     nullptr, nullptr, UniqueIdentifier)
00523                     .release();
00524   if (!UniqueIdentifier.empty())
00525     retainType(RetTy);
00526   trackIfUnresolved(RetTy);
00527   return RetTy;
00528 }
00529 
00530 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
00531   return MDTuple::get(VMContext, Elements);
00532 }
00533 
00534 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
00535   SmallVector<llvm::Metadata *, 16> Elts;
00536   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
00537     if (Elements[i] && isa<MDNode>(Elements[i]))
00538       Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
00539     else
00540       Elts.push_back(Elements[i]);
00541   }
00542   return DITypeRefArray(MDNode::get(VMContext, Elts));
00543 }
00544 
00545 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
00546   return DISubrange::get(VMContext, Count, Lo);
00547 }
00548 
00549 static void checkGlobalVariableScope(DIScope *Context) {
00550 #ifndef NDEBUG
00551   if (auto *CT =
00552           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
00553     assert(CT->getIdentifier().empty() &&
00554            "Context of a global variable should not be a type with identifier");
00555 #endif
00556 }
00557 
00558 DIGlobalVariable *DIBuilder::createGlobalVariable(
00559     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
00560     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
00561     MDNode *Decl) {
00562   checkGlobalVariableScope(Context);
00563 
00564   auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
00565                                   Name, LinkageName, F, LineNumber,
00566                                   DITypeRef::get(Ty), isLocalToUnit, true, Val,
00567                                   cast_or_null<DIDerivedType>(Decl));
00568   AllGVs.push_back(N);
00569   return N;
00570 }
00571 
00572 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
00573     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
00574     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
00575     MDNode *Decl) {
00576   checkGlobalVariableScope(Context);
00577 
00578   return DIGlobalVariable::getTemporary(
00579              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
00580              LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
00581              cast_or_null<DIDerivedType>(Decl))
00582       .release();
00583 }
00584 
00585 DILocalVariable *DIBuilder::createLocalVariable(
00586     unsigned Tag, DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
00587     DIType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
00588   // FIXME: Why getNonCompileUnitScope()?
00589   // FIXME: Why is "!Context" okay here?
00590   // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
00591   // the only valid scopes)?
00592   DIScope *Context = getNonCompileUnitScope(Scope);
00593 
00594   auto *Node = DILocalVariable::get(
00595       VMContext, Tag, cast_or_null<DILocalScope>(Context), Name, File, LineNo,
00596       DITypeRef::get(Ty), ArgNo, Flags);
00597   if (AlwaysPreserve) {
00598     // The optimizer may remove local variable. If there is an interest
00599     // to preserve variable info in such situation then stash it in a
00600     // named mdnode.
00601     DISubprogram *Fn = getDISubprogram(Scope);
00602     assert(Fn && "Missing subprogram for local variable");
00603     PreservedVariables[Fn].emplace_back(Node);
00604   }
00605   return Node;
00606 }
00607 
00608 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
00609   return DIExpression::get(VMContext, Addr);
00610 }
00611 
00612 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
00613   // TODO: Remove the callers of this signed version and delete.
00614   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
00615   return createExpression(Addr);
00616 }
00617 
00618 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
00619                                                   unsigned SizeInBytes) {
00620   uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
00621   return DIExpression::get(VMContext, Addr);
00622 }
00623 
00624 DISubprogram *DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
00625                                         StringRef LinkageName, DIFile *File,
00626                                         unsigned LineNo, DISubroutineType *Ty,
00627                                         bool isLocalToUnit, bool isDefinition,
00628                                         unsigned ScopeLine, unsigned Flags,
00629                                         bool isOptimized, Function *Fn,
00630                                         MDNode *TParams, MDNode *Decl) {
00631   // dragonegg does not generate identifier for types, so using an empty map
00632   // to resolve the context should be fine.
00633   DITypeIdentifierMap EmptyMap;
00634   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
00635                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
00636                         Flags, isOptimized, Fn, TParams, Decl);
00637 }
00638 
00639 DISubprogram *DIBuilder::createFunction(DIScope *Context, StringRef Name,
00640                                         StringRef LinkageName, DIFile *File,
00641                                         unsigned LineNo, DISubroutineType *Ty,
00642                                         bool isLocalToUnit, bool isDefinition,
00643                                         unsigned ScopeLine, unsigned Flags,
00644                                         bool isOptimized, Function *Fn,
00645                                         MDNode *TParams, MDNode *Decl) {
00646   assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
00647          "function types should be subroutines");
00648   auto *Node = DISubprogram::get(
00649       VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
00650       LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
00651       nullptr, 0, 0, Flags, isOptimized, Fn, cast_or_null<MDTuple>(TParams),
00652       cast_or_null<DISubprogram>(Decl),
00653       MDTuple::getTemporary(VMContext, None).release());
00654 
00655   if (isDefinition)
00656     AllSubprograms.push_back(Node);
00657   trackIfUnresolved(Node);
00658   return Node;
00659 }
00660 
00661 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
00662     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
00663     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
00664     bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
00665     Function *Fn, MDNode *TParams, MDNode *Decl) {
00666   return DISubprogram::getTemporary(
00667              VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
00668              LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
00669              ScopeLine, nullptr, 0, 0, Flags, isOptimized, Fn,
00670              cast_or_null<MDTuple>(TParams), cast_or_null<DISubprogram>(Decl),
00671              nullptr)
00672       .release();
00673 }
00674 
00675 DISubprogram *
00676 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
00677                         DIFile *F, unsigned LineNo, DISubroutineType *Ty,
00678                         bool isLocalToUnit, bool isDefinition, unsigned VK,
00679                         unsigned VIndex, DIType *VTableHolder, unsigned Flags,
00680                         bool isOptimized, Function *Fn, MDNode *TParam) {
00681   assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
00682          "function types should be subroutines");
00683   assert(getNonCompileUnitScope(Context) &&
00684          "Methods should have both a Context and a context that isn't "
00685          "the compile unit.");
00686   // FIXME: Do we want to use different scope/lines?
00687   auto *SP = DISubprogram::get(
00688       VMContext, DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F,
00689       LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
00690       DITypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
00691       cast_or_null<MDTuple>(TParam), nullptr, nullptr);
00692 
00693   if (isDefinition)
00694     AllSubprograms.push_back(SP);
00695   trackIfUnresolved(SP);
00696   return SP;
00697 }
00698 
00699 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
00700                                         DIFile *File, unsigned LineNo) {
00701   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
00702                           LineNo);
00703 }
00704 
00705 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
00706                                                       DIFile *File,
00707                                                       unsigned Discriminator) {
00708   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
00709 }
00710 
00711 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
00712                                               unsigned Line, unsigned Col) {
00713   // Make these distinct, to avoid merging two lexical blocks on the same
00714   // file/line/column.
00715   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
00716                                      File, Line, Col);
00717 }
00718 
00719 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
00720   assert(V && "no value passed to dbg intrinsic");
00721   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
00722 }
00723 
00724 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
00725   I->setDebugLoc(const_cast<DILocation *>(DL));
00726   return I;
00727 }
00728 
00729 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
00730                                       DIExpression *Expr, const DILocation *DL,
00731                                       Instruction *InsertBefore) {
00732   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
00733   assert(DL && "Expected debug loc");
00734   assert(DL->getScope()->getSubprogram() ==
00735              VarInfo->getScope()->getSubprogram() &&
00736          "Expected matching subprograms");
00737   if (!DeclareFn)
00738     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
00739 
00740   trackIfUnresolved(VarInfo);
00741   trackIfUnresolved(Expr);
00742   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
00743                    MetadataAsValue::get(VMContext, VarInfo),
00744                    MetadataAsValue::get(VMContext, Expr)};
00745   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
00746 }
00747 
00748 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
00749                                       DIExpression *Expr, const DILocation *DL,
00750                                       BasicBlock *InsertAtEnd) {
00751   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
00752   assert(DL && "Expected debug loc");
00753   assert(DL->getScope()->getSubprogram() ==
00754              VarInfo->getScope()->getSubprogram() &&
00755          "Expected matching subprograms");
00756   if (!DeclareFn)
00757     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
00758 
00759   trackIfUnresolved(VarInfo);
00760   trackIfUnresolved(Expr);
00761   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
00762                    MetadataAsValue::get(VMContext, VarInfo),
00763                    MetadataAsValue::get(VMContext, Expr)};
00764 
00765   // If this block already has a terminator then insert this intrinsic
00766   // before the terminator.
00767   if (TerminatorInst *T = InsertAtEnd->getTerminator())
00768     return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
00769   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
00770 }
00771 
00772 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
00773                                                 DILocalVariable *VarInfo,
00774                                                 DIExpression *Expr,
00775                                                 const DILocation *DL,
00776                                                 Instruction *InsertBefore) {
00777   assert(V && "no value passed to dbg.value");
00778   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
00779   assert(DL && "Expected debug loc");
00780   assert(DL->getScope()->getSubprogram() ==
00781              VarInfo->getScope()->getSubprogram() &&
00782          "Expected matching subprograms");
00783   if (!ValueFn)
00784     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
00785 
00786   trackIfUnresolved(VarInfo);
00787   trackIfUnresolved(Expr);
00788   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
00789                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
00790                    MetadataAsValue::get(VMContext, VarInfo),
00791                    MetadataAsValue::get(VMContext, Expr)};
00792   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
00793 }
00794 
00795 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
00796                                                 DILocalVariable *VarInfo,
00797                                                 DIExpression *Expr,
00798                                                 const DILocation *DL,
00799                                                 BasicBlock *InsertAtEnd) {
00800   assert(V && "no value passed to dbg.value");
00801   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
00802   assert(DL && "Expected debug loc");
00803   assert(DL->getScope()->getSubprogram() ==
00804              VarInfo->getScope()->getSubprogram() &&
00805          "Expected matching subprograms");
00806   if (!ValueFn)
00807     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
00808 
00809   trackIfUnresolved(VarInfo);
00810   trackIfUnresolved(Expr);
00811   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
00812                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
00813                    MetadataAsValue::get(VMContext, VarInfo),
00814                    MetadataAsValue::get(VMContext, Expr)};
00815 
00816   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
00817 }
00818 
00819 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
00820                                     DICompositeType *VTableHolder) {
00821   {
00822     TypedTrackingMDRef<DICompositeType> N(T);
00823     N->replaceVTableHolder(DITypeRef::get(VTableHolder));
00824     T = N.get();
00825   }
00826 
00827   // If this didn't create a self-reference, just return.
00828   if (T != VTableHolder)
00829     return;
00830 
00831   // Look for unresolved operands.  T will drop RAUW support, orphaning any
00832   // cycles underneath it.
00833   if (T->isResolved())
00834     for (const MDOperand &O : T->operands())
00835       if (auto *N = dyn_cast_or_null<MDNode>(O))
00836         trackIfUnresolved(N);
00837 }
00838 
00839 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
00840                               DINodeArray TParams) {
00841   {
00842     TypedTrackingMDRef<DICompositeType> N(T);
00843     if (Elements)
00844       N->replaceElements(Elements);
00845     if (TParams)
00846       N->replaceTemplateParams(DITemplateParameterArray(TParams));
00847     T = N.get();
00848   }
00849 
00850   // If T isn't resolved, there's no problem.
00851   if (!T->isResolved())
00852     return;
00853 
00854   // If "T" is resolved, it may be due to a self-reference cycle.  Track the
00855   // arrays explicitly if they're unresolved, or else the cycles will be
00856   // orphaned.
00857   if (Elements)
00858     trackIfUnresolved(Elements.get());
00859   if (TParams)
00860     trackIfUnresolved(TParams.get());
00861 }