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,
00331                              DITypeRef::get(Ty));
00332 }
00333 
00334 DITemplateTypeParameter *
00335 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
00336                                        DIType *Ty) {
00337   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
00338   return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
00339 }
00340 
00341 static DITemplateValueParameter *
00342 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
00343                                    DIScope *Context, StringRef Name, DIType *Ty,
00344                                    Metadata *MD) {
00345   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
00346   return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
00347                                        MD);
00348 }
00349 
00350 DITemplateValueParameter *
00351 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
00352                                         DIType *Ty, Constant *Val) {
00353   return createTemplateValueParameterHelper(
00354       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
00355       getConstantOrNull(Val));
00356 }
00357 
00358 DITemplateValueParameter *
00359 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
00360                                            DIType *Ty, StringRef Val) {
00361   return createTemplateValueParameterHelper(
00362       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
00363       MDString::get(VMContext, Val));
00364 }
00365 
00366 DITemplateValueParameter *
00367 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
00368                                        DIType *Ty, DINodeArray Val) {
00369   return createTemplateValueParameterHelper(
00370       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
00371       Val.get());
00372 }
00373 
00374 DICompositeType *DIBuilder::createClassType(
00375     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
00376     uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
00377     unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
00378     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
00379   assert((!Context || isa<DIScope>(Context)) &&
00380          "createClassType should be called with a valid Context");
00381 
00382   auto *R = DICompositeType::get(
00383       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
00384       DIScopeRef::get(getNonCompileUnitScope(Context)),
00385       DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
00386       Elements, 0, DITypeRef::get(VTableHolder),
00387       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
00388   if (!UniqueIdentifier.empty())
00389     retainType(R);
00390   trackIfUnresolved(R);
00391   return R;
00392 }
00393 
00394 DICompositeType *DIBuilder::createStructType(
00395     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
00396     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
00397     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
00398     DIType *VTableHolder, StringRef UniqueIdentifier) {
00399   auto *R = DICompositeType::get(
00400       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
00401       DIScopeRef::get(getNonCompileUnitScope(Context)),
00402       DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
00403       RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
00404   if (!UniqueIdentifier.empty())
00405     retainType(R);
00406   trackIfUnresolved(R);
00407   return R;
00408 }
00409 
00410 DICompositeType *DIBuilder::createUnionType(
00411     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
00412     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
00413     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
00414   auto *R = DICompositeType::get(
00415       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
00416       DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
00417       AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
00418       UniqueIdentifier);
00419   if (!UniqueIdentifier.empty())
00420     retainType(R);
00421   trackIfUnresolved(R);
00422   return R;
00423 }
00424 
00425 DISubroutineType *DIBuilder::createSubroutineType(DIFile *File,
00426                                                   DITypeRefArray ParameterTypes,
00427                                                   unsigned Flags) {
00428   return DISubroutineType::get(VMContext, Flags, ParameterTypes);
00429 }
00430 
00431 DICompositeType *DIBuilder::createEnumerationType(
00432     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
00433     uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
00434     DIType *UnderlyingType, StringRef UniqueIdentifier) {
00435   auto *CTy = DICompositeType::get(
00436       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
00437       DIScopeRef::get(getNonCompileUnitScope(Scope)),
00438       DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
00439       0, nullptr, nullptr, UniqueIdentifier);
00440   AllEnumTypes.push_back(CTy);
00441   if (!UniqueIdentifier.empty())
00442     retainType(CTy);
00443   trackIfUnresolved(CTy);
00444   return CTy;
00445 }
00446 
00447 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
00448                                             DIType *Ty,
00449                                             DINodeArray Subscripts) {
00450   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
00451                                  nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
00452                                  AlignInBits, 0, 0, Subscripts, 0, nullptr);
00453   trackIfUnresolved(R);
00454   return R;
00455 }
00456 
00457 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
00458                                              uint64_t AlignInBits, DIType *Ty,
00459                                              DINodeArray Subscripts) {
00460   auto *R =
00461       DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
00462                            nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
00463                            DINode::FlagVector, Subscripts, 0, nullptr);
00464   trackIfUnresolved(R);
00465   return R;
00466 }
00467 
00468 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
00469                                    unsigned FlagsToSet) {
00470   auto NewTy = Ty->clone();
00471   NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
00472   return MDNode::replaceWithUniqued(std::move(NewTy));
00473 }
00474 
00475 DIType *DIBuilder::createArtificialType(DIType *Ty) {
00476   // FIXME: Restrict this to the nodes where it's valid.
00477   if (Ty->isArtificial())
00478     return Ty;
00479   return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
00480 }
00481 
00482 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
00483   // FIXME: Restrict this to the nodes where it's valid.
00484   if (Ty->isObjectPointer())
00485     return Ty;
00486   unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
00487   return createTypeWithFlags(VMContext, Ty, Flags);
00488 }
00489 
00490 void DIBuilder::retainType(DIType *T) {
00491   assert(T && "Expected non-null type");
00492   AllRetainTypes.emplace_back(T);
00493 }
00494 
00495 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
00496 
00497 DICompositeType *
00498 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
00499                              DIFile *F, unsigned Line, unsigned RuntimeLang,
00500                              uint64_t SizeInBits, uint64_t AlignInBits,
00501                              StringRef UniqueIdentifier) {
00502   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
00503   // replaceWithUniqued().
00504   auto *RetTy = DICompositeType::get(
00505       VMContext, Tag, Name, F, Line,
00506       DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
00507       AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
00508       nullptr, UniqueIdentifier);
00509   if (!UniqueIdentifier.empty())
00510     retainType(RetTy);
00511   trackIfUnresolved(RetTy);
00512   return RetTy;
00513 }
00514 
00515 DICompositeType *DIBuilder::createReplaceableCompositeType(
00516     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
00517     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
00518     unsigned Flags, StringRef UniqueIdentifier) {
00519   auto *RetTy = DICompositeType::getTemporary(
00520                     VMContext, Tag, Name, F, Line,
00521                     DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
00522                     SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
00523                     nullptr, nullptr, UniqueIdentifier)
00524                     .release();
00525   if (!UniqueIdentifier.empty())
00526     retainType(RetTy);
00527   trackIfUnresolved(RetTy);
00528   return RetTy;
00529 }
00530 
00531 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
00532   return MDTuple::get(VMContext, Elements);
00533 }
00534 
00535 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
00536   SmallVector<llvm::Metadata *, 16> Elts;
00537   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
00538     if (Elements[i] && isa<MDNode>(Elements[i]))
00539       Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
00540     else
00541       Elts.push_back(Elements[i]);
00542   }
00543   return DITypeRefArray(MDNode::get(VMContext, Elts));
00544 }
00545 
00546 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
00547   return DISubrange::get(VMContext, Count, Lo);
00548 }
00549 
00550 static void checkGlobalVariableScope(DIScope *Context) {
00551 #ifndef NDEBUG
00552   if (auto *CT =
00553           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
00554     assert(CT->getIdentifier().empty() &&
00555            "Context of a global variable should not be a type with identifier");
00556 #endif
00557 }
00558 
00559 DIGlobalVariable *DIBuilder::createGlobalVariable(
00560     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
00561     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
00562     MDNode *Decl) {
00563   checkGlobalVariableScope(Context);
00564 
00565   auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
00566                                   Name, LinkageName, F, LineNumber,
00567                                   DITypeRef::get(Ty), isLocalToUnit, true, Val,
00568                                   cast_or_null<DIDerivedType>(Decl));
00569   AllGVs.push_back(N);
00570   return N;
00571 }
00572 
00573 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
00574     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
00575     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
00576     MDNode *Decl) {
00577   checkGlobalVariableScope(Context);
00578 
00579   return DIGlobalVariable::getTemporary(
00580              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
00581              LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
00582              cast_or_null<DIDerivedType>(Decl))
00583       .release();
00584 }
00585 
00586 DILocalVariable *DIBuilder::createLocalVariable(
00587     unsigned Tag, DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
00588     DIType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
00589   // FIXME: Why getNonCompileUnitScope()?
00590   // FIXME: Why is "!Context" okay here?
00591   // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
00592   // the only valid scopes)?
00593   DIScope *Context = getNonCompileUnitScope(Scope);
00594 
00595   auto *Node = DILocalVariable::get(
00596       VMContext, Tag, cast_or_null<DILocalScope>(Context), Name, File, LineNo,
00597       DITypeRef::get(Ty), ArgNo, Flags);
00598   if (AlwaysPreserve) {
00599     // The optimizer may remove local variable. If there is an interest
00600     // to preserve variable info in such situation then stash it in a
00601     // named mdnode.
00602     DISubprogram *Fn = getDISubprogram(Scope);
00603     assert(Fn && "Missing subprogram for local variable");
00604     PreservedVariables[Fn].emplace_back(Node);
00605   }
00606   return Node;
00607 }
00608 
00609 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
00610   return DIExpression::get(VMContext, Addr);
00611 }
00612 
00613 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
00614   // TODO: Remove the callers of this signed version and delete.
00615   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
00616   return createExpression(Addr);
00617 }
00618 
00619 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
00620                                                   unsigned SizeInBytes) {
00621   uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
00622   return DIExpression::get(VMContext, Addr);
00623 }
00624 
00625 DISubprogram *DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
00626                                         StringRef LinkageName, DIFile *File,
00627                                         unsigned LineNo, DISubroutineType *Ty,
00628                                         bool isLocalToUnit, bool isDefinition,
00629                                         unsigned ScopeLine, unsigned Flags,
00630                                         bool isOptimized, Function *Fn,
00631                                         MDNode *TParams, MDNode *Decl) {
00632   // dragonegg does not generate identifier for types, so using an empty map
00633   // to resolve the context should be fine.
00634   DITypeIdentifierMap EmptyMap;
00635   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
00636                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
00637                         Flags, isOptimized, Fn, TParams, Decl);
00638 }
00639 
00640 DISubprogram *DIBuilder::createFunction(DIScope *Context, StringRef Name,
00641                                         StringRef LinkageName, DIFile *File,
00642                                         unsigned LineNo, DISubroutineType *Ty,
00643                                         bool isLocalToUnit, bool isDefinition,
00644                                         unsigned ScopeLine, unsigned Flags,
00645                                         bool isOptimized, Function *Fn,
00646                                         MDNode *TParams, MDNode *Decl) {
00647   assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
00648          "function types should be subroutines");
00649   auto *Node = DISubprogram::get(
00650       VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
00651       LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
00652       nullptr, 0, 0, Flags, isOptimized, Fn, cast_or_null<MDTuple>(TParams),
00653       cast_or_null<DISubprogram>(Decl),
00654       MDTuple::getTemporary(VMContext, None).release());
00655 
00656   if (isDefinition)
00657     AllSubprograms.push_back(Node);
00658   trackIfUnresolved(Node);
00659   return Node;
00660 }
00661 
00662 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
00663     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
00664     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
00665     bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
00666     Function *Fn, MDNode *TParams, MDNode *Decl) {
00667   return DISubprogram::getTemporary(
00668              VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
00669              LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
00670              ScopeLine, nullptr, 0, 0, Flags, isOptimized, Fn,
00671              cast_or_null<MDTuple>(TParams), cast_or_null<DISubprogram>(Decl),
00672              nullptr)
00673       .release();
00674 }
00675 
00676 DISubprogram *
00677 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
00678                         DIFile *F, unsigned LineNo, DISubroutineType *Ty,
00679                         bool isLocalToUnit, bool isDefinition, unsigned VK,
00680                         unsigned VIndex, DIType *VTableHolder, unsigned Flags,
00681                         bool isOptimized, Function *Fn, MDNode *TParam) {
00682   assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
00683          "function types should be subroutines");
00684   assert(getNonCompileUnitScope(Context) &&
00685          "Methods should have both a Context and a context that isn't "
00686          "the compile unit.");
00687   // FIXME: Do we want to use different scope/lines?
00688   auto *SP = DISubprogram::get(
00689       VMContext, DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F,
00690       LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
00691       DITypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
00692       cast_or_null<MDTuple>(TParam), nullptr, nullptr);
00693 
00694   if (isDefinition)
00695     AllSubprograms.push_back(SP);
00696   trackIfUnresolved(SP);
00697   return SP;
00698 }
00699 
00700 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
00701                                         DIFile *File, unsigned LineNo) {
00702   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
00703                           LineNo);
00704 }
00705 
00706 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
00707                                                       DIFile *File,
00708                                                       unsigned Discriminator) {
00709   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
00710 }
00711 
00712 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
00713                                               unsigned Line, unsigned Col) {
00714   // Make these distinct, to avoid merging two lexical blocks on the same
00715   // file/line/column.
00716   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
00717                                      File, Line, Col);
00718 }
00719 
00720 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
00721   assert(V && "no value passed to dbg intrinsic");
00722   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
00723 }
00724 
00725 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
00726   I->setDebugLoc(const_cast<DILocation *>(DL));
00727   return I;
00728 }
00729 
00730 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
00731                                       DIExpression *Expr, const DILocation *DL,
00732                                       Instruction *InsertBefore) {
00733   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
00734   assert(DL && "Expected debug loc");
00735   assert(DL->getScope()->getSubprogram() ==
00736              VarInfo->getScope()->getSubprogram() &&
00737          "Expected matching subprograms");
00738   if (!DeclareFn)
00739     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
00740 
00741   trackIfUnresolved(VarInfo);
00742   trackIfUnresolved(Expr);
00743   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
00744                    MetadataAsValue::get(VMContext, VarInfo),
00745                    MetadataAsValue::get(VMContext, Expr)};
00746   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
00747 }
00748 
00749 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
00750                                       DIExpression *Expr, const DILocation *DL,
00751                                       BasicBlock *InsertAtEnd) {
00752   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
00753   assert(DL && "Expected debug loc");
00754   assert(DL->getScope()->getSubprogram() ==
00755              VarInfo->getScope()->getSubprogram() &&
00756          "Expected matching subprograms");
00757   if (!DeclareFn)
00758     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
00759 
00760   trackIfUnresolved(VarInfo);
00761   trackIfUnresolved(Expr);
00762   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
00763                    MetadataAsValue::get(VMContext, VarInfo),
00764                    MetadataAsValue::get(VMContext, Expr)};
00765 
00766   // If this block already has a terminator then insert this intrinsic
00767   // before the terminator.
00768   if (TerminatorInst *T = InsertAtEnd->getTerminator())
00769     return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
00770   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
00771 }
00772 
00773 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
00774                                                 DILocalVariable *VarInfo,
00775                                                 DIExpression *Expr,
00776                                                 const DILocation *DL,
00777                                                 Instruction *InsertBefore) {
00778   assert(V && "no value passed to dbg.value");
00779   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
00780   assert(DL && "Expected debug loc");
00781   assert(DL->getScope()->getSubprogram() ==
00782              VarInfo->getScope()->getSubprogram() &&
00783          "Expected matching subprograms");
00784   if (!ValueFn)
00785     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
00786 
00787   trackIfUnresolved(VarInfo);
00788   trackIfUnresolved(Expr);
00789   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
00790                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
00791                    MetadataAsValue::get(VMContext, VarInfo),
00792                    MetadataAsValue::get(VMContext, Expr)};
00793   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
00794 }
00795 
00796 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
00797                                                 DILocalVariable *VarInfo,
00798                                                 DIExpression *Expr,
00799                                                 const DILocation *DL,
00800                                                 BasicBlock *InsertAtEnd) {
00801   assert(V && "no value passed to dbg.value");
00802   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
00803   assert(DL && "Expected debug loc");
00804   assert(DL->getScope()->getSubprogram() ==
00805              VarInfo->getScope()->getSubprogram() &&
00806          "Expected matching subprograms");
00807   if (!ValueFn)
00808     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
00809 
00810   trackIfUnresolved(VarInfo);
00811   trackIfUnresolved(Expr);
00812   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
00813                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
00814                    MetadataAsValue::get(VMContext, VarInfo),
00815                    MetadataAsValue::get(VMContext, Expr)};
00816 
00817   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
00818 }
00819 
00820 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
00821                                     DICompositeType *VTableHolder) {
00822   {
00823     TypedTrackingMDRef<DICompositeType> N(T);
00824     N->replaceVTableHolder(DITypeRef::get(VTableHolder));
00825     T = N.get();
00826   }
00827 
00828   // If this didn't create a self-reference, just return.
00829   if (T != VTableHolder)
00830     return;
00831 
00832   // Look for unresolved operands.  T will drop RAUW support, orphaning any
00833   // cycles underneath it.
00834   if (T->isResolved())
00835     for (const MDOperand &O : T->operands())
00836       if (auto *N = dyn_cast_or_null<MDNode>(O))
00837         trackIfUnresolved(N);
00838 }
00839 
00840 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
00841                               DINodeArray TParams) {
00842   {
00843     TypedTrackingMDRef<DICompositeType> N(T);
00844     if (Elements)
00845       N->replaceElements(Elements);
00846     if (TParams)
00847       N->replaceTemplateParams(DITemplateParameterArray(TParams));
00848     T = N.get();
00849   }
00850 
00851   // If T isn't resolved, there's no problem.
00852   if (!T->isResolved())
00853     return;
00854 
00855   // If "T" is resolved, it may be due to a self-reference cycle.  Track the
00856   // arrays explicitly if they're unresolved, or else the cycles will be
00857   // orphaned.
00858   if (Elements)
00859     trackIfUnresolved(Elements.get());
00860   if (TParams)
00861     trackIfUnresolved(TParams.get());
00862 }