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