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