Home | History | Annotate | Line # | Download | only in IR
      1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 // This file implements the DIBuilder.
     10 //
     11 //===----------------------------------------------------------------------===//
     12 
     13 #include "llvm/IR/DIBuilder.h"
     14 #include "LLVMContextImpl.h"
     15 #include "llvm/ADT/Optional.h"
     16 #include "llvm/ADT/STLExtras.h"
     17 #include "llvm/BinaryFormat/Dwarf.h"
     18 #include "llvm/IR/Constants.h"
     19 #include "llvm/IR/DebugInfo.h"
     20 #include "llvm/IR/IRBuilder.h"
     21 #include "llvm/IR/IntrinsicInst.h"
     22 #include "llvm/IR/Module.h"
     23 #include "llvm/Support/CommandLine.h"
     24 #include "llvm/Support/Debug.h"
     25 
     26 using namespace llvm;
     27 using namespace llvm::dwarf;
     28 
     29 static cl::opt<bool>
     30     UseDbgAddr("use-dbg-addr",
     31                llvm::cl::desc("Use llvm.dbg.addr for all local variables"),
     32                cl::init(false), cl::Hidden);
     33 
     34 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes, DICompileUnit *CU)
     35   : M(m), VMContext(M.getContext()), CUNode(CU),
     36       DeclareFn(nullptr), ValueFn(nullptr), LabelFn(nullptr),
     37       AllowUnresolvedNodes(AllowUnresolvedNodes) {}
     38 
     39 void DIBuilder::trackIfUnresolved(MDNode *N) {
     40   if (!N)
     41     return;
     42   if (N->isResolved())
     43     return;
     44 
     45   assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
     46   UnresolvedNodes.emplace_back(N);
     47 }
     48 
     49 void DIBuilder::finalizeSubprogram(DISubprogram *SP) {
     50   MDTuple *Temp = SP->getRetainedNodes().get();
     51   if (!Temp || !Temp->isTemporary())
     52     return;
     53 
     54   SmallVector<Metadata *, 16> RetainedNodes;
     55 
     56   auto PV = PreservedVariables.find(SP);
     57   if (PV != PreservedVariables.end())
     58     RetainedNodes.append(PV->second.begin(), PV->second.end());
     59 
     60   auto PL = PreservedLabels.find(SP);
     61   if (PL != PreservedLabels.end())
     62     RetainedNodes.append(PL->second.begin(), PL->second.end());
     63 
     64   DINodeArray Node = getOrCreateArray(RetainedNodes);
     65 
     66   TempMDTuple(Temp)->replaceAllUsesWith(Node.get());
     67 }
     68 
     69 void DIBuilder::finalize() {
     70   if (!CUNode) {
     71     assert(!AllowUnresolvedNodes &&
     72            "creating type nodes without a CU is not supported");
     73     return;
     74   }
     75 
     76   CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
     77 
     78   SmallVector<Metadata *, 16> RetainValues;
     79   // Declarations and definitions of the same type may be retained. Some
     80   // clients RAUW these pairs, leaving duplicates in the retained types
     81   // list. Use a set to remove the duplicates while we transform the
     82   // TrackingVHs back into Values.
     83   SmallPtrSet<Metadata *, 16> RetainSet;
     84   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
     85     if (RetainSet.insert(AllRetainTypes[I]).second)
     86       RetainValues.push_back(AllRetainTypes[I]);
     87 
     88   if (!RetainValues.empty())
     89     CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
     90 
     91   DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
     92   for (auto *SP : SPs)
     93     finalizeSubprogram(SP);
     94   for (auto *N : RetainValues)
     95     if (auto *SP = dyn_cast<DISubprogram>(N))
     96       finalizeSubprogram(SP);
     97 
     98   if (!AllGVs.empty())
     99     CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
    100 
    101   if (!AllImportedModules.empty())
    102     CUNode->replaceImportedEntities(MDTuple::get(
    103         VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
    104                                                AllImportedModules.end())));
    105 
    106   for (const auto &I : AllMacrosPerParent) {
    107     // DIMacroNode's with nullptr parent are DICompileUnit direct children.
    108     if (!I.first) {
    109       CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef()));
    110       continue;
    111     }
    112     // Otherwise, it must be a temporary DIMacroFile that need to be resolved.
    113     auto *TMF = cast<DIMacroFile>(I.first);
    114     auto *MF = DIMacroFile::get(VMContext, dwarf::DW_MACINFO_start_file,
    115                                 TMF->getLine(), TMF->getFile(),
    116                                 getOrCreateMacroArray(I.second.getArrayRef()));
    117     replaceTemporary(llvm::TempDIMacroNode(TMF), MF);
    118   }
    119 
    120   // Now that all temp nodes have been replaced or deleted, resolve remaining
    121   // cycles.
    122   for (const auto &N : UnresolvedNodes)
    123     if (N && !N->isResolved())
    124       N->resolveCycles();
    125   UnresolvedNodes.clear();
    126 
    127   // Can't handle unresolved nodes anymore.
    128   AllowUnresolvedNodes = false;
    129 }
    130 
    131 /// If N is compile unit return NULL otherwise return N.
    132 static DIScope *getNonCompileUnitScope(DIScope *N) {
    133   if (!N || isa<DICompileUnit>(N))
    134     return nullptr;
    135   return cast<DIScope>(N);
    136 }
    137 
    138 DICompileUnit *DIBuilder::createCompileUnit(
    139     unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized,
    140     StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
    141     DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId,
    142     bool SplitDebugInlining, bool DebugInfoForProfiling,
    143     DICompileUnit::DebugNameTableKind NameTableKind, bool RangesBaseAddress,
    144     StringRef SysRoot, StringRef SDK) {
    145 
    146   assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
    147           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
    148          "Invalid Language tag");
    149 
    150   assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
    151   CUNode = DICompileUnit::getDistinct(
    152       VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer,
    153       SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId,
    154       SplitDebugInlining, DebugInfoForProfiling, NameTableKind,
    155       RangesBaseAddress, SysRoot, SDK);
    156 
    157   // Create a named metadata so that it is easier to find cu in a module.
    158   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
    159   NMD->addOperand(CUNode);
    160   trackIfUnresolved(CUNode);
    161   return CUNode;
    162 }
    163 
    164 static DIImportedEntity *
    165 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
    166                      Metadata *NS, DIFile *File, unsigned Line, StringRef Name,
    167                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
    168   if (Line)
    169     assert(File && "Source location has line number but no file");
    170   unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size();
    171   auto *M = DIImportedEntity::get(C, Tag, Context, cast_or_null<DINode>(NS),
    172                                   File, Line, Name);
    173   if (EntitiesCount < C.pImpl->DIImportedEntitys.size())
    174     // A new Imported Entity was just added to the context.
    175     // Add it to the Imported Modules list.
    176     AllImportedModules.emplace_back(M);
    177   return M;
    178 }
    179 
    180 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
    181                                                   DINamespace *NS, DIFile *File,
    182                                                   unsigned Line) {
    183   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
    184                                 Context, NS, File, Line, StringRef(),
    185                                 AllImportedModules);
    186 }
    187 
    188 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
    189                                                   DIImportedEntity *NS,
    190                                                   DIFile *File, unsigned Line) {
    191   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
    192                                 Context, NS, File, Line, StringRef(),
    193                                 AllImportedModules);
    194 }
    195 
    196 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
    197                                                   DIFile *File, unsigned Line) {
    198   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
    199                                 Context, M, File, Line, StringRef(),
    200                                 AllImportedModules);
    201 }
    202 
    203 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
    204                                                        DINode *Decl,
    205                                                        DIFile *File,
    206                                                        unsigned Line,
    207                                                        StringRef Name) {
    208   // Make sure to use the unique identifier based metadata reference for
    209   // types that have one.
    210   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
    211                                 Context, Decl, File, Line, Name,
    212                                 AllImportedModules);
    213 }
    214 
    215 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory,
    216                               Optional<DIFile::ChecksumInfo<StringRef>> CS,
    217                               Optional<StringRef> Source) {
    218   return DIFile::get(VMContext, Filename, Directory, CS, Source);
    219 }
    220 
    221 DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber,
    222                                 unsigned MacroType, StringRef Name,
    223                                 StringRef Value) {
    224   assert(!Name.empty() && "Unable to create macro without name");
    225   assert((MacroType == dwarf::DW_MACINFO_undef ||
    226           MacroType == dwarf::DW_MACINFO_define) &&
    227          "Unexpected macro type");
    228   auto *M = DIMacro::get(VMContext, MacroType, LineNumber, Name, Value);
    229   AllMacrosPerParent[Parent].insert(M);
    230   return M;
    231 }
    232 
    233 DIMacroFile *DIBuilder::createTempMacroFile(DIMacroFile *Parent,
    234                                             unsigned LineNumber, DIFile *File) {
    235   auto *MF = DIMacroFile::getTemporary(VMContext, dwarf::DW_MACINFO_start_file,
    236                                        LineNumber, File, DIMacroNodeArray())
    237                  .release();
    238   AllMacrosPerParent[Parent].insert(MF);
    239   // Add the new temporary DIMacroFile to the macro per parent map as a parent.
    240   // This is needed to assure DIMacroFile with no children to have an entry in
    241   // the map. Otherwise, it will not be resolved in DIBuilder::finalize().
    242   AllMacrosPerParent.insert({MF, {}});
    243   return MF;
    244 }
    245 
    246 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val,
    247                                           bool IsUnsigned) {
    248   assert(!Name.empty() && "Unable to create enumerator without name");
    249   return DIEnumerator::get(VMContext, APInt(64, Val, !IsUnsigned), IsUnsigned,
    250                            Name);
    251 }
    252 
    253 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
    254   assert(!Name.empty() && "Unable to create type without name");
    255   return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
    256 }
    257 
    258 DIBasicType *DIBuilder::createNullPtrType() {
    259   return createUnspecifiedType("decltype(nullptr)");
    260 }
    261 
    262 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
    263                                         unsigned Encoding,
    264                                         DINode::DIFlags Flags) {
    265   assert(!Name.empty() && "Unable to create type without name");
    266   return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
    267                           0, Encoding, Flags);
    268 }
    269 
    270 DIStringType *DIBuilder::createStringType(StringRef Name, uint64_t SizeInBits) {
    271   assert(!Name.empty() && "Unable to create type without name");
    272   return DIStringType::get(VMContext, dwarf::DW_TAG_string_type, Name,
    273                            SizeInBits, 0);
    274 }
    275 
    276 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
    277   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0,
    278                             0, 0, None, DINode::FlagZero);
    279 }
    280 
    281 DIDerivedType *DIBuilder::createPointerType(
    282     DIType *PointeeTy,
    283     uint64_t SizeInBits,
    284     uint32_t AlignInBits,
    285     Optional<unsigned> DWARFAddressSpace,
    286     StringRef Name) {
    287   // FIXME: Why is there a name here?
    288   return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
    289                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
    290                             AlignInBits, 0, DWARFAddressSpace,
    291                             DINode::FlagZero);
    292 }
    293 
    294 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
    295                                                   DIType *Base,
    296                                                   uint64_t SizeInBits,
    297                                                   uint32_t AlignInBits,
    298                                                   DINode::DIFlags Flags) {
    299   return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
    300                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
    301                             AlignInBits, 0, None, Flags, Base);
    302 }
    303 
    304 DIDerivedType *DIBuilder::createReferenceType(
    305     unsigned Tag, DIType *RTy,
    306     uint64_t SizeInBits,
    307     uint32_t AlignInBits,
    308     Optional<unsigned> DWARFAddressSpace) {
    309   assert(RTy && "Unable to create reference type");
    310   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy,
    311                             SizeInBits, AlignInBits, 0, DWARFAddressSpace,
    312                             DINode::FlagZero);
    313 }
    314 
    315 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
    316                                         DIFile *File, unsigned LineNo,
    317                                         DIScope *Context,
    318                                         uint32_t AlignInBits) {
    319   return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
    320                             LineNo, getNonCompileUnitScope(Context), Ty, 0,
    321                             AlignInBits, 0, None, DINode::FlagZero);
    322 }
    323 
    324 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
    325   assert(Ty && "Invalid type!");
    326   assert(FriendTy && "Invalid friend type!");
    327   return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty,
    328                             FriendTy, 0, 0, 0, None, DINode::FlagZero);
    329 }
    330 
    331 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
    332                                             uint64_t BaseOffset,
    333                                             uint32_t VBPtrOffset,
    334                                             DINode::DIFlags Flags) {
    335   assert(Ty && "Unable to create inheritance");
    336   Metadata *ExtraData = ConstantAsMetadata::get(
    337       ConstantInt::get(IntegerType::get(VMContext, 32), VBPtrOffset));
    338   return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
    339                             0, Ty, BaseTy, 0, 0, BaseOffset, None,
    340                             Flags, ExtraData);
    341 }
    342 
    343 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
    344                                            DIFile *File, unsigned LineNumber,
    345                                            uint64_t SizeInBits,
    346                                            uint32_t AlignInBits,
    347                                            uint64_t OffsetInBits,
    348                                            DINode::DIFlags Flags, DIType *Ty) {
    349   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
    350                             LineNumber, getNonCompileUnitScope(Scope), Ty,
    351                             SizeInBits, AlignInBits, OffsetInBits, None, Flags);
    352 }
    353 
    354 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
    355   if (C)
    356     return ConstantAsMetadata::get(C);
    357   return nullptr;
    358 }
    359 
    360 DIDerivedType *DIBuilder::createVariantMemberType(
    361     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
    362     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
    363     Constant *Discriminant, DINode::DIFlags Flags, DIType *Ty) {
    364   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
    365                             LineNumber, getNonCompileUnitScope(Scope), Ty,
    366                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
    367                             getConstantOrNull(Discriminant));
    368 }
    369 
    370 DIDerivedType *DIBuilder::createBitFieldMemberType(
    371     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
    372     uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits,
    373     DINode::DIFlags Flags, DIType *Ty) {
    374   Flags |= DINode::FlagBitField;
    375   return DIDerivedType::get(
    376       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
    377       getNonCompileUnitScope(Scope), Ty, SizeInBits, /* AlignInBits */ 0,
    378       OffsetInBits, None, Flags,
    379       ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64),
    380                                                StorageOffsetInBits)));
    381 }
    382 
    383 DIDerivedType *
    384 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File,
    385                                   unsigned LineNumber, DIType *Ty,
    386                                   DINode::DIFlags Flags, llvm::Constant *Val,
    387                                   uint32_t AlignInBits) {
    388   Flags |= DINode::FlagStaticMember;
    389   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
    390                             LineNumber, getNonCompileUnitScope(Scope), Ty, 0,
    391                             AlignInBits, 0, None, Flags,
    392                             getConstantOrNull(Val));
    393 }
    394 
    395 DIDerivedType *
    396 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber,
    397                           uint64_t SizeInBits, uint32_t AlignInBits,
    398                           uint64_t OffsetInBits, DINode::DIFlags Flags,
    399                           DIType *Ty, MDNode *PropertyNode) {
    400   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
    401                             LineNumber, getNonCompileUnitScope(File), Ty,
    402                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
    403                             PropertyNode);
    404 }
    405 
    406 DIObjCProperty *
    407 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
    408                               StringRef GetterName, StringRef SetterName,
    409                               unsigned PropertyAttributes, DIType *Ty) {
    410   return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
    411                              SetterName, PropertyAttributes, Ty);
    412 }
    413 
    414 DITemplateTypeParameter *
    415 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
    416                                        DIType *Ty, bool isDefault) {
    417   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
    418   return DITemplateTypeParameter::get(VMContext, Name, Ty, isDefault);
    419 }
    420 
    421 static DITemplateValueParameter *
    422 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
    423                                    DIScope *Context, StringRef Name, DIType *Ty,
    424                                    bool IsDefault, Metadata *MD) {
    425   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
    426   return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, IsDefault, MD);
    427 }
    428 
    429 DITemplateValueParameter *
    430 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
    431                                         DIType *Ty, bool isDefault,
    432                                         Constant *Val) {
    433   return createTemplateValueParameterHelper(
    434       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
    435       isDefault, getConstantOrNull(Val));
    436 }
    437 
    438 DITemplateValueParameter *
    439 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
    440                                            DIType *Ty, StringRef Val) {
    441   return createTemplateValueParameterHelper(
    442       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
    443       false, MDString::get(VMContext, Val));
    444 }
    445 
    446 DITemplateValueParameter *
    447 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
    448                                        DIType *Ty, DINodeArray Val) {
    449   return createTemplateValueParameterHelper(
    450       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
    451       false, Val.get());
    452 }
    453 
    454 DICompositeType *DIBuilder::createClassType(
    455     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
    456     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
    457     DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
    458     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
    459   assert((!Context || isa<DIScope>(Context)) &&
    460          "createClassType should be called with a valid Context");
    461 
    462   auto *R = DICompositeType::get(
    463       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
    464       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
    465       OffsetInBits, Flags, Elements, 0, VTableHolder,
    466       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
    467   trackIfUnresolved(R);
    468   return R;
    469 }
    470 
    471 DICompositeType *DIBuilder::createStructType(
    472     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
    473     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
    474     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
    475     DIType *VTableHolder, StringRef UniqueIdentifier) {
    476   auto *R = DICompositeType::get(
    477       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
    478       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0,
    479       Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier);
    480   trackIfUnresolved(R);
    481   return R;
    482 }
    483 
    484 DICompositeType *DIBuilder::createUnionType(
    485     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
    486     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
    487     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
    488   auto *R = DICompositeType::get(
    489       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
    490       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
    491       Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier);
    492   trackIfUnresolved(R);
    493   return R;
    494 }
    495 
    496 DICompositeType *DIBuilder::createVariantPart(
    497     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
    498     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
    499     DIDerivedType *Discriminator, DINodeArray Elements, StringRef UniqueIdentifier) {
    500   auto *R = DICompositeType::get(
    501       VMContext, dwarf::DW_TAG_variant_part, Name, File, LineNumber,
    502       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
    503       Elements, 0, nullptr, nullptr, UniqueIdentifier, Discriminator);
    504   trackIfUnresolved(R);
    505   return R;
    506 }
    507 
    508 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
    509                                                   DINode::DIFlags Flags,
    510                                                   unsigned CC) {
    511   return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
    512 }
    513 
    514 DICompositeType *DIBuilder::createEnumerationType(
    515     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
    516     uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
    517     DIType *UnderlyingType, StringRef UniqueIdentifier, bool IsScoped) {
    518   auto *CTy = DICompositeType::get(
    519       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
    520       getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
    521       IsScoped ? DINode::FlagEnumClass : DINode::FlagZero, Elements, 0, nullptr,
    522       nullptr, UniqueIdentifier);
    523   AllEnumTypes.push_back(CTy);
    524   trackIfUnresolved(CTy);
    525   return CTy;
    526 }
    527 
    528 DIDerivedType *DIBuilder::createSetType(DIScope *Scope, StringRef Name,
    529                                         DIFile *File, unsigned LineNo,
    530                                         uint64_t SizeInBits,
    531                                         uint32_t AlignInBits, DIType *Ty) {
    532   auto *R =
    533       DIDerivedType::get(VMContext, dwarf::DW_TAG_set_type, Name, File, LineNo,
    534                          getNonCompileUnitScope(Scope), Ty, SizeInBits,
    535                          AlignInBits, 0, None, DINode::FlagZero);
    536   trackIfUnresolved(R);
    537   return R;
    538 }
    539 
    540 DICompositeType *DIBuilder::createArrayType(
    541     uint64_t Size, uint32_t AlignInBits, DIType *Ty, DINodeArray Subscripts,
    542     PointerUnion<DIExpression *, DIVariable *> DL,
    543     PointerUnion<DIExpression *, DIVariable *> AS,
    544     PointerUnion<DIExpression *, DIVariable *> AL,
    545     PointerUnion<DIExpression *, DIVariable *> RK) {
    546   auto *R = DICompositeType::get(
    547       VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
    548       nullptr, Ty, Size, AlignInBits, 0, DINode::FlagZero,
    549       Subscripts, 0, nullptr, nullptr, "", nullptr,
    550       DL.is<DIExpression *>() ? (Metadata *)DL.get<DIExpression *>()
    551                               : (Metadata *)DL.get<DIVariable *>(),
    552       AS.is<DIExpression *>() ? (Metadata *)AS.get<DIExpression *>()
    553                               : (Metadata *)AS.get<DIVariable *>(),
    554       AL.is<DIExpression *>() ? (Metadata *)AL.get<DIExpression *>()
    555                               : (Metadata *)AL.get<DIVariable *>(),
    556       RK.is<DIExpression *>() ? (Metadata *)RK.get<DIExpression *>()
    557                               : (Metadata *)RK.get<DIVariable *>());
    558   trackIfUnresolved(R);
    559   return R;
    560 }
    561 
    562 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
    563                                              uint32_t AlignInBits, DIType *Ty,
    564                                              DINodeArray Subscripts) {
    565   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
    566                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
    567                                  DINode::FlagVector, Subscripts, 0, nullptr);
    568   trackIfUnresolved(R);
    569   return R;
    570 }
    571 
    572 DISubprogram *DIBuilder::createArtificialSubprogram(DISubprogram *SP) {
    573   auto NewSP = SP->cloneWithFlags(SP->getFlags() | DINode::FlagArtificial);
    574   return MDNode::replaceWithDistinct(std::move(NewSP));
    575 }
    576 
    577 static DIType *createTypeWithFlags(const DIType *Ty,
    578                                    DINode::DIFlags FlagsToSet) {
    579   auto NewTy = Ty->cloneWithFlags(Ty->getFlags() | FlagsToSet);
    580   return MDNode::replaceWithUniqued(std::move(NewTy));
    581 }
    582 
    583 DIType *DIBuilder::createArtificialType(DIType *Ty) {
    584   // FIXME: Restrict this to the nodes where it's valid.
    585   if (Ty->isArtificial())
    586     return Ty;
    587   return createTypeWithFlags(Ty, DINode::FlagArtificial);
    588 }
    589 
    590 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
    591   // FIXME: Restrict this to the nodes where it's valid.
    592   if (Ty->isObjectPointer())
    593     return Ty;
    594   DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
    595   return createTypeWithFlags(Ty, Flags);
    596 }
    597 
    598 void DIBuilder::retainType(DIScope *T) {
    599   assert(T && "Expected non-null type");
    600   assert((isa<DIType>(T) || (isa<DISubprogram>(T) &&
    601                              cast<DISubprogram>(T)->isDefinition() == false)) &&
    602          "Expected type or subprogram declaration");
    603   AllRetainTypes.emplace_back(T);
    604 }
    605 
    606 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
    607 
    608 DICompositeType *
    609 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
    610                              DIFile *F, unsigned Line, unsigned RuntimeLang,
    611                              uint64_t SizeInBits, uint32_t AlignInBits,
    612                              StringRef UniqueIdentifier) {
    613   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
    614   // replaceWithUniqued().
    615   auto *RetTy = DICompositeType::get(
    616       VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
    617       SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang,
    618       nullptr, nullptr, UniqueIdentifier);
    619   trackIfUnresolved(RetTy);
    620   return RetTy;
    621 }
    622 
    623 DICompositeType *DIBuilder::createReplaceableCompositeType(
    624     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
    625     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
    626     DINode::DIFlags Flags, StringRef UniqueIdentifier) {
    627   auto *RetTy =
    628       DICompositeType::getTemporary(
    629           VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
    630           SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
    631           nullptr, UniqueIdentifier)
    632           .release();
    633   trackIfUnresolved(RetTy);
    634   return RetTy;
    635 }
    636 
    637 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
    638   return MDTuple::get(VMContext, Elements);
    639 }
    640 
    641 DIMacroNodeArray
    642 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) {
    643   return MDTuple::get(VMContext, Elements);
    644 }
    645 
    646 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
    647   SmallVector<llvm::Metadata *, 16> Elts;
    648   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
    649     if (Elements[i] && isa<MDNode>(Elements[i]))
    650       Elts.push_back(cast<DIType>(Elements[i]));
    651     else
    652       Elts.push_back(Elements[i]);
    653   }
    654   return DITypeRefArray(MDNode::get(VMContext, Elts));
    655 }
    656 
    657 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
    658   auto *LB = ConstantAsMetadata::get(
    659       ConstantInt::getSigned(Type::getInt64Ty(VMContext), Lo));
    660   auto *CountNode = ConstantAsMetadata::get(
    661       ConstantInt::getSigned(Type::getInt64Ty(VMContext), Count));
    662   return DISubrange::get(VMContext, CountNode, LB, nullptr, nullptr);
    663 }
    664 
    665 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) {
    666   auto *LB = ConstantAsMetadata::get(
    667       ConstantInt::getSigned(Type::getInt64Ty(VMContext), Lo));
    668   return DISubrange::get(VMContext, CountNode, LB, nullptr, nullptr);
    669 }
    670 
    671 DISubrange *DIBuilder::getOrCreateSubrange(Metadata *CountNode, Metadata *LB,
    672                                            Metadata *UB, Metadata *Stride) {
    673   return DISubrange::get(VMContext, CountNode, LB, UB, Stride);
    674 }
    675 
    676 DIGenericSubrange *DIBuilder::getOrCreateGenericSubrange(
    677     DIGenericSubrange::BoundType CountNode, DIGenericSubrange::BoundType LB,
    678     DIGenericSubrange::BoundType UB, DIGenericSubrange::BoundType Stride) {
    679   auto ConvToMetadata = [&](DIGenericSubrange::BoundType Bound) -> Metadata * {
    680     return Bound.is<DIExpression *>() ? (Metadata *)Bound.get<DIExpression *>()
    681                                       : (Metadata *)Bound.get<DIVariable *>();
    682   };
    683   return DIGenericSubrange::get(VMContext, ConvToMetadata(CountNode),
    684                                 ConvToMetadata(LB), ConvToMetadata(UB),
    685                                 ConvToMetadata(Stride));
    686 }
    687 
    688 static void checkGlobalVariableScope(DIScope *Context) {
    689 #ifndef NDEBUG
    690   if (auto *CT =
    691           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
    692     assert(CT->getIdentifier().empty() &&
    693            "Context of a global variable should not be a type with identifier");
    694 #endif
    695 }
    696 
    697 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression(
    698     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
    699     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit,
    700     bool isDefined, DIExpression *Expr,
    701     MDNode *Decl, MDTuple *TemplateParams, uint32_t AlignInBits) {
    702   checkGlobalVariableScope(Context);
    703 
    704   auto *GV = DIGlobalVariable::getDistinct(
    705       VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
    706       LineNumber, Ty, IsLocalToUnit, isDefined, cast_or_null<DIDerivedType>(Decl),
    707       TemplateParams, AlignInBits);
    708   if (!Expr)
    709     Expr = createExpression();
    710   auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr);
    711   AllGVs.push_back(N);
    712   return N;
    713 }
    714 
    715 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
    716     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
    717     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, MDNode *Decl,
    718     MDTuple *TemplateParams, uint32_t AlignInBits) {
    719   checkGlobalVariableScope(Context);
    720 
    721   return DIGlobalVariable::getTemporary(
    722              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
    723              LineNumber, Ty, IsLocalToUnit, false,
    724              cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits)
    725       .release();
    726 }
    727 
    728 static DILocalVariable *createLocalVariable(
    729     LLVMContext &VMContext,
    730     DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables,
    731     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
    732     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
    733     uint32_t AlignInBits) {
    734   // FIXME: Why getNonCompileUnitScope()?
    735   // FIXME: Why is "!Context" okay here?
    736   // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
    737   // the only valid scopes)?
    738   DIScope *Context = getNonCompileUnitScope(Scope);
    739 
    740   auto *Node =
    741       DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
    742                            File, LineNo, Ty, ArgNo, Flags, AlignInBits);
    743   if (AlwaysPreserve) {
    744     // The optimizer may remove local variables. If there is an interest
    745     // to preserve variable info in such situation then stash it in a
    746     // named mdnode.
    747     DISubprogram *Fn = getDISubprogram(Scope);
    748     assert(Fn && "Missing subprogram for local variable");
    749     PreservedVariables[Fn].emplace_back(Node);
    750   }
    751   return Node;
    752 }
    753 
    754 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
    755                                                DIFile *File, unsigned LineNo,
    756                                                DIType *Ty, bool AlwaysPreserve,
    757                                                DINode::DIFlags Flags,
    758                                                uint32_t AlignInBits) {
    759   return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
    760                              /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
    761                              Flags, AlignInBits);
    762 }
    763 
    764 DILocalVariable *DIBuilder::createParameterVariable(
    765     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
    766     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) {
    767   assert(ArgNo && "Expected non-zero argument number for parameter");
    768   return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
    769                              File, LineNo, Ty, AlwaysPreserve, Flags,
    770                              /* AlignInBits */0);
    771 }
    772 
    773 DILabel *DIBuilder::createLabel(
    774     DIScope *Scope, StringRef Name, DIFile *File,
    775     unsigned LineNo, bool AlwaysPreserve) {
    776   DIScope *Context = getNonCompileUnitScope(Scope);
    777 
    778   auto *Node =
    779       DILabel::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
    780                    File, LineNo);
    781 
    782   if (AlwaysPreserve) {
    783     /// The optimizer may remove labels. If there is an interest
    784     /// to preserve label info in such situation then append it to
    785     /// the list of retained nodes of the DISubprogram.
    786     DISubprogram *Fn = getDISubprogram(Scope);
    787     assert(Fn && "Missing subprogram for label");
    788     PreservedLabels[Fn].emplace_back(Node);
    789   }
    790   return Node;
    791 }
    792 
    793 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
    794   return DIExpression::get(VMContext, Addr);
    795 }
    796 
    797 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
    798   // TODO: Remove the callers of this signed version and delete.
    799   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
    800   return createExpression(Addr);
    801 }
    802 
    803 template <class... Ts>
    804 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
    805   if (IsDistinct)
    806     return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
    807   return DISubprogram::get(std::forward<Ts>(Args)...);
    808 }
    809 
    810 DISubprogram *DIBuilder::createFunction(
    811     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
    812     unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
    813     DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
    814     DITemplateParameterArray TParams, DISubprogram *Decl,
    815     DITypeArray ThrownTypes) {
    816   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
    817   auto *Node = getSubprogram(
    818       /*IsDistinct=*/IsDefinition, VMContext, getNonCompileUnitScope(Context),
    819       Name, LinkageName, File, LineNo, Ty, ScopeLine, nullptr, 0, 0, Flags,
    820       SPFlags, IsDefinition ? CUNode : nullptr, TParams, Decl,
    821       MDTuple::getTemporary(VMContext, None).release(), ThrownTypes);
    822 
    823   if (IsDefinition)
    824     AllSubprograms.push_back(Node);
    825   trackIfUnresolved(Node);
    826   return Node;
    827 }
    828 
    829 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
    830     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
    831     unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
    832     DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
    833     DITemplateParameterArray TParams, DISubprogram *Decl,
    834     DITypeArray ThrownTypes) {
    835   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
    836   return DISubprogram::getTemporary(VMContext, getNonCompileUnitScope(Context),
    837                                     Name, LinkageName, File, LineNo, Ty,
    838                                     ScopeLine, nullptr, 0, 0, Flags, SPFlags,
    839                                     IsDefinition ? CUNode : nullptr, TParams,
    840                                     Decl, nullptr, ThrownTypes)
    841       .release();
    842 }
    843 
    844 DISubprogram *DIBuilder::createMethod(
    845     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
    846     unsigned LineNo, DISubroutineType *Ty, unsigned VIndex, int ThisAdjustment,
    847     DIType *VTableHolder, DINode::DIFlags Flags,
    848     DISubprogram::DISPFlags SPFlags, DITemplateParameterArray TParams,
    849     DITypeArray ThrownTypes) {
    850   assert(getNonCompileUnitScope(Context) &&
    851          "Methods should have both a Context and a context that isn't "
    852          "the compile unit.");
    853   // FIXME: Do we want to use different scope/lines?
    854   bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
    855   auto *SP = getSubprogram(
    856       /*IsDistinct=*/IsDefinition, VMContext, cast<DIScope>(Context), Name,
    857       LinkageName, F, LineNo, Ty, LineNo, VTableHolder, VIndex, ThisAdjustment,
    858       Flags, SPFlags, IsDefinition ? CUNode : nullptr, TParams, nullptr,
    859       nullptr, ThrownTypes);
    860 
    861   if (IsDefinition)
    862     AllSubprograms.push_back(SP);
    863   trackIfUnresolved(SP);
    864   return SP;
    865 }
    866 
    867 DICommonBlock *DIBuilder::createCommonBlock(
    868     DIScope *Scope, DIGlobalVariable *Decl, StringRef Name, DIFile *File,
    869     unsigned LineNo) {
    870   return DICommonBlock::get(
    871       VMContext, Scope, Decl, Name, File, LineNo);
    872 }
    873 
    874 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
    875                                         bool ExportSymbols) {
    876 
    877   // It is okay to *not* make anonymous top-level namespaces distinct, because
    878   // all nodes that have an anonymous namespace as their parent scope are
    879   // guaranteed to be unique and/or are linked to their containing
    880   // DICompileUnit. This decision is an explicit tradeoff of link time versus
    881   // memory usage versus code simplicity and may get revisited in the future.
    882   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name,
    883                           ExportSymbols);
    884 }
    885 
    886 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
    887                                   StringRef ConfigurationMacros,
    888                                   StringRef IncludePath, StringRef APINotesFile,
    889                                   DIFile *File, unsigned LineNo, bool IsDecl) {
    890   return DIModule::get(VMContext, File, getNonCompileUnitScope(Scope), Name,
    891                        ConfigurationMacros, IncludePath, APINotesFile, LineNo,
    892                        IsDecl);
    893 }
    894 
    895 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
    896                                                       DIFile *File,
    897                                                       unsigned Discriminator) {
    898   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
    899 }
    900 
    901 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
    902                                               unsigned Line, unsigned Col) {
    903   // Make these distinct, to avoid merging two lexical blocks on the same
    904   // file/line/column.
    905   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
    906                                      File, Line, Col);
    907 }
    908 
    909 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
    910                                       DIExpression *Expr, const DILocation *DL,
    911                                       Instruction *InsertBefore) {
    912   return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(),
    913                        InsertBefore);
    914 }
    915 
    916 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
    917                                       DIExpression *Expr, const DILocation *DL,
    918                                       BasicBlock *InsertAtEnd) {
    919   // If this block already has a terminator then insert this intrinsic before
    920   // the terminator. Otherwise, put it at the end of the block.
    921   Instruction *InsertBefore = InsertAtEnd->getTerminator();
    922   return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore);
    923 }
    924 
    925 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
    926                                     Instruction *InsertBefore) {
    927   return insertLabel(
    928       LabelInfo, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
    929       InsertBefore);
    930 }
    931 
    932 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
    933                                     BasicBlock *InsertAtEnd) {
    934   return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
    935 }
    936 
    937 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
    938                                                 DILocalVariable *VarInfo,
    939                                                 DIExpression *Expr,
    940                                                 const DILocation *DL,
    941                                                 Instruction *InsertBefore) {
    942   return insertDbgValueIntrinsic(
    943       V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
    944       InsertBefore);
    945 }
    946 
    947 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
    948                                                 DILocalVariable *VarInfo,
    949                                                 DIExpression *Expr,
    950                                                 const DILocation *DL,
    951                                                 BasicBlock *InsertAtEnd) {
    952   return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
    953 }
    954 
    955 /// Initialize IRBuilder for inserting dbg.declare and dbg.value intrinsics.
    956 /// This abstracts over the various ways to specify an insert position.
    957 static void initIRBuilder(IRBuilder<> &Builder, const DILocation *DL,
    958                           BasicBlock *InsertBB, Instruction *InsertBefore) {
    959   if (InsertBefore)
    960     Builder.SetInsertPoint(InsertBefore);
    961   else if (InsertBB)
    962     Builder.SetInsertPoint(InsertBB);
    963   Builder.SetCurrentDebugLocation(DL);
    964 }
    965 
    966 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
    967   assert(V && "no value passed to dbg intrinsic");
    968   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
    969 }
    970 
    971 static Function *getDeclareIntrin(Module &M) {
    972   return Intrinsic::getDeclaration(&M, UseDbgAddr ? Intrinsic::dbg_addr
    973                                                   : Intrinsic::dbg_declare);
    974 }
    975 
    976 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
    977                                       DIExpression *Expr, const DILocation *DL,
    978                                       BasicBlock *InsertBB, Instruction *InsertBefore) {
    979   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
    980   assert(DL && "Expected debug loc");
    981   assert(DL->getScope()->getSubprogram() ==
    982              VarInfo->getScope()->getSubprogram() &&
    983          "Expected matching subprograms");
    984   if (!DeclareFn)
    985     DeclareFn = getDeclareIntrin(M);
    986 
    987   trackIfUnresolved(VarInfo);
    988   trackIfUnresolved(Expr);
    989   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
    990                    MetadataAsValue::get(VMContext, VarInfo),
    991                    MetadataAsValue::get(VMContext, Expr)};
    992 
    993   IRBuilder<> B(DL->getContext());
    994   initIRBuilder(B, DL, InsertBB, InsertBefore);
    995   return B.CreateCall(DeclareFn, Args);
    996 }
    997 
    998 Instruction *DIBuilder::insertDbgValueIntrinsic(
    999     Value *V, DILocalVariable *VarInfo, DIExpression *Expr,
   1000     const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
   1001   assert(V && "no value passed to dbg.value");
   1002   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
   1003   assert(DL && "Expected debug loc");
   1004   assert(DL->getScope()->getSubprogram() ==
   1005              VarInfo->getScope()->getSubprogram() &&
   1006          "Expected matching subprograms");
   1007   if (!ValueFn)
   1008     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
   1009 
   1010   trackIfUnresolved(VarInfo);
   1011   trackIfUnresolved(Expr);
   1012   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
   1013                    MetadataAsValue::get(VMContext, VarInfo),
   1014                    MetadataAsValue::get(VMContext, Expr)};
   1015 
   1016   IRBuilder<> B(DL->getContext());
   1017   initIRBuilder(B, DL, InsertBB, InsertBefore);
   1018   return B.CreateCall(ValueFn, Args);
   1019 }
   1020 
   1021 Instruction *DIBuilder::insertLabel(
   1022     DILabel *LabelInfo, const DILocation *DL,
   1023     BasicBlock *InsertBB, Instruction *InsertBefore) {
   1024   assert(LabelInfo && "empty or invalid DILabel* passed to dbg.label");
   1025   assert(DL && "Expected debug loc");
   1026   assert(DL->getScope()->getSubprogram() ==
   1027              LabelInfo->getScope()->getSubprogram() &&
   1028          "Expected matching subprograms");
   1029   if (!LabelFn)
   1030     LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
   1031 
   1032   trackIfUnresolved(LabelInfo);
   1033   Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
   1034 
   1035   IRBuilder<> B(DL->getContext());
   1036   initIRBuilder(B, DL, InsertBB, InsertBefore);
   1037   return B.CreateCall(LabelFn, Args);
   1038 }
   1039 
   1040 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
   1041                                     DIType *VTableHolder) {
   1042   {
   1043     TypedTrackingMDRef<DICompositeType> N(T);
   1044     N->replaceVTableHolder(VTableHolder);
   1045     T = N.get();
   1046   }
   1047 
   1048   // If this didn't create a self-reference, just return.
   1049   if (T != VTableHolder)
   1050     return;
   1051 
   1052   // Look for unresolved operands.  T will drop RAUW support, orphaning any
   1053   // cycles underneath it.
   1054   if (T->isResolved())
   1055     for (const MDOperand &O : T->operands())
   1056       if (auto *N = dyn_cast_or_null<MDNode>(O))
   1057         trackIfUnresolved(N);
   1058 }
   1059 
   1060 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
   1061                               DINodeArray TParams) {
   1062   {
   1063     TypedTrackingMDRef<DICompositeType> N(T);
   1064     if (Elements)
   1065       N->replaceElements(Elements);
   1066     if (TParams)
   1067       N->replaceTemplateParams(DITemplateParameterArray(TParams));
   1068     T = N.get();
   1069   }
   1070 
   1071   // If T isn't resolved, there's no problem.
   1072   if (!T->isResolved())
   1073     return;
   1074 
   1075   // If T is resolved, it may be due to a self-reference cycle.  Track the
   1076   // arrays explicitly if they're unresolved, or else the cycles will be
   1077   // orphaned.
   1078   if (Elements)
   1079     trackIfUnresolved(Elements.get());
   1080   if (TParams)
   1081     trackIfUnresolved(TParams.get());
   1082 }
   1083