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