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