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