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