LLVM API Documentation

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       SmallVector<Metadata *, 4> Variables;
00098       for (Metadata *V : PreservedVariables.lookup(SP))
00099         Variables.push_back(V);
00100       DIArray AV = getOrCreateArray(Variables);
00101       DIType(Temp).replaceAllUsesWith(AV);
00102     }
00103   }
00104 
00105   DIArray GVs = getOrCreateArray(AllGVs);
00106   DIType(TempGVs).replaceAllUsesWith(GVs);
00107 
00108   SmallVector<Metadata *, 16> RetainValuesI;
00109   for (unsigned I = 0, E = AllImportedModules.size(); I < E; I++)
00110     RetainValuesI.push_back(AllImportedModules[I]);
00111   DIArray IMs = getOrCreateArray(RetainValuesI);
00112   DIType(TempImportedModules).replaceAllUsesWith(IMs);
00113 
00114   // Now that all temp nodes have been replaced or deleted, resolve remaining
00115   // cycles.
00116   for (const auto &N : UnresolvedNodes)
00117     if (N && !N->isResolved())
00118       N->resolveCycles();
00119   UnresolvedNodes.clear();
00120 
00121   // Can't handle unresolved nodes anymore.
00122   AllowUnresolvedNodes = false;
00123 }
00124 
00125 /// If N is compile unit return NULL otherwise return N.
00126 static MDNode *getNonCompileUnitScope(MDNode *N) {
00127   if (DIDescriptor(N).isCompileUnit())
00128     return nullptr;
00129   return N;
00130 }
00131 
00132 static MDNode *createFilePathPair(LLVMContext &VMContext, StringRef Filename,
00133                                   StringRef Directory) {
00134   assert(!Filename.empty() && "Unable to create file without name");
00135   Metadata *Pair[] = {MDString::get(VMContext, Filename),
00136                       MDString::get(VMContext, Directory)};
00137   return MDNode::get(VMContext, Pair);
00138 }
00139 
00140 DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
00141                                            StringRef Directory,
00142                                            StringRef Producer, bool isOptimized,
00143                                            StringRef Flags, unsigned RunTimeVer,
00144                                            StringRef SplitName,
00145                                            DebugEmissionKind Kind,
00146                                            bool EmitDebugInfo) {
00147 
00148   assert(((Lang <= dwarf::DW_LANG_OCaml && Lang >= dwarf::DW_LANG_C89) ||
00149           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
00150          "Invalid Language tag");
00151   assert(!Filename.empty() &&
00152          "Unable to create compile unit without filename");
00153   Metadata *TElts[] = {HeaderBuilder::get(DW_TAG_base_type).get(VMContext)};
00154   TempEnumTypes = MDNode::getTemporary(VMContext, TElts).release();
00155 
00156   TempRetainTypes = MDNode::getTemporary(VMContext, TElts).release();
00157 
00158   TempSubprograms = MDNode::getTemporary(VMContext, TElts).release();
00159 
00160   TempGVs = MDNode::getTemporary(VMContext, TElts).release();
00161 
00162   TempImportedModules = MDNode::getTemporary(VMContext, TElts).release();
00163 
00164   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_compile_unit)
00165                           .concat(Lang)
00166                           .concat(Producer)
00167                           .concat(isOptimized)
00168                           .concat(Flags)
00169                           .concat(RunTimeVer)
00170                           .concat(SplitName)
00171                           .concat(Kind)
00172                           .get(VMContext),
00173                       createFilePathPair(VMContext, Filename, Directory),
00174                       TempEnumTypes, TempRetainTypes, TempSubprograms, TempGVs,
00175                       TempImportedModules};
00176 
00177   MDNode *CUNode = MDNode::get(VMContext, Elts);
00178 
00179   // Create a named metadata so that it is easier to find cu in a module.
00180   // Note that we only generate this when the caller wants to actually
00181   // emit debug information. When we are only interested in tracking
00182   // source line locations throughout the backend, we prevent codegen from
00183   // emitting debug info in the final output by not generating llvm.dbg.cu.
00184   if (EmitDebugInfo) {
00185     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
00186     NMD->addOperand(CUNode);
00187   }
00188 
00189   trackIfUnresolved(CUNode);
00190   return DICompileUnit(CUNode);
00191 }
00192 
00193 static DIImportedEntity
00194 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope Context,
00195                      Metadata *NS, unsigned Line, StringRef Name,
00196                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
00197   const MDNode *R;
00198   Metadata *Elts[] = {HeaderBuilder::get(Tag).concat(Line).concat(Name).get(C),
00199                       Context, NS};
00200   R = MDNode::get(C, Elts);
00201   DIImportedEntity M(R);
00202   assert(M.Verify() && "Imported module should be valid");
00203   AllImportedModules.emplace_back(M.get());
00204   return M;
00205 }
00206 
00207 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
00208                                                  DINameSpace NS,
00209                                                  unsigned Line) {
00210   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
00211                                 Context, NS, Line, StringRef(), AllImportedModules);
00212 }
00213 
00214 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
00215                                                  DIImportedEntity NS,
00216                                                  unsigned Line) {
00217   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
00218                                 Context, NS, Line, StringRef(), AllImportedModules);
00219 }
00220 
00221 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
00222                                                       DIDescriptor Decl,
00223                                                       unsigned Line, StringRef Name) {
00224   // Make sure to use the unique identifier based metadata reference for
00225   // types that have one.
00226   Metadata *V =
00227       Decl.isType() ? static_cast<Metadata *>(DIType(Decl).getRef()) : Decl;
00228   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
00229                                 Context, V, Line, Name,
00230                                 AllImportedModules);
00231 }
00232 
00233 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
00234                                                       DIImportedEntity Imp,
00235                                                       unsigned Line, StringRef Name) {
00236   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
00237                                 Context, Imp, Line, Name, AllImportedModules);
00238 }
00239 
00240 DIFile DIBuilder::createFile(StringRef Filename, StringRef Directory) {
00241   Metadata *Elts[] = {
00242       HeaderBuilder::get(dwarf::DW_TAG_file_type).get(VMContext),
00243       createFilePathPair(VMContext, Filename, Directory)};
00244   return DIFile(MDNode::get(VMContext, Elts));
00245 }
00246 
00247 DIEnumerator DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
00248   assert(!Name.empty() && "Unable to create enumerator without name");
00249   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_enumerator)
00250                           .concat(Name)
00251                           .concat(Val)
00252                           .get(VMContext)};
00253   return DIEnumerator(MDNode::get(VMContext, Elts));
00254 }
00255 
00256 DIBasicType DIBuilder::createUnspecifiedType(StringRef Name) {
00257   assert(!Name.empty() && "Unable to create type without name");
00258   // Unspecified types are encoded in DIBasicType format. Line number, filename,
00259   // size, alignment, offset and flags are always empty here.
00260   Metadata *Elts[] = {
00261       HeaderBuilder::get(dwarf::DW_TAG_unspecified_type)
00262           .concat(Name)
00263           .concat(0)
00264           .concat(0)
00265           .concat(0)
00266           .concat(0)
00267           .concat(0)
00268           .concat(0)
00269           .get(VMContext),
00270       nullptr, // Filename
00271       nullptr  // Unused
00272   };
00273   return DIBasicType(MDNode::get(VMContext, Elts));
00274 }
00275 
00276 DIBasicType DIBuilder::createNullPtrType() {
00277   return createUnspecifiedType("decltype(nullptr)");
00278 }
00279 
00280 DIBasicType
00281 DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
00282                            uint64_t AlignInBits, unsigned Encoding) {
00283   assert(!Name.empty() && "Unable to create type without name");
00284   // Basic types are encoded in DIBasicType format. Line number, filename,
00285   // offset and flags are always empty here.
00286   Metadata *Elts[] = {
00287       HeaderBuilder::get(dwarf::DW_TAG_base_type)
00288           .concat(Name)
00289           .concat(0) // Line
00290           .concat(SizeInBits)
00291           .concat(AlignInBits)
00292           .concat(0) // Offset
00293           .concat(0) // Flags
00294           .concat(Encoding)
00295           .get(VMContext),
00296       nullptr, // Filename
00297       nullptr  // Unused
00298   };
00299   return DIBasicType(MDNode::get(VMContext, Elts));
00300 }
00301 
00302 DIDerivedType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
00303   // Qualified types are encoded in DIDerivedType format.
00304   Metadata *Elts[] = {HeaderBuilder::get(Tag)
00305                           .concat(StringRef()) // Name
00306                           .concat(0)           // Line
00307                           .concat(0)           // Size
00308                           .concat(0)           // Align
00309                           .concat(0)           // Offset
00310                           .concat(0)           // Flags
00311                           .get(VMContext),
00312                       nullptr, // Filename
00313                       nullptr, // Unused
00314                       FromTy.getRef()};
00315   return DIDerivedType(MDNode::get(VMContext, Elts));
00316 }
00317 
00318 DIDerivedType
00319 DIBuilder::createPointerType(DIType PointeeTy, uint64_t SizeInBits,
00320                              uint64_t AlignInBits, StringRef Name) {
00321   // Pointer types are encoded in DIDerivedType format.
00322   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_pointer_type)
00323                           .concat(Name)
00324                           .concat(0) // Line
00325                           .concat(SizeInBits)
00326                           .concat(AlignInBits)
00327                           .concat(0) // Offset
00328                           .concat(0) // Flags
00329                           .get(VMContext),
00330                       nullptr, // Filename
00331                       nullptr, // Unused
00332                       PointeeTy.getRef()};
00333   return DIDerivedType(MDNode::get(VMContext, Elts));
00334 }
00335 
00336 DIDerivedType
00337 DIBuilder::createMemberPointerType(DIType PointeeTy, DIType Base,
00338                                    uint64_t SizeInBits, uint64_t AlignInBits) {
00339   // Pointer types are encoded in DIDerivedType format.
00340   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_ptr_to_member_type)
00341                           .concat(StringRef())
00342                           .concat(0) // Line
00343                           .concat(SizeInBits) // Size
00344                           .concat(AlignInBits) // Align
00345                           .concat(0) // Offset
00346                           .concat(0) // Flags
00347                           .get(VMContext),
00348                       nullptr, // Filename
00349                       nullptr, // Unused
00350                       PointeeTy.getRef(), Base.getRef()};
00351   return DIDerivedType(MDNode::get(VMContext, Elts));
00352 }
00353 
00354 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
00355   assert(RTy.isType() && "Unable to create reference type");
00356   // References are encoded in DIDerivedType format.
00357   Metadata *Elts[] = {HeaderBuilder::get(Tag)
00358                           .concat(StringRef()) // Name
00359                           .concat(0)           // Line
00360                           .concat(0)           // Size
00361                           .concat(0)           // Align
00362                           .concat(0)           // Offset
00363                           .concat(0)           // Flags
00364                           .get(VMContext),
00365                       nullptr, // Filename
00366                       nullptr, // TheCU,
00367                       RTy.getRef()};
00368   return DIDerivedType(MDNode::get(VMContext, Elts));
00369 }
00370 
00371 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
00372                                        unsigned LineNo, DIDescriptor Context) {
00373   // typedefs are encoded in DIDerivedType format.
00374   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_typedef)
00375                           .concat(Name)
00376                           .concat(LineNo)
00377                           .concat(0) // Size
00378                           .concat(0) // Align
00379                           .concat(0) // Offset
00380                           .concat(0) // Flags
00381                           .get(VMContext),
00382                       File.getFileNode(),
00383                       DIScope(getNonCompileUnitScope(Context)).getRef(),
00384                       Ty.getRef()};
00385   return DIDerivedType(MDNode::get(VMContext, Elts));
00386 }
00387 
00388 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
00389   // typedefs are encoded in DIDerivedType format.
00390   assert(Ty.isType() && "Invalid type!");
00391   assert(FriendTy.isType() && "Invalid friend type!");
00392   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_friend)
00393                           .concat(StringRef()) // Name
00394                           .concat(0)           // Line
00395                           .concat(0)           // Size
00396                           .concat(0)           // Align
00397                           .concat(0)           // Offset
00398                           .concat(0)           // Flags
00399                           .get(VMContext),
00400                       nullptr, Ty.getRef(), FriendTy.getRef()};
00401   return DIDerivedType(MDNode::get(VMContext, Elts));
00402 }
00403 
00404 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
00405                                            uint64_t BaseOffset,
00406                                            unsigned Flags) {
00407   assert(Ty.isType() && "Unable to create inheritance");
00408   // TAG_inheritance is encoded in DIDerivedType format.
00409   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_inheritance)
00410                           .concat(StringRef()) // Name
00411                           .concat(0)           // Line
00412                           .concat(0)           // Size
00413                           .concat(0)           // Align
00414                           .concat(BaseOffset)
00415                           .concat(Flags)
00416                           .get(VMContext),
00417                       nullptr, Ty.getRef(), BaseTy.getRef()};
00418   return DIDerivedType(MDNode::get(VMContext, Elts));
00419 }
00420 
00421 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
00422                                           DIFile File, unsigned LineNumber,
00423                                           uint64_t SizeInBits,
00424                                           uint64_t AlignInBits,
00425                                           uint64_t OffsetInBits, unsigned Flags,
00426                                           DIType Ty) {
00427   // TAG_member is encoded in DIDerivedType format.
00428   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
00429                           .concat(Name)
00430                           .concat(LineNumber)
00431                           .concat(SizeInBits)
00432                           .concat(AlignInBits)
00433                           .concat(OffsetInBits)
00434                           .concat(Flags)
00435                           .get(VMContext),
00436                       File.getFileNode(),
00437                       DIScope(getNonCompileUnitScope(Scope)).getRef(),
00438                       Ty.getRef()};
00439   return DIDerivedType(MDNode::get(VMContext, Elts));
00440 }
00441 
00442 static Metadata *getConstantOrNull(Constant *C) {
00443   if (C)
00444     return ConstantAsMetadata::get(C);
00445   return nullptr;
00446 }
00447 
00448 DIDerivedType DIBuilder::createStaticMemberType(DIDescriptor Scope,
00449                                                 StringRef Name, DIFile File,
00450                                                 unsigned LineNumber, DIType Ty,
00451                                                 unsigned Flags,
00452                                                 llvm::Constant *Val) {
00453   // TAG_member is encoded in DIDerivedType format.
00454   Flags |= DIDescriptor::FlagStaticMember;
00455   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
00456                           .concat(Name)
00457                           .concat(LineNumber)
00458                           .concat(0) // Size
00459                           .concat(0) // Align
00460                           .concat(0) // Offset
00461                           .concat(Flags)
00462                           .get(VMContext),
00463                       File.getFileNode(),
00464                       DIScope(getNonCompileUnitScope(Scope)).getRef(),
00465                       Ty.getRef(), getConstantOrNull(Val)};
00466   return DIDerivedType(MDNode::get(VMContext, Elts));
00467 }
00468 
00469 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
00470                                         unsigned LineNumber,
00471                                         uint64_t SizeInBits,
00472                                         uint64_t AlignInBits,
00473                                         uint64_t OffsetInBits, unsigned Flags,
00474                                         DIType Ty, MDNode *PropertyNode) {
00475   // TAG_member is encoded in DIDerivedType format.
00476   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
00477                           .concat(Name)
00478                           .concat(LineNumber)
00479                           .concat(SizeInBits)
00480                           .concat(AlignInBits)
00481                           .concat(OffsetInBits)
00482                           .concat(Flags)
00483                           .get(VMContext),
00484                       File.getFileNode(), getNonCompileUnitScope(File), Ty,
00485                       PropertyNode};
00486   return DIDerivedType(MDNode::get(VMContext, Elts));
00487 }
00488 
00489 DIObjCProperty
00490 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
00491                               StringRef GetterName, StringRef SetterName,
00492                               unsigned PropertyAttributes, DIType Ty) {
00493   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_APPLE_property)
00494                           .concat(Name)
00495                           .concat(LineNumber)
00496                           .concat(GetterName)
00497                           .concat(SetterName)
00498                           .concat(PropertyAttributes)
00499                           .get(VMContext),
00500                       File, Ty};
00501   return DIObjCProperty(MDNode::get(VMContext, Elts));
00502 }
00503 
00504 DITemplateTypeParameter
00505 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
00506                                        DIType Ty, MDNode *File, unsigned LineNo,
00507                                        unsigned ColumnNo) {
00508   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_template_type_parameter)
00509                           .concat(Name)
00510                           .concat(LineNo)
00511                           .concat(ColumnNo)
00512                           .get(VMContext),
00513                       DIScope(getNonCompileUnitScope(Context)).getRef(),
00514                       Ty.getRef(), File};
00515   return DITemplateTypeParameter(MDNode::get(VMContext, Elts));
00516 }
00517 
00518 static DITemplateValueParameter createTemplateValueParameterHelper(
00519     LLVMContext &VMContext, unsigned Tag, DIDescriptor Context, StringRef Name,
00520     DIType Ty, Metadata *MD, MDNode *File, unsigned LineNo, unsigned ColumnNo) {
00521   Metadata *Elts[] = {
00522       HeaderBuilder::get(Tag).concat(Name).concat(LineNo).concat(ColumnNo).get(
00523           VMContext),
00524       DIScope(getNonCompileUnitScope(Context)).getRef(), Ty.getRef(), MD, File};
00525   return DITemplateValueParameter(MDNode::get(VMContext, Elts));
00526 }
00527 
00528 DITemplateValueParameter
00529 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
00530                                         DIType Ty, Constant *Val, MDNode *File,
00531                                         unsigned LineNo, unsigned ColumnNo) {
00532   return createTemplateValueParameterHelper(
00533       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
00534       getConstantOrNull(Val), File, LineNo, ColumnNo);
00535 }
00536 
00537 DITemplateValueParameter
00538 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
00539                                            DIType Ty, StringRef Val,
00540                                            MDNode *File, unsigned LineNo,
00541                                            unsigned ColumnNo) {
00542   return createTemplateValueParameterHelper(
00543       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
00544       MDString::get(VMContext, Val), File, LineNo, ColumnNo);
00545 }
00546 
00547 DITemplateValueParameter
00548 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
00549                                        DIType Ty, DIArray Val,
00550                                        MDNode *File, unsigned LineNo,
00551                                        unsigned ColumnNo) {
00552   return createTemplateValueParameterHelper(
00553       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
00554       Val, File, LineNo, ColumnNo);
00555 }
00556 
00557 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
00558                                            DIFile File, unsigned LineNumber,
00559                                            uint64_t SizeInBits,
00560                                            uint64_t AlignInBits,
00561                                            uint64_t OffsetInBits,
00562                                            unsigned Flags, DIType DerivedFrom,
00563                                            DIArray Elements,
00564                                            DIType VTableHolder,
00565                                            MDNode *TemplateParams,
00566                                            StringRef UniqueIdentifier) {
00567   assert((!Context || Context.isScope() || Context.isType()) &&
00568          "createClassType should be called with a valid Context");
00569   // TAG_class_type is encoded in DICompositeType format.
00570   Metadata *Elts[] = {
00571       HeaderBuilder::get(dwarf::DW_TAG_class_type)
00572           .concat(Name)
00573           .concat(LineNumber)
00574           .concat(SizeInBits)
00575           .concat(AlignInBits)
00576           .concat(OffsetInBits)
00577           .concat(Flags)
00578           .concat(0)
00579           .get(VMContext),
00580       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
00581       DerivedFrom.getRef(), Elements, VTableHolder.getRef(), TemplateParams,
00582       UniqueIdentifier.empty() ? nullptr
00583                                : MDString::get(VMContext, UniqueIdentifier)};
00584   DICompositeType R(MDNode::get(VMContext, Elts));
00585   assert(R.isCompositeType() &&
00586          "createClassType should return a DICompositeType");
00587   if (!UniqueIdentifier.empty())
00588     retainType(R);
00589   return R;
00590 }
00591 
00592 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
00593                                             StringRef Name, DIFile File,
00594                                             unsigned LineNumber,
00595                                             uint64_t SizeInBits,
00596                                             uint64_t AlignInBits,
00597                                             unsigned Flags, DIType DerivedFrom,
00598                                             DIArray Elements,
00599                                             unsigned RunTimeLang,
00600                                             DIType VTableHolder,
00601                                             StringRef UniqueIdentifier) {
00602  // TAG_structure_type is encoded in DICompositeType format.
00603   Metadata *Elts[] = {
00604       HeaderBuilder::get(dwarf::DW_TAG_structure_type)
00605           .concat(Name)
00606           .concat(LineNumber)
00607           .concat(SizeInBits)
00608           .concat(AlignInBits)
00609           .concat(0)
00610           .concat(Flags)
00611           .concat(RunTimeLang)
00612           .get(VMContext),
00613       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
00614       DerivedFrom.getRef(), Elements, VTableHolder.getRef(), nullptr,
00615       UniqueIdentifier.empty() ? nullptr
00616                                : MDString::get(VMContext, UniqueIdentifier)};
00617   DICompositeType R(MDNode::get(VMContext, Elts));
00618   assert(R.isCompositeType() &&
00619          "createStructType should return a DICompositeType");
00620   if (!UniqueIdentifier.empty())
00621     retainType(R);
00622   return R;
00623 }
00624 
00625 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
00626                                            DIFile File, unsigned LineNumber,
00627                                            uint64_t SizeInBits,
00628                                            uint64_t AlignInBits, unsigned Flags,
00629                                            DIArray Elements,
00630                                            unsigned RunTimeLang,
00631                                            StringRef UniqueIdentifier) {
00632   // TAG_union_type is encoded in DICompositeType format.
00633   Metadata *Elts[] = {
00634       HeaderBuilder::get(dwarf::DW_TAG_union_type)
00635           .concat(Name)
00636           .concat(LineNumber)
00637           .concat(SizeInBits)
00638           .concat(AlignInBits)
00639           .concat(0) // Offset
00640           .concat(Flags)
00641           .concat(RunTimeLang)
00642           .get(VMContext),
00643       File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
00644       nullptr, Elements, nullptr, nullptr,
00645       UniqueIdentifier.empty() ? nullptr
00646                                : MDString::get(VMContext, UniqueIdentifier)};
00647   DICompositeType R(MDNode::get(VMContext, Elts));
00648   if (!UniqueIdentifier.empty())
00649     retainType(R);
00650   return R;
00651 }
00652 
00653 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
00654                                                  DITypeArray ParameterTypes,
00655                                                  unsigned Flags) {
00656   // TAG_subroutine_type is encoded in DICompositeType format.
00657   Metadata *Elts[] = {
00658       HeaderBuilder::get(dwarf::DW_TAG_subroutine_type)
00659           .concat(StringRef())
00660           .concat(0)     // Line
00661           .concat(0)     // Size
00662           .concat(0)     // Align
00663           .concat(0)     // Offset
00664           .concat(Flags) // Flags
00665           .concat(0)
00666           .get(VMContext),
00667       nullptr, nullptr, nullptr, ParameterTypes, nullptr, nullptr,
00668       nullptr // Type Identifer
00669   };
00670   return DISubroutineType(MDNode::get(VMContext, Elts));
00671 }
00672 
00673 DICompositeType DIBuilder::createEnumerationType(
00674     DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
00675     uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
00676     DIType UnderlyingType, StringRef UniqueIdentifier) {
00677   // TAG_enumeration_type is encoded in DICompositeType format.
00678   Metadata *Elts[] = {
00679       HeaderBuilder::get(dwarf::DW_TAG_enumeration_type)
00680           .concat(Name)
00681           .concat(LineNumber)
00682           .concat(SizeInBits)
00683           .concat(AlignInBits)
00684           .concat(0) // Offset
00685           .concat(0) // Flags
00686           .concat(0)
00687           .get(VMContext),
00688       File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
00689       UnderlyingType.getRef(), Elements, nullptr, nullptr,
00690       UniqueIdentifier.empty() ? nullptr
00691                                : MDString::get(VMContext, UniqueIdentifier)};
00692   DICompositeType CTy(MDNode::get(VMContext, Elts));
00693   AllEnumTypes.push_back(CTy);
00694   if (!UniqueIdentifier.empty())
00695     retainType(CTy);
00696   return CTy;
00697 }
00698 
00699 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
00700                                            DIType Ty, DIArray Subscripts) {
00701   // TAG_array_type is encoded in DICompositeType format.
00702   Metadata *Elts[] = {
00703       HeaderBuilder::get(dwarf::DW_TAG_array_type)
00704           .concat(StringRef())
00705           .concat(0) // Line
00706           .concat(Size)
00707           .concat(AlignInBits)
00708           .concat(0) // Offset
00709           .concat(0) // Flags
00710           .concat(0)
00711           .get(VMContext),
00712       nullptr, // Filename/Directory,
00713       nullptr, // Unused
00714       Ty.getRef(), Subscripts, nullptr, nullptr,
00715       nullptr // Type Identifer
00716   };
00717   return DICompositeType(MDNode::get(VMContext, Elts));
00718 }
00719 
00720 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
00721                                             DIType Ty, DIArray Subscripts) {
00722   // A vector is an array type with the FlagVector flag applied.
00723   Metadata *Elts[] = {
00724       HeaderBuilder::get(dwarf::DW_TAG_array_type)
00725           .concat("")
00726           .concat(0) // Line
00727           .concat(Size)
00728           .concat(AlignInBits)
00729           .concat(0) // Offset
00730           .concat(DIType::FlagVector)
00731           .concat(0)
00732           .get(VMContext),
00733       nullptr, // Filename/Directory,
00734       nullptr, // Unused
00735       Ty.getRef(), Subscripts, nullptr, nullptr,
00736       nullptr // Type Identifer
00737   };
00738   return DICompositeType(MDNode::get(VMContext, Elts));
00739 }
00740 
00741 static HeaderBuilder setTypeFlagsInHeader(StringRef Header,
00742                                           unsigned FlagsToSet) {
00743   DIHeaderFieldIterator I(Header);
00744   std::advance(I, 6);
00745 
00746   unsigned Flags;
00747   if (I->getAsInteger(0, Flags))
00748     Flags = 0;
00749   Flags |= FlagsToSet;
00750 
00751   return HeaderBuilder()
00752       .concat(I.getPrefix())
00753       .concat(Flags)
00754       .concat(I.getSuffix());
00755 }
00756 
00757 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
00758                                   unsigned FlagsToSet) {
00759   SmallVector<Metadata *, 9> Elts;
00760   MDNode *N = Ty;
00761   assert(N && "Unexpected input DIType!");
00762   // Update header field.
00763   Elts.push_back(setTypeFlagsInHeader(Ty.getHeader(), FlagsToSet).get(Context));
00764   for (unsigned I = 1, E = N->getNumOperands(); I != E; ++I)
00765     Elts.push_back(N->getOperand(I));
00766 
00767   return DIType(MDNode::get(Context, Elts));
00768 }
00769 
00770 DIType DIBuilder::createArtificialType(DIType Ty) {
00771   if (Ty.isArtificial())
00772     return Ty;
00773   return createTypeWithFlags(VMContext, Ty, DIType::FlagArtificial);
00774 }
00775 
00776 DIType DIBuilder::createObjectPointerType(DIType Ty) {
00777   if (Ty.isObjectPointer())
00778     return Ty;
00779   unsigned Flags = DIType::FlagObjectPointer | DIType::FlagArtificial;
00780   return createTypeWithFlags(VMContext, Ty, Flags);
00781 }
00782 
00783 void DIBuilder::retainType(DIType T) { AllRetainTypes.emplace_back(T); }
00784 
00785 DIBasicType DIBuilder::createUnspecifiedParameter() {
00786   return DIBasicType();
00787 }
00788 
00789 DICompositeType
00790 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
00791                              DIFile F, unsigned Line, unsigned RuntimeLang,
00792                              uint64_t SizeInBits, uint64_t AlignInBits,
00793                              StringRef UniqueIdentifier) {
00794   // Create a temporary MDNode.
00795   Metadata *Elts[] = {
00796       HeaderBuilder::get(Tag)
00797           .concat(Name)
00798           .concat(Line)
00799           .concat(SizeInBits)
00800           .concat(AlignInBits)
00801           .concat(0) // Offset
00802           .concat(DIDescriptor::FlagFwdDecl)
00803           .concat(RuntimeLang)
00804           .get(VMContext),
00805       F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
00806       DIArray(), nullptr,
00807       nullptr, // TemplateParams
00808       UniqueIdentifier.empty() ? nullptr
00809                                : MDString::get(VMContext, UniqueIdentifier)};
00810   MDNode *Node = MDNode::get(VMContext, Elts);
00811   DICompositeType RetTy(Node);
00812   assert(RetTy.isCompositeType() &&
00813          "createForwardDecl result should be a DIType");
00814   if (!UniqueIdentifier.empty())
00815     retainType(RetTy);
00816   return RetTy;
00817 }
00818 
00819 DICompositeType DIBuilder::createReplaceableForwardDecl(
00820     unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
00821     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
00822     StringRef UniqueIdentifier) {
00823   // Create a temporary MDNode.
00824   Metadata *Elts[] = {
00825       HeaderBuilder::get(Tag)
00826           .concat(Name)
00827           .concat(Line)
00828           .concat(SizeInBits)
00829           .concat(AlignInBits)
00830           .concat(0) // Offset
00831           .concat(DIDescriptor::FlagFwdDecl)
00832           .concat(RuntimeLang)
00833           .get(VMContext),
00834       F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
00835       DIArray(), nullptr,
00836       nullptr, // TemplateParams
00837       UniqueIdentifier.empty() ? nullptr
00838                                : MDString::get(VMContext, UniqueIdentifier)};
00839   DICompositeType RetTy(MDNode::getTemporary(VMContext, Elts).release());
00840   assert(RetTy.isCompositeType() &&
00841          "createReplaceableForwardDecl result should be a DIType");
00842   if (!UniqueIdentifier.empty())
00843     retainType(RetTy);
00844   return RetTy;
00845 }
00846 
00847 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
00848   return DIArray(MDNode::get(VMContext, Elements));
00849 }
00850 
00851 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
00852   SmallVector<llvm::Metadata *, 16> Elts;
00853   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
00854     if (Elements[i] && isa<MDNode>(Elements[i]))
00855       Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
00856     else
00857       Elts.push_back(Elements[i]);
00858   }
00859   return DITypeArray(MDNode::get(VMContext, Elts));
00860 }
00861 
00862 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
00863   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subrange_type)
00864                           .concat(Lo)
00865                           .concat(Count)
00866                           .get(VMContext)};
00867 
00868   return DISubrange(MDNode::get(VMContext, Elts));
00869 }
00870 
00871 static DIGlobalVariable createGlobalVariableHelper(
00872     LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
00873     StringRef LinkageName, DIFile F, unsigned LineNumber, DITypeRef Ty,
00874     bool isLocalToUnit, Constant *Val, MDNode *Decl, bool isDefinition,
00875     std::function<MDNode *(ArrayRef<Metadata *>)> CreateFunc) {
00876 
00877   MDNode *TheCtx = getNonCompileUnitScope(Context);
00878   if (DIScope(TheCtx).isCompositeType()) {
00879     assert(!DICompositeType(TheCtx).getIdentifier() &&
00880            "Context of a global variable should not be a type with identifier");
00881   }
00882 
00883   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_variable)
00884                           .concat(Name)
00885                           .concat(Name)
00886                           .concat(LinkageName)
00887                           .concat(LineNumber)
00888                           .concat(isLocalToUnit)
00889                           .concat(isDefinition)
00890                           .get(VMContext),
00891                       TheCtx, F, Ty, getConstantOrNull(Val),
00892                       DIDescriptor(Decl)};
00893 
00894   return DIGlobalVariable(CreateFunc(Elts));
00895 }
00896 
00897 DIGlobalVariable DIBuilder::createGlobalVariable(
00898     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
00899     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
00900     MDNode *Decl) {
00901   return createGlobalVariableHelper(
00902       VMContext, Context, Name, LinkageName, F, LineNumber, Ty, isLocalToUnit,
00903       Val, Decl, true, [&](ArrayRef<Metadata *> Elts) -> MDNode *{
00904         MDNode *Node = MDNode::get(VMContext, Elts);
00905         AllGVs.push_back(Node);
00906         return Node;
00907       });
00908 }
00909 
00910 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
00911     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
00912     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
00913     MDNode *Decl) {
00914   return createGlobalVariableHelper(VMContext, Context, Name, LinkageName, F,
00915                                     LineNumber, Ty, isLocalToUnit, Val, Decl,
00916                                     false, [&](ArrayRef<Metadata *> Elts) {
00917     return MDNode::getTemporary(VMContext, Elts).release();
00918   });
00919 }
00920 
00921 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
00922                                           StringRef Name, DIFile File,
00923                                           unsigned LineNo, DITypeRef Ty,
00924                                           bool AlwaysPreserve, unsigned Flags,
00925                                           unsigned ArgNo) {
00926   DIDescriptor Context(getNonCompileUnitScope(Scope));
00927   assert((!Context || Context.isScope()) &&
00928          "createLocalVariable should be called with a valid Context");
00929   Metadata *Elts[] = {HeaderBuilder::get(Tag)
00930                           .concat(Name)
00931                           .concat(LineNo | (ArgNo << 24))
00932                           .concat(Flags)
00933                           .get(VMContext),
00934                       getNonCompileUnitScope(Scope), File, Ty};
00935   MDNode *Node = MDNode::get(VMContext, Elts);
00936   if (AlwaysPreserve) {
00937     // The optimizer may remove local variable. If there is an interest
00938     // to preserve variable info in such situation then stash it in a
00939     // named mdnode.
00940     DISubprogram Fn(getDISubprogram(Scope));
00941     assert(Fn && "Missing subprogram for local variable");
00942     PreservedVariables[Fn].emplace_back(Node);
00943   }
00944   DIVariable RetVar(Node);
00945   assert(RetVar.isVariable() &&
00946          "createLocalVariable should return a valid DIVariable");
00947   return RetVar;
00948 }
00949 
00950 DIExpression DIBuilder::createExpression(ArrayRef<int64_t> Addr) {
00951   auto Header = HeaderBuilder::get(DW_TAG_expression);
00952   for (int64_t I : Addr)
00953     Header.concat(I);
00954   Metadata *Elts[] = {Header.get(VMContext)};
00955   return DIExpression(MDNode::get(VMContext, Elts));
00956 }
00957 
00958 DIExpression DIBuilder::createPieceExpression(unsigned OffsetInBytes,
00959                                               unsigned SizeInBytes) {
00960   int64_t Addr[] = {dwarf::DW_OP_piece, OffsetInBytes, SizeInBytes};
00961   return createExpression(Addr);
00962 }
00963 
00964 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
00965                                        StringRef LinkageName, DIFile File,
00966                                        unsigned LineNo, DICompositeType Ty,
00967                                        bool isLocalToUnit, bool isDefinition,
00968                                        unsigned ScopeLine, unsigned Flags,
00969                                        bool isOptimized, Function *Fn,
00970                                        MDNode *TParams, MDNode *Decl) {
00971   // dragonegg does not generate identifier for types, so using an empty map
00972   // to resolve the context should be fine.
00973   DITypeIdentifierMap EmptyMap;
00974   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
00975                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
00976                         Flags, isOptimized, Fn, TParams, Decl);
00977 }
00978 
00979 static DISubprogram createFunctionHelper(
00980     LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
00981     StringRef LinkageName, DIFile File, unsigned LineNo, DICompositeType Ty,
00982     bool isLocalToUnit, bool isDefinition, unsigned ScopeLine, unsigned Flags,
00983     bool isOptimized, Function *Fn, MDNode *TParams, MDNode *Decl, MDNode *Vars,
00984     std::function<MDNode *(ArrayRef<Metadata *>)> CreateFunc) {
00985   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
00986          "function types should be subroutines");
00987   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
00988                           .concat(Name)
00989                           .concat(Name)
00990                           .concat(LinkageName)
00991                           .concat(LineNo)
00992                           .concat(isLocalToUnit)
00993                           .concat(isDefinition)
00994                           .concat(0)
00995                           .concat(0)
00996                           .concat(Flags)
00997                           .concat(isOptimized)
00998                           .concat(ScopeLine)
00999                           .get(VMContext),
01000                       File.getFileNode(),
01001                       DIScope(getNonCompileUnitScope(Context)).getRef(), Ty,
01002                       nullptr, getConstantOrNull(Fn), TParams, Decl, Vars};
01003 
01004   DISubprogram S(CreateFunc(Elts));
01005   assert(S.isSubprogram() &&
01006          "createFunction should return a valid DISubprogram");
01007   return S;
01008 }
01009 
01010 
01011 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
01012                                        StringRef LinkageName, DIFile File,
01013                                        unsigned LineNo, DICompositeType Ty,
01014                                        bool isLocalToUnit, bool isDefinition,
01015                                        unsigned ScopeLine, unsigned Flags,
01016                                        bool isOptimized, Function *Fn,
01017                                        MDNode *TParams, MDNode *Decl) {
01018   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
01019                               LineNo, Ty, isLocalToUnit, isDefinition,
01020                               ScopeLine, Flags, isOptimized, Fn, TParams, Decl,
01021                               MDNode::getTemporary(VMContext, None).release(),
01022                               [&](ArrayRef<Metadata *> Elts) -> MDNode *{
01023     MDNode *Node = MDNode::get(VMContext, Elts);
01024     // Create a named metadata so that we
01025     // do not lose this mdnode.
01026     if (isDefinition)
01027       AllSubprograms.push_back(Node);
01028     return Node;
01029   });
01030 }
01031 
01032 DISubprogram
01033 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
01034                                      StringRef LinkageName, DIFile File,
01035                                      unsigned LineNo, DICompositeType Ty,
01036                                      bool isLocalToUnit, bool isDefinition,
01037                                      unsigned ScopeLine, unsigned Flags,
01038                                      bool isOptimized, Function *Fn,
01039                                      MDNode *TParams, MDNode *Decl) {
01040   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
01041                               LineNo, Ty, isLocalToUnit, isDefinition,
01042                               ScopeLine, Flags, isOptimized, Fn, TParams, Decl,
01043                               nullptr, [&](ArrayRef<Metadata *> Elts) {
01044     return MDNode::getTemporary(VMContext, Elts).release();
01045   });
01046 }
01047 
01048 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
01049                                      StringRef LinkageName, DIFile F,
01050                                      unsigned LineNo, DICompositeType Ty,
01051                                      bool isLocalToUnit, bool isDefinition,
01052                                      unsigned VK, unsigned VIndex,
01053                                      DIType VTableHolder, unsigned Flags,
01054                                      bool isOptimized, Function *Fn,
01055                                      MDNode *TParam) {
01056   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
01057          "function types should be subroutines");
01058   assert(getNonCompileUnitScope(Context) &&
01059          "Methods should have both a Context and a context that isn't "
01060          "the compile unit.");
01061   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
01062                           .concat(Name)
01063                           .concat(Name)
01064                           .concat(LinkageName)
01065                           .concat(LineNo)
01066                           .concat(isLocalToUnit)
01067                           .concat(isDefinition)
01068                           .concat(VK)
01069                           .concat(VIndex)
01070                           .concat(Flags)
01071                           .concat(isOptimized)
01072                           .concat(LineNo)
01073                           // FIXME: Do we want to use different scope/lines?
01074                           .get(VMContext),
01075                       F.getFileNode(), DIScope(Context).getRef(), Ty,
01076                       VTableHolder.getRef(), getConstantOrNull(Fn), TParam,
01077                       nullptr, nullptr};
01078   MDNode *Node = MDNode::get(VMContext, Elts);
01079   if (isDefinition)
01080     AllSubprograms.push_back(Node);
01081   DISubprogram S(Node);
01082   assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
01083   return S;
01084 }
01085 
01086 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
01087                                        DIFile File, unsigned LineNo) {
01088   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_namespace)
01089                           .concat(Name)
01090                           .concat(LineNo)
01091                           .get(VMContext),
01092                       File.getFileNode(), getNonCompileUnitScope(Scope)};
01093   DINameSpace R(MDNode::get(VMContext, Elts));
01094   assert(R.Verify() &&
01095          "createNameSpace should return a verifiable DINameSpace");
01096   return R;
01097 }
01098 
01099 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
01100                                                      DIFile File,
01101                                                      unsigned Discriminator) {
01102   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
01103                           .concat(Discriminator)
01104                           .get(VMContext),
01105                       File.getFileNode(), Scope};
01106   DILexicalBlockFile R(MDNode::get(VMContext, Elts));
01107   assert(
01108       R.Verify() &&
01109       "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
01110   return R;
01111 }
01112 
01113 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
01114                                              unsigned Line, unsigned Col) {
01115   // FIXME: This isn't thread safe nor the right way to defeat MDNode uniquing.
01116   // I believe the right way is to have a self-referential element in the node.
01117   // Also: why do we bother with line/column - they're not used and the
01118   // documentation (SourceLevelDebugging.rst) claims the line/col are necessary
01119   // for uniquing, yet then we have this other solution (because line/col were
01120   // inadequate) anyway. Remove all 3 and replace them with a self-reference.
01121 
01122   // Defeat MDNode uniquing for lexical blocks by using unique id.
01123   static unsigned int unique_id = 0;
01124   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
01125                           .concat(Line)
01126                           .concat(Col)
01127                           .concat(unique_id++)
01128                           .get(VMContext),
01129                       File.getFileNode(), getNonCompileUnitScope(Scope)};
01130   DILexicalBlock R(MDNode::get(VMContext, Elts));
01131   assert(R.Verify() &&
01132          "createLexicalBlock should return a verifiable DILexicalBlock");
01133   return R;
01134 }
01135 
01136 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
01137   assert(V && "no value passed to dbg intrinsic");
01138   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
01139 }
01140 
01141 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
01142                                       DIExpression Expr,
01143                                       Instruction *InsertBefore) {
01144   assert(VarInfo.isVariable() &&
01145          "empty or invalid DIVariable passed to dbg.declare");
01146   if (!DeclareFn)
01147     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
01148 
01149   trackIfUnresolved(VarInfo);
01150   trackIfUnresolved(Expr);
01151   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
01152                    MetadataAsValue::get(VMContext, VarInfo),
01153                    MetadataAsValue::get(VMContext, Expr)};
01154   return CallInst::Create(DeclareFn, Args, "", InsertBefore);
01155 }
01156 
01157 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
01158                                       DIExpression Expr,
01159                                       BasicBlock *InsertAtEnd) {
01160   assert(VarInfo.isVariable() &&
01161          "empty or invalid DIVariable passed to dbg.declare");
01162   if (!DeclareFn)
01163     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
01164 
01165   trackIfUnresolved(VarInfo);
01166   trackIfUnresolved(Expr);
01167   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
01168                    MetadataAsValue::get(VMContext, VarInfo),
01169                    MetadataAsValue::get(VMContext, Expr)};
01170 
01171   // If this block already has a terminator then insert this intrinsic
01172   // before the terminator.
01173   if (TerminatorInst *T = InsertAtEnd->getTerminator())
01174     return CallInst::Create(DeclareFn, Args, "", T);
01175   else
01176     return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
01177 }
01178 
01179 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
01180                                                 DIVariable VarInfo,
01181                                                 DIExpression Expr,
01182                                                 Instruction *InsertBefore) {
01183   assert(V && "no value passed to dbg.value");
01184   assert(VarInfo.isVariable() &&
01185          "empty or invalid DIVariable passed to dbg.value");
01186   if (!ValueFn)
01187     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
01188 
01189   trackIfUnresolved(VarInfo);
01190   trackIfUnresolved(Expr);
01191   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
01192                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
01193                    MetadataAsValue::get(VMContext, VarInfo),
01194                    MetadataAsValue::get(VMContext, Expr)};
01195   return CallInst::Create(ValueFn, Args, "", InsertBefore);
01196 }
01197 
01198 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
01199                                                 DIVariable VarInfo,
01200                                                 DIExpression Expr,
01201                                                 BasicBlock *InsertAtEnd) {
01202   assert(V && "no value passed to dbg.value");
01203   assert(VarInfo.isVariable() &&
01204          "empty or invalid DIVariable passed to dbg.value");
01205   if (!ValueFn)
01206     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
01207 
01208   trackIfUnresolved(VarInfo);
01209   trackIfUnresolved(Expr);
01210   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
01211                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
01212                    MetadataAsValue::get(VMContext, VarInfo),
01213                    MetadataAsValue::get(VMContext, Expr)};
01214   return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
01215 }
01216 
01217 void DIBuilder::replaceVTableHolder(DICompositeType &T, DICompositeType VTableHolder) {
01218   T.setContainingType(VTableHolder);
01219 
01220   // If this didn't create a self-reference, just return.
01221   if (T != VTableHolder)
01222     return;
01223 
01224   // Look for unresolved operands.  T has dropped RAUW support and is already
01225   // marked resolved, orphaning any cycles underneath it.
01226   assert(T->isResolved() && "Expected self-reference to be resolved");
01227   for (const MDOperand &O : T->operands())
01228     if (auto *N = dyn_cast_or_null<MDNode>(O))
01229       trackIfUnresolved(N);
01230 }
01231 
01232 void DIBuilder::replaceArrays(DICompositeType &T, DIArray Elements,
01233                               DIArray TParams) {
01234   T.setArrays(Elements, TParams);
01235 
01236   // If T isn't resolved, there's no problem.
01237   if (!T->isResolved())
01238     return;
01239 
01240   // If "T" is resolved, it may be due to a self-reference cycle.  Track the
01241   // arrays explicitly if they're unresolved, or else the cycles will be
01242   // orphaned.
01243   if (Elements)
01244     trackIfUnresolved(Elements);
01245   if (TParams)
01246     trackIfUnresolved(TParams);
01247 }