1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the DIBuilder. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/DIBuilder.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/IR/Constants.h" 17 #include "llvm/IR/DebugInfo.h" 18 #include "llvm/IR/IntrinsicInst.h" 19 #include "llvm/IR/Module.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/Dwarf.h" 22 23 using namespace llvm; 24 using namespace llvm::dwarf; 25 26 namespace { 27 class HeaderBuilder { 28 /// \brief Whether there are any fields yet. 29 /// 30 /// Note that this is not equivalent to \c Chars.empty(), since \a concat() 31 /// may have been called already with an empty string. 32 bool IsEmpty; 33 SmallVector<char, 256> Chars; 34 35 public: 36 HeaderBuilder() : IsEmpty(true) {} 37 HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {} 38 HeaderBuilder(HeaderBuilder &&X) 39 : IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {} 40 41 template <class Twineable> HeaderBuilder &concat(Twineable &&X) { 42 if (IsEmpty) 43 IsEmpty = false; 44 else 45 Chars.push_back(0); 46 Twine(X).toVector(Chars); 47 return *this; 48 } 49 50 MDString *get(LLVMContext &Context) const { 51 return MDString::get(Context, StringRef(Chars.begin(), Chars.size())); 52 } 53 54 static HeaderBuilder get(unsigned Tag) { 55 return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag)); 56 } 57 }; 58 } 59 60 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes) 61 : M(m), VMContext(M.getContext()), TempEnumTypes(nullptr), 62 TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr), 63 DeclareFn(nullptr), ValueFn(nullptr), 64 AllowUnresolvedNodes(AllowUnresolvedNodes) {} 65 66 void DIBuilder::trackIfUnresolved(MDNode *N) { 67 if (!N) 68 return; 69 if (N->isResolved()) 70 return; 71 72 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes"); 73 UnresolvedNodes.emplace_back(N); 74 } 75 76 void DIBuilder::finalize() { 77 TempEnumTypes->replaceAllUsesWith(MDTuple::get(VMContext, AllEnumTypes)); 78 79 SmallVector<Metadata *, 16> RetainValues; 80 // Declarations and definitions of the same type may be retained. Some 81 // clients RAUW these pairs, leaving duplicates in the retained types 82 // list. Use a set to remove the duplicates while we transform the 83 // TrackingVHs back into Values. 84 SmallPtrSet<Metadata *, 16> RetainSet; 85 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++) 86 if (RetainSet.insert(AllRetainTypes[I]).second) 87 RetainValues.push_back(AllRetainTypes[I]); 88 TempRetainTypes->replaceAllUsesWith(MDTuple::get(VMContext, RetainValues)); 89 90 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms); 91 TempSubprograms->replaceAllUsesWith(SPs.get()); 92 for (auto *SP : SPs) { 93 if (MDTuple *Temp = SP->getVariables().get()) { 94 const auto &PV = PreservedVariables.lookup(SP); 95 SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end()); 96 DINodeArray AV = getOrCreateArray(Variables); 97 TempMDTuple(Temp)->replaceAllUsesWith(AV.get()); 98 } 99 } 100 101 TempGVs->replaceAllUsesWith(MDTuple::get(VMContext, AllGVs)); 102 103 TempImportedModules->replaceAllUsesWith(MDTuple::get( 104 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(), 105 AllImportedModules.end()))); 106 107 // Now that all temp nodes have been replaced or deleted, resolve remaining 108 // cycles. 109 for (const auto &N : UnresolvedNodes) 110 if (N && !N->isResolved()) 111 N->resolveCycles(); 112 UnresolvedNodes.clear(); 113 114 // Can't handle unresolved nodes anymore. 115 AllowUnresolvedNodes = false; 116 } 117 118 /// If N is compile unit return NULL otherwise return N. 119 static DIScope *getNonCompileUnitScope(DIScope *N) { 120 if (!N || isa<DICompileUnit>(N)) 121 return nullptr; 122 return cast<DIScope>(N); 123 } 124 125 DICompileUnit *DIBuilder::createCompileUnit( 126 unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer, 127 bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName, 128 DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) { 129 130 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) || 131 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && 132 "Invalid Language tag"); 133 assert(!Filename.empty() && 134 "Unable to create compile unit without filename"); 135 136 // TODO: Once we make DICompileUnit distinct, stop using temporaries here 137 // (just start with operands assigned to nullptr). 138 TempEnumTypes = MDTuple::getTemporary(VMContext, None); 139 TempRetainTypes = MDTuple::getTemporary(VMContext, None); 140 TempSubprograms = MDTuple::getTemporary(VMContext, None); 141 TempGVs = MDTuple::getTemporary(VMContext, None); 142 TempImportedModules = MDTuple::getTemporary(VMContext, None); 143 144 DICompileUnit *CUNode = DICompileUnit::getDistinct( 145 VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer, 146 isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes.get(), 147 TempRetainTypes.get(), TempSubprograms.get(), TempGVs.get(), 148 TempImportedModules.get(), DWOId); 149 150 // Create a named metadata so that it is easier to find cu in a module. 151 // Note that we only generate this when the caller wants to actually 152 // emit debug information. When we are only interested in tracking 153 // source line locations throughout the backend, we prevent codegen from 154 // emitting debug info in the final output by not generating llvm.dbg.cu. 155 if (EmitDebugInfo) { 156 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); 157 NMD->addOperand(CUNode); 158 } 159 160 trackIfUnresolved(CUNode); 161 return CUNode; 162 } 163 164 static DIImportedEntity * 165 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context, 166 Metadata *NS, unsigned Line, StringRef Name, 167 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) { 168 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name); 169 AllImportedModules.emplace_back(M); 170 return M; 171 } 172 173 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, 174 DINamespace *NS, 175 unsigned Line) { 176 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 177 Context, NS, Line, StringRef(), AllImportedModules); 178 } 179 180 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, 181 DIImportedEntity *NS, 182 unsigned Line) { 183 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 184 Context, NS, Line, StringRef(), AllImportedModules); 185 } 186 187 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M, 188 unsigned Line) { 189 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 190 Context, M, Line, StringRef(), AllImportedModules); 191 } 192 193 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context, 194 DINode *Decl, 195 unsigned Line, 196 StringRef Name) { 197 // Make sure to use the unique identifier based metadata reference for 198 // types that have one. 199 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration, 200 Context, DINodeRef::get(Decl), Line, Name, 201 AllImportedModules); 202 } 203 204 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) { 205 return DIFile::get(VMContext, Filename, Directory); 206 } 207 208 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) { 209 assert(!Name.empty() && "Unable to create enumerator without name"); 210 return DIEnumerator::get(VMContext, Val, Name); 211 } 212 213 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) { 214 assert(!Name.empty() && "Unable to create type without name"); 215 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name); 216 } 217 218 DIBasicType *DIBuilder::createNullPtrType() { 219 return createUnspecifiedType("decltype(nullptr)"); 220 } 221 222 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits, 223 uint64_t AlignInBits, 224 unsigned Encoding) { 225 assert(!Name.empty() && "Unable to create type without name"); 226 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits, 227 AlignInBits, Encoding); 228 } 229 230 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) { 231 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, 232 DITypeRef::get(FromTy), 0, 0, 0, 0); 233 } 234 235 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy, 236 uint64_t SizeInBits, 237 uint64_t AlignInBits, 238 StringRef Name) { 239 // FIXME: Why is there a name here? 240 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name, 241 nullptr, 0, nullptr, DITypeRef::get(PointeeTy), 242 SizeInBits, AlignInBits, 0, 0); 243 } 244 245 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy, 246 DIType *Base, 247 uint64_t SizeInBits, 248 uint64_t AlignInBits) { 249 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "", 250 nullptr, 0, nullptr, DITypeRef::get(PointeeTy), 251 SizeInBits, AlignInBits, 0, 0, 252 DITypeRef::get(Base)); 253 } 254 255 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy) { 256 assert(RTy && "Unable to create reference type"); 257 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, 258 DITypeRef::get(RTy), 0, 0, 0, 0); 259 } 260 261 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name, 262 DIFile *File, unsigned LineNo, 263 DIScope *Context) { 264 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File, 265 LineNo, 266 DIScopeRef::get(getNonCompileUnitScope(Context)), 267 DITypeRef::get(Ty), 0, 0, 0, 0); 268 } 269 270 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) { 271 assert(Ty && "Invalid type!"); 272 assert(FriendTy && "Invalid friend type!"); 273 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, 274 DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0, 275 0, 0); 276 } 277 278 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy, 279 uint64_t BaseOffset, 280 unsigned Flags) { 281 assert(Ty && "Unable to create inheritance"); 282 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr, 283 0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0, 284 BaseOffset, Flags); 285 } 286 287 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name, 288 DIFile *File, unsigned LineNumber, 289 uint64_t SizeInBits, 290 uint64_t AlignInBits, 291 uint64_t OffsetInBits, 292 unsigned Flags, DIType *Ty) { 293 return DIDerivedType::get( 294 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, 295 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 296 SizeInBits, AlignInBits, OffsetInBits, Flags); 297 } 298 299 static ConstantAsMetadata *getConstantOrNull(Constant *C) { 300 if (C) 301 return ConstantAsMetadata::get(C); 302 return nullptr; 303 } 304 305 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, 306 DIFile *File, 307 unsigned LineNumber, 308 DIType *Ty, unsigned Flags, 309 llvm::Constant *Val) { 310 Flags |= DINode::FlagStaticMember; 311 return DIDerivedType::get( 312 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, 313 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0, 314 0, Flags, getConstantOrNull(Val)); 315 } 316 317 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File, 318 unsigned LineNumber, 319 uint64_t SizeInBits, 320 uint64_t AlignInBits, 321 uint64_t OffsetInBits, unsigned Flags, 322 DIType *Ty, MDNode *PropertyNode) { 323 return DIDerivedType::get( 324 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, 325 DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty), 326 SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode); 327 } 328 329 DIObjCProperty * 330 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber, 331 StringRef GetterName, StringRef SetterName, 332 unsigned PropertyAttributes, DIType *Ty) { 333 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName, 334 SetterName, PropertyAttributes, 335 DITypeRef::get(Ty)); 336 } 337 338 DITemplateTypeParameter * 339 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name, 340 DIType *Ty) { 341 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 342 return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty)); 343 } 344 345 static DITemplateValueParameter * 346 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag, 347 DIScope *Context, StringRef Name, DIType *Ty, 348 Metadata *MD) { 349 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 350 return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty), 351 MD); 352 } 353 354 DITemplateValueParameter * 355 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name, 356 DIType *Ty, Constant *Val) { 357 return createTemplateValueParameterHelper( 358 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty, 359 getConstantOrNull(Val)); 360 } 361 362 DITemplateValueParameter * 363 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name, 364 DIType *Ty, StringRef Val) { 365 return createTemplateValueParameterHelper( 366 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty, 367 MDString::get(VMContext, Val)); 368 } 369 370 DITemplateValueParameter * 371 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name, 372 DIType *Ty, DINodeArray Val) { 373 return createTemplateValueParameterHelper( 374 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty, 375 Val.get()); 376 } 377 378 DICompositeType *DIBuilder::createClassType( 379 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 380 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits, 381 unsigned Flags, DIType *DerivedFrom, DINodeArray Elements, 382 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) { 383 assert((!Context || isa<DIScope>(Context)) && 384 "createClassType should be called with a valid Context"); 385 386 auto *R = DICompositeType::get( 387 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 388 DIScopeRef::get(getNonCompileUnitScope(Context)), 389 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags, 390 Elements, 0, DITypeRef::get(VTableHolder), 391 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier); 392 if (!UniqueIdentifier.empty()) 393 retainType(R); 394 trackIfUnresolved(R); 395 return R; 396 } 397 398 DICompositeType *DIBuilder::createStructType( 399 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 400 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags, 401 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang, 402 DIType *VTableHolder, StringRef UniqueIdentifier) { 403 auto *R = DICompositeType::get( 404 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 405 DIScopeRef::get(getNonCompileUnitScope(Context)), 406 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements, 407 RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier); 408 if (!UniqueIdentifier.empty()) 409 retainType(R); 410 trackIfUnresolved(R); 411 return R; 412 } 413 414 DICompositeType *DIBuilder::createUnionType( 415 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 416 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags, 417 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) { 418 auto *R = DICompositeType::get( 419 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber, 420 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits, 421 AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr, 422 UniqueIdentifier); 423 if (!UniqueIdentifier.empty()) 424 retainType(R); 425 trackIfUnresolved(R); 426 return R; 427 } 428 429 DISubroutineType *DIBuilder::createSubroutineType(DIFile *File, 430 DITypeRefArray ParameterTypes, 431 unsigned Flags) { 432 return DISubroutineType::get(VMContext, Flags, ParameterTypes); 433 } 434 435 DICompositeType *DIBuilder::createEnumerationType( 436 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 437 uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements, 438 DIType *UnderlyingType, StringRef UniqueIdentifier) { 439 auto *CTy = DICompositeType::get( 440 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber, 441 DIScopeRef::get(getNonCompileUnitScope(Scope)), 442 DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements, 443 0, nullptr, nullptr, UniqueIdentifier); 444 AllEnumTypes.push_back(CTy); 445 if (!UniqueIdentifier.empty()) 446 retainType(CTy); 447 trackIfUnresolved(CTy); 448 return CTy; 449 } 450 451 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits, 452 DIType *Ty, 453 DINodeArray Subscripts) { 454 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", 455 nullptr, 0, nullptr, DITypeRef::get(Ty), Size, 456 AlignInBits, 0, 0, Subscripts, 0, nullptr); 457 trackIfUnresolved(R); 458 return R; 459 } 460 461 DICompositeType *DIBuilder::createVectorType(uint64_t Size, 462 uint64_t AlignInBits, DIType *Ty, 463 DINodeArray Subscripts) { 464 auto *R = 465 DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0, 466 nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0, 467 DINode::FlagVector, Subscripts, 0, nullptr); 468 trackIfUnresolved(R); 469 return R; 470 } 471 472 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty, 473 unsigned FlagsToSet) { 474 auto NewTy = Ty->clone(); 475 NewTy->setFlags(NewTy->getFlags() | FlagsToSet); 476 return MDNode::replaceWithUniqued(std::move(NewTy)); 477 } 478 479 DIType *DIBuilder::createArtificialType(DIType *Ty) { 480 // FIXME: Restrict this to the nodes where it's valid. 481 if (Ty->isArtificial()) 482 return Ty; 483 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial); 484 } 485 486 DIType *DIBuilder::createObjectPointerType(DIType *Ty) { 487 // FIXME: Restrict this to the nodes where it's valid. 488 if (Ty->isObjectPointer()) 489 return Ty; 490 unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial; 491 return createTypeWithFlags(VMContext, Ty, Flags); 492 } 493 494 void DIBuilder::retainType(DIType *T) { 495 assert(T && "Expected non-null type"); 496 AllRetainTypes.emplace_back(T); 497 } 498 499 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; } 500 501 DICompositeType * 502 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope, 503 DIFile *F, unsigned Line, unsigned RuntimeLang, 504 uint64_t SizeInBits, uint64_t AlignInBits, 505 StringRef UniqueIdentifier) { 506 // FIXME: Define in terms of createReplaceableForwardDecl() by calling 507 // replaceWithUniqued(). 508 auto *RetTy = DICompositeType::get( 509 VMContext, Tag, Name, F, Line, 510 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits, 511 AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr, 512 nullptr, UniqueIdentifier); 513 if (!UniqueIdentifier.empty()) 514 retainType(RetTy); 515 trackIfUnresolved(RetTy); 516 return RetTy; 517 } 518 519 DICompositeType *DIBuilder::createReplaceableCompositeType( 520 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line, 521 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits, 522 unsigned Flags, StringRef UniqueIdentifier) { 523 auto *RetTy = DICompositeType::getTemporary( 524 VMContext, Tag, Name, F, Line, 525 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, 526 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, 527 nullptr, nullptr, UniqueIdentifier) 528 .release(); 529 if (!UniqueIdentifier.empty()) 530 retainType(RetTy); 531 trackIfUnresolved(RetTy); 532 return RetTy; 533 } 534 535 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) { 536 return MDTuple::get(VMContext, Elements); 537 } 538 539 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) { 540 SmallVector<llvm::Metadata *, 16> Elts; 541 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 542 if (Elements[i] && isa<MDNode>(Elements[i])) 543 Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i]))); 544 else 545 Elts.push_back(Elements[i]); 546 } 547 return DITypeRefArray(MDNode::get(VMContext, Elts)); 548 } 549 550 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) { 551 return DISubrange::get(VMContext, Count, Lo); 552 } 553 554 static void checkGlobalVariableScope(DIScope *Context) { 555 #ifndef NDEBUG 556 if (auto *CT = 557 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context))) 558 assert(CT->getIdentifier().empty() && 559 "Context of a global variable should not be a type with identifier"); 560 #endif 561 } 562 563 DIGlobalVariable *DIBuilder::createGlobalVariable( 564 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 565 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val, 566 MDNode *Decl) { 567 checkGlobalVariableScope(Context); 568 569 auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context), 570 Name, LinkageName, F, LineNumber, 571 DITypeRef::get(Ty), isLocalToUnit, true, Val, 572 cast_or_null<DIDerivedType>(Decl)); 573 AllGVs.push_back(N); 574 return N; 575 } 576 577 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl( 578 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 579 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val, 580 MDNode *Decl) { 581 checkGlobalVariableScope(Context); 582 583 return DIGlobalVariable::getTemporary( 584 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F, 585 LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val, 586 cast_or_null<DIDerivedType>(Decl)) 587 .release(); 588 } 589 590 DILocalVariable *DIBuilder::createLocalVariable( 591 unsigned Tag, DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo, 592 DIType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) { 593 // FIXME: Why getNonCompileUnitScope()? 594 // FIXME: Why is "!Context" okay here? 595 // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT 596 // the only valid scopes)? 597 DIScope *Context = getNonCompileUnitScope(Scope); 598 599 auto *Node = DILocalVariable::get( 600 VMContext, Tag, cast_or_null<DILocalScope>(Context), Name, File, LineNo, 601 DITypeRef::get(Ty), ArgNo, Flags); 602 if (AlwaysPreserve) { 603 // The optimizer may remove local variable. If there is an interest 604 // to preserve variable info in such situation then stash it in a 605 // named mdnode. 606 DISubprogram *Fn = getDISubprogram(Scope); 607 assert(Fn && "Missing subprogram for local variable"); 608 PreservedVariables[Fn].emplace_back(Node); 609 } 610 return Node; 611 } 612 613 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) { 614 return DIExpression::get(VMContext, Addr); 615 } 616 617 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) { 618 // TODO: Remove the callers of this signed version and delete. 619 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end()); 620 return createExpression(Addr); 621 } 622 623 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes, 624 unsigned SizeInBytes) { 625 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes}; 626 return DIExpression::get(VMContext, Addr); 627 } 628 629 DISubprogram *DIBuilder::createFunction(DIScopeRef Context, StringRef Name, 630 StringRef LinkageName, DIFile *File, 631 unsigned LineNo, DISubroutineType *Ty, 632 bool isLocalToUnit, bool isDefinition, 633 unsigned ScopeLine, unsigned Flags, 634 bool isOptimized, Function *Fn, 635 MDNode *TParams, MDNode *Decl) { 636 // dragonegg does not generate identifier for types, so using an empty map 637 // to resolve the context should be fine. 638 DITypeIdentifierMap EmptyMap; 639 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File, 640 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, 641 Flags, isOptimized, Fn, TParams, Decl); 642 } 643 644 DISubprogram *DIBuilder::createFunction(DIScope *Context, StringRef Name, 645 StringRef LinkageName, DIFile *File, 646 unsigned LineNo, DISubroutineType *Ty, 647 bool isLocalToUnit, bool isDefinition, 648 unsigned ScopeLine, unsigned Flags, 649 bool isOptimized, Function *Fn, 650 MDNode *TParams, MDNode *Decl) { 651 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type && 652 "function types should be subroutines"); 653 auto *Node = DISubprogram::get( 654 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name, 655 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, 656 nullptr, 0, 0, Flags, isOptimized, Fn, cast_or_null<MDTuple>(TParams), 657 cast_or_null<DISubprogram>(Decl), 658 MDTuple::getTemporary(VMContext, None).release()); 659 660 if (isDefinition) 661 AllSubprograms.push_back(Node); 662 trackIfUnresolved(Node); 663 return Node; 664 } 665 666 DISubprogram *DIBuilder::createTempFunctionFwdDecl( 667 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, 668 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 669 bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized, 670 Function *Fn, MDNode *TParams, MDNode *Decl) { 671 return DISubprogram::getTemporary( 672 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name, 673 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, 674 ScopeLine, nullptr, 0, 0, Flags, isOptimized, Fn, 675 cast_or_null<MDTuple>(TParams), cast_or_null<DISubprogram>(Decl), 676 nullptr) 677 .release(); 678 } 679 680 DISubprogram * 681 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName, 682 DIFile *F, unsigned LineNo, DISubroutineType *Ty, 683 bool isLocalToUnit, bool isDefinition, unsigned VK, 684 unsigned VIndex, DIType *VTableHolder, unsigned Flags, 685 bool isOptimized, Function *Fn, MDNode *TParam) { 686 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type && 687 "function types should be subroutines"); 688 assert(getNonCompileUnitScope(Context) && 689 "Methods should have both a Context and a context that isn't " 690 "the compile unit."); 691 // FIXME: Do we want to use different scope/lines? 692 auto *SP = DISubprogram::get( 693 VMContext, DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F, 694 LineNo, Ty, isLocalToUnit, isDefinition, LineNo, 695 DITypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn, 696 cast_or_null<MDTuple>(TParam), nullptr, nullptr); 697 698 if (isDefinition) 699 AllSubprograms.push_back(SP); 700 trackIfUnresolved(SP); 701 return SP; 702 } 703 704 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name, 705 DIFile *File, unsigned LineNo) { 706 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name, 707 LineNo); 708 } 709 710 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name, 711 StringRef ConfigurationMacros, 712 StringRef IncludePath, 713 StringRef ISysRoot) { 714 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name, 715 ConfigurationMacros, IncludePath, ISysRoot); 716 } 717 718 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope, 719 DIFile *File, 720 unsigned Discriminator) { 721 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator); 722 } 723 724 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File, 725 unsigned Line, unsigned Col) { 726 // Make these distinct, to avoid merging two lexical blocks on the same 727 // file/line/column. 728 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope), 729 File, Line, Col); 730 } 731 732 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) { 733 assert(V && "no value passed to dbg intrinsic"); 734 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V)); 735 } 736 737 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) { 738 I->setDebugLoc(const_cast<DILocation *>(DL)); 739 return I; 740 } 741 742 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 743 DIExpression *Expr, const DILocation *DL, 744 Instruction *InsertBefore) { 745 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); 746 assert(DL && "Expected debug loc"); 747 assert(DL->getScope()->getSubprogram() == 748 VarInfo->getScope()->getSubprogram() && 749 "Expected matching subprograms"); 750 if (!DeclareFn) 751 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); 752 753 trackIfUnresolved(VarInfo); 754 trackIfUnresolved(Expr); 755 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), 756 MetadataAsValue::get(VMContext, VarInfo), 757 MetadataAsValue::get(VMContext, Expr)}; 758 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL); 759 } 760 761 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 762 DIExpression *Expr, const DILocation *DL, 763 BasicBlock *InsertAtEnd) { 764 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); 765 assert(DL && "Expected debug loc"); 766 assert(DL->getScope()->getSubprogram() == 767 VarInfo->getScope()->getSubprogram() && 768 "Expected matching subprograms"); 769 if (!DeclareFn) 770 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); 771 772 trackIfUnresolved(VarInfo); 773 trackIfUnresolved(Expr); 774 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), 775 MetadataAsValue::get(VMContext, VarInfo), 776 MetadataAsValue::get(VMContext, Expr)}; 777 778 // If this block already has a terminator then insert this intrinsic 779 // before the terminator. 780 if (TerminatorInst *T = InsertAtEnd->getTerminator()) 781 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL); 782 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL); 783 } 784 785 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset, 786 DILocalVariable *VarInfo, 787 DIExpression *Expr, 788 const DILocation *DL, 789 Instruction *InsertBefore) { 790 assert(V && "no value passed to dbg.value"); 791 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); 792 assert(DL && "Expected debug loc"); 793 assert(DL->getScope()->getSubprogram() == 794 VarInfo->getScope()->getSubprogram() && 795 "Expected matching subprograms"); 796 if (!ValueFn) 797 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); 798 799 trackIfUnresolved(VarInfo); 800 trackIfUnresolved(Expr); 801 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), 802 ConstantInt::get(Type::getInt64Ty(VMContext), Offset), 803 MetadataAsValue::get(VMContext, VarInfo), 804 MetadataAsValue::get(VMContext, Expr)}; 805 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL); 806 } 807 808 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset, 809 DILocalVariable *VarInfo, 810 DIExpression *Expr, 811 const DILocation *DL, 812 BasicBlock *InsertAtEnd) { 813 assert(V && "no value passed to dbg.value"); 814 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); 815 assert(DL && "Expected debug loc"); 816 assert(DL->getScope()->getSubprogram() == 817 VarInfo->getScope()->getSubprogram() && 818 "Expected matching subprograms"); 819 if (!ValueFn) 820 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); 821 822 trackIfUnresolved(VarInfo); 823 trackIfUnresolved(Expr); 824 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), 825 ConstantInt::get(Type::getInt64Ty(VMContext), Offset), 826 MetadataAsValue::get(VMContext, VarInfo), 827 MetadataAsValue::get(VMContext, Expr)}; 828 829 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL); 830 } 831 832 void DIBuilder::replaceVTableHolder(DICompositeType *&T, 833 DICompositeType *VTableHolder) { 834 { 835 TypedTrackingMDRef<DICompositeType> N(T); 836 N->replaceVTableHolder(DITypeRef::get(VTableHolder)); 837 T = N.get(); 838 } 839 840 // If this didn't create a self-reference, just return. 841 if (T != VTableHolder) 842 return; 843 844 // Look for unresolved operands. T will drop RAUW support, orphaning any 845 // cycles underneath it. 846 if (T->isResolved()) 847 for (const MDOperand &O : T->operands()) 848 if (auto *N = dyn_cast_or_null<MDNode>(O)) 849 trackIfUnresolved(N); 850 } 851 852 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements, 853 DINodeArray TParams) { 854 { 855 TypedTrackingMDRef<DICompositeType> N(T); 856 if (Elements) 857 N->replaceElements(Elements); 858 if (TParams) 859 N->replaceTemplateParams(DITemplateParameterArray(TParams)); 860 T = N.get(); 861 } 862 863 // If T isn't resolved, there's no problem. 864 if (!T->isResolved()) 865 return; 866 867 // If "T" is resolved, it may be due to a self-reference cycle. Track the 868 // arrays explicitly if they're unresolved, or else the cycles will be 869 // orphaned. 870 if (Elements) 871 trackIfUnresolved(Elements.get()); 872 if (TParams) 873 trackIfUnresolved(TParams.get()); 874 } 875