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