1 //===- DebugInfoMetadata.cpp - Implement debug info metadata --------------===// 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 debug info Metadata classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/DebugInfoMetadata.h" 14 #include "LLVMContextImpl.h" 15 #include "MetadataImpl.h" 16 #include "llvm/ADT/SmallSet.h" 17 #include "llvm/ADT/StringSwitch.h" 18 #include "llvm/BinaryFormat/Dwarf.h" 19 #include "llvm/IR/Function.h" 20 #include "llvm/IR/Type.h" 21 #include "llvm/IR/Value.h" 22 23 #include <numeric> 24 25 using namespace llvm; 26 27 namespace llvm { 28 // Use FS-AFDO discriminator. 29 cl::opt<bool> EnableFSDiscriminator( 30 "enable-fs-discriminator", cl::Hidden, 31 cl::desc("Enable adding flow sensitive discriminators")); 32 } // namespace llvm 33 34 const DIExpression::FragmentInfo DebugVariable::DefaultFragment = { 35 std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()}; 36 37 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line, 38 unsigned Column, ArrayRef<Metadata *> MDs, 39 bool ImplicitCode) 40 : MDNode(C, DILocationKind, Storage, MDs) { 41 assert((MDs.size() == 1 || MDs.size() == 2) && 42 "Expected a scope and optional inlined-at"); 43 44 // Set line and column. 45 assert(Column < (1u << 16) && "Expected 16-bit column"); 46 47 SubclassData32 = Line; 48 SubclassData16 = Column; 49 50 setImplicitCode(ImplicitCode); 51 } 52 53 static void adjustColumn(unsigned &Column) { 54 // Set to unknown on overflow. We only have 16 bits to play with here. 55 if (Column >= (1u << 16)) 56 Column = 0; 57 } 58 59 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line, 60 unsigned Column, Metadata *Scope, 61 Metadata *InlinedAt, bool ImplicitCode, 62 StorageType Storage, bool ShouldCreate) { 63 // Fixup column. 64 adjustColumn(Column); 65 66 if (Storage == Uniqued) { 67 if (auto *N = getUniqued(Context.pImpl->DILocations, 68 DILocationInfo::KeyTy(Line, Column, Scope, 69 InlinedAt, ImplicitCode))) 70 return N; 71 if (!ShouldCreate) 72 return nullptr; 73 } else { 74 assert(ShouldCreate && "Expected non-uniqued nodes to always be created"); 75 } 76 77 SmallVector<Metadata *, 2> Ops; 78 Ops.push_back(Scope); 79 if (InlinedAt) 80 Ops.push_back(InlinedAt); 81 return storeImpl(new (Ops.size(), Storage) DILocation( 82 Context, Storage, Line, Column, Ops, ImplicitCode), 83 Storage, Context.pImpl->DILocations); 84 } 85 86 const DILocation * 87 DILocation::getMergedLocations(ArrayRef<const DILocation *> Locs) { 88 if (Locs.empty()) 89 return nullptr; 90 if (Locs.size() == 1) 91 return Locs[0]; 92 auto *Merged = Locs[0]; 93 for (const DILocation *L : llvm::drop_begin(Locs)) { 94 Merged = getMergedLocation(Merged, L); 95 if (Merged == nullptr) 96 break; 97 } 98 return Merged; 99 } 100 101 const DILocation *DILocation::getMergedLocation(const DILocation *LocA, 102 const DILocation *LocB) { 103 if (!LocA || !LocB) 104 return nullptr; 105 106 if (LocA == LocB) 107 return LocA; 108 109 SmallPtrSet<DILocation *, 5> InlinedLocationsA; 110 for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt()) 111 InlinedLocationsA.insert(L); 112 SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations; 113 DIScope *S = LocA->getScope(); 114 DILocation *L = LocA->getInlinedAt(); 115 while (S) { 116 Locations.insert(std::make_pair(S, L)); 117 S = S->getScope(); 118 if (!S && L) { 119 S = L->getScope(); 120 L = L->getInlinedAt(); 121 } 122 } 123 const DILocation *Result = LocB; 124 S = LocB->getScope(); 125 L = LocB->getInlinedAt(); 126 while (S) { 127 if (Locations.count(std::make_pair(S, L))) 128 break; 129 S = S->getScope(); 130 if (!S && L) { 131 S = L->getScope(); 132 L = L->getInlinedAt(); 133 } 134 } 135 136 // If the two locations are irreconsilable, just pick one. This is misleading, 137 // but on the other hand, it's a "line 0" location. 138 if (!S || !isa<DILocalScope>(S)) 139 S = LocA->getScope(); 140 return DILocation::get(Result->getContext(), 0, 0, S, L); 141 } 142 143 Optional<unsigned> DILocation::encodeDiscriminator(unsigned BD, unsigned DF, 144 unsigned CI) { 145 std::array<unsigned, 3> Components = {BD, DF, CI}; 146 uint64_t RemainingWork = 0U; 147 // We use RemainingWork to figure out if we have no remaining components to 148 // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to 149 // encode anything for the latter 2. 150 // Since any of the input components is at most 32 bits, their sum will be 151 // less than 34 bits, and thus RemainingWork won't overflow. 152 RemainingWork = 153 std::accumulate(Components.begin(), Components.end(), RemainingWork); 154 155 int I = 0; 156 unsigned Ret = 0; 157 unsigned NextBitInsertionIndex = 0; 158 while (RemainingWork > 0) { 159 unsigned C = Components[I++]; 160 RemainingWork -= C; 161 unsigned EC = encodeComponent(C); 162 Ret |= (EC << NextBitInsertionIndex); 163 NextBitInsertionIndex += encodingBits(C); 164 } 165 166 // Encoding may be unsuccessful because of overflow. We determine success by 167 // checking equivalence of components before & after encoding. Alternatively, 168 // we could determine Success during encoding, but the current alternative is 169 // simpler. 170 unsigned TBD, TDF, TCI = 0; 171 decodeDiscriminator(Ret, TBD, TDF, TCI); 172 if (TBD == BD && TDF == DF && TCI == CI) 173 return Ret; 174 return None; 175 } 176 177 void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF, 178 unsigned &CI) { 179 BD = getUnsignedFromPrefixEncoding(D); 180 DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D)); 181 CI = getUnsignedFromPrefixEncoding( 182 getNextComponentInDiscriminator(getNextComponentInDiscriminator(D))); 183 } 184 dwarf::Tag DINode::getTag() const { return (dwarf::Tag)SubclassData16; } 185 186 DINode::DIFlags DINode::getFlag(StringRef Flag) { 187 return StringSwitch<DIFlags>(Flag) 188 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME) 189 #include "llvm/IR/DebugInfoFlags.def" 190 .Default(DINode::FlagZero); 191 } 192 193 StringRef DINode::getFlagString(DIFlags Flag) { 194 switch (Flag) { 195 #define HANDLE_DI_FLAG(ID, NAME) \ 196 case Flag##NAME: \ 197 return "DIFlag" #NAME; 198 #include "llvm/IR/DebugInfoFlags.def" 199 } 200 return ""; 201 } 202 203 DINode::DIFlags DINode::splitFlags(DIFlags Flags, 204 SmallVectorImpl<DIFlags> &SplitFlags) { 205 // Flags that are packed together need to be specially handled, so 206 // that, for example, we emit "DIFlagPublic" and not 207 // "DIFlagPrivate | DIFlagProtected". 208 if (DIFlags A = Flags & FlagAccessibility) { 209 if (A == FlagPrivate) 210 SplitFlags.push_back(FlagPrivate); 211 else if (A == FlagProtected) 212 SplitFlags.push_back(FlagProtected); 213 else 214 SplitFlags.push_back(FlagPublic); 215 Flags &= ~A; 216 } 217 if (DIFlags R = Flags & FlagPtrToMemberRep) { 218 if (R == FlagSingleInheritance) 219 SplitFlags.push_back(FlagSingleInheritance); 220 else if (R == FlagMultipleInheritance) 221 SplitFlags.push_back(FlagMultipleInheritance); 222 else 223 SplitFlags.push_back(FlagVirtualInheritance); 224 Flags &= ~R; 225 } 226 if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) { 227 Flags &= ~FlagIndirectVirtualBase; 228 SplitFlags.push_back(FlagIndirectVirtualBase); 229 } 230 231 #define HANDLE_DI_FLAG(ID, NAME) \ 232 if (DIFlags Bit = Flags & Flag##NAME) { \ 233 SplitFlags.push_back(Bit); \ 234 Flags &= ~Bit; \ 235 } 236 #include "llvm/IR/DebugInfoFlags.def" 237 return Flags; 238 } 239 240 DIScope *DIScope::getScope() const { 241 if (auto *T = dyn_cast<DIType>(this)) 242 return T->getScope(); 243 244 if (auto *SP = dyn_cast<DISubprogram>(this)) 245 return SP->getScope(); 246 247 if (auto *LB = dyn_cast<DILexicalBlockBase>(this)) 248 return LB->getScope(); 249 250 if (auto *NS = dyn_cast<DINamespace>(this)) 251 return NS->getScope(); 252 253 if (auto *CB = dyn_cast<DICommonBlock>(this)) 254 return CB->getScope(); 255 256 if (auto *M = dyn_cast<DIModule>(this)) 257 return M->getScope(); 258 259 assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) && 260 "Unhandled type of scope."); 261 return nullptr; 262 } 263 264 StringRef DIScope::getName() const { 265 if (auto *T = dyn_cast<DIType>(this)) 266 return T->getName(); 267 if (auto *SP = dyn_cast<DISubprogram>(this)) 268 return SP->getName(); 269 if (auto *NS = dyn_cast<DINamespace>(this)) 270 return NS->getName(); 271 if (auto *CB = dyn_cast<DICommonBlock>(this)) 272 return CB->getName(); 273 if (auto *M = dyn_cast<DIModule>(this)) 274 return M->getName(); 275 assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) || 276 isa<DICompileUnit>(this)) && 277 "Unhandled type of scope."); 278 return ""; 279 } 280 281 #ifndef NDEBUG 282 static bool isCanonical(const MDString *S) { 283 return !S || !S->getString().empty(); 284 } 285 #endif 286 287 dwarf::Tag GenericDINode::getTag() const { return (dwarf::Tag)SubclassData16; } 288 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag, 289 MDString *Header, 290 ArrayRef<Metadata *> DwarfOps, 291 StorageType Storage, bool ShouldCreate) { 292 unsigned Hash = 0; 293 if (Storage == Uniqued) { 294 GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps); 295 if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key)) 296 return N; 297 if (!ShouldCreate) 298 return nullptr; 299 Hash = Key.getHash(); 300 } else { 301 assert(ShouldCreate && "Expected non-uniqued nodes to always be created"); 302 } 303 304 // Use a nullptr for empty headers. 305 assert(isCanonical(Header) && "Expected canonical MDString"); 306 Metadata *PreOps[] = {Header}; 307 return storeImpl(new (DwarfOps.size() + 1, Storage) GenericDINode( 308 Context, Storage, Hash, Tag, PreOps, DwarfOps), 309 Storage, Context.pImpl->GenericDINodes); 310 } 311 312 void GenericDINode::recalculateHash() { 313 setHash(GenericDINodeInfo::KeyTy::calculateHash(this)); 314 } 315 316 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__ 317 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS 318 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS) \ 319 do { \ 320 if (Storage == Uniqued) { \ 321 if (auto *N = getUniqued(Context.pImpl->CLASS##s, \ 322 CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS)))) \ 323 return N; \ 324 if (!ShouldCreate) \ 325 return nullptr; \ 326 } else { \ 327 assert(ShouldCreate && \ 328 "Expected non-uniqued nodes to always be created"); \ 329 } \ 330 } while (false) 331 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS) \ 332 return storeImpl(new (array_lengthof(OPS), Storage) \ 333 CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \ 334 Storage, Context.pImpl->CLASS##s) 335 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS) \ 336 return storeImpl(new (0u, Storage) \ 337 CLASS(Context, Storage, UNWRAP_ARGS(ARGS)), \ 338 Storage, Context.pImpl->CLASS##s) 339 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS) \ 340 return storeImpl(new (array_lengthof(OPS), Storage) \ 341 CLASS(Context, Storage, OPS), \ 342 Storage, Context.pImpl->CLASS##s) 343 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS) \ 344 return storeImpl(new (NUM_OPS, Storage) \ 345 CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \ 346 Storage, Context.pImpl->CLASS##s) 347 348 DISubrange::DISubrange(LLVMContext &C, StorageType Storage, 349 ArrayRef<Metadata *> Ops) 350 : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, Ops) {} 351 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo, 352 StorageType Storage, bool ShouldCreate) { 353 auto *CountNode = ConstantAsMetadata::get( 354 ConstantInt::getSigned(Type::getInt64Ty(Context), Count)); 355 auto *LB = ConstantAsMetadata::get( 356 ConstantInt::getSigned(Type::getInt64Ty(Context), Lo)); 357 return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage, 358 ShouldCreate); 359 } 360 361 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode, 362 int64_t Lo, StorageType Storage, 363 bool ShouldCreate) { 364 auto *LB = ConstantAsMetadata::get( 365 ConstantInt::getSigned(Type::getInt64Ty(Context), Lo)); 366 return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage, 367 ShouldCreate); 368 } 369 370 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode, 371 Metadata *LB, Metadata *UB, Metadata *Stride, 372 StorageType Storage, bool ShouldCreate) { 373 DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride)); 374 Metadata *Ops[] = {CountNode, LB, UB, Stride}; 375 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops); 376 } 377 378 DISubrange::BoundType DISubrange::getCount() const { 379 Metadata *CB = getRawCountNode(); 380 if (!CB) 381 return BoundType(); 382 383 assert((isa<ConstantAsMetadata>(CB) || isa<DIVariable>(CB) || 384 isa<DIExpression>(CB)) && 385 "Count must be signed constant or DIVariable or DIExpression"); 386 387 if (auto *MD = dyn_cast<ConstantAsMetadata>(CB)) 388 return BoundType(cast<ConstantInt>(MD->getValue())); 389 390 if (auto *MD = dyn_cast<DIVariable>(CB)) 391 return BoundType(MD); 392 393 if (auto *MD = dyn_cast<DIExpression>(CB)) 394 return BoundType(MD); 395 396 return BoundType(); 397 } 398 399 DISubrange::BoundType DISubrange::getLowerBound() const { 400 Metadata *LB = getRawLowerBound(); 401 if (!LB) 402 return BoundType(); 403 404 assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) || 405 isa<DIExpression>(LB)) && 406 "LowerBound must be signed constant or DIVariable or DIExpression"); 407 408 if (auto *MD = dyn_cast<ConstantAsMetadata>(LB)) 409 return BoundType(cast<ConstantInt>(MD->getValue())); 410 411 if (auto *MD = dyn_cast<DIVariable>(LB)) 412 return BoundType(MD); 413 414 if (auto *MD = dyn_cast<DIExpression>(LB)) 415 return BoundType(MD); 416 417 return BoundType(); 418 } 419 420 DISubrange::BoundType DISubrange::getUpperBound() const { 421 Metadata *UB = getRawUpperBound(); 422 if (!UB) 423 return BoundType(); 424 425 assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) || 426 isa<DIExpression>(UB)) && 427 "UpperBound must be signed constant or DIVariable or DIExpression"); 428 429 if (auto *MD = dyn_cast<ConstantAsMetadata>(UB)) 430 return BoundType(cast<ConstantInt>(MD->getValue())); 431 432 if (auto *MD = dyn_cast<DIVariable>(UB)) 433 return BoundType(MD); 434 435 if (auto *MD = dyn_cast<DIExpression>(UB)) 436 return BoundType(MD); 437 438 return BoundType(); 439 } 440 441 DISubrange::BoundType DISubrange::getStride() const { 442 Metadata *ST = getRawStride(); 443 if (!ST) 444 return BoundType(); 445 446 assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) || 447 isa<DIExpression>(ST)) && 448 "Stride must be signed constant or DIVariable or DIExpression"); 449 450 if (auto *MD = dyn_cast<ConstantAsMetadata>(ST)) 451 return BoundType(cast<ConstantInt>(MD->getValue())); 452 453 if (auto *MD = dyn_cast<DIVariable>(ST)) 454 return BoundType(MD); 455 456 if (auto *MD = dyn_cast<DIExpression>(ST)) 457 return BoundType(MD); 458 459 return BoundType(); 460 } 461 DIGenericSubrange::DIGenericSubrange(LLVMContext &C, StorageType Storage, 462 ArrayRef<Metadata *> Ops) 463 : DINode(C, DIGenericSubrangeKind, Storage, dwarf::DW_TAG_generic_subrange, 464 Ops) {} 465 466 DIGenericSubrange *DIGenericSubrange::getImpl(LLVMContext &Context, 467 Metadata *CountNode, Metadata *LB, 468 Metadata *UB, Metadata *Stride, 469 StorageType Storage, 470 bool ShouldCreate) { 471 DEFINE_GETIMPL_LOOKUP(DIGenericSubrange, (CountNode, LB, UB, Stride)); 472 Metadata *Ops[] = {CountNode, LB, UB, Stride}; 473 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGenericSubrange, Ops); 474 } 475 476 DIGenericSubrange::BoundType DIGenericSubrange::getCount() const { 477 Metadata *CB = getRawCountNode(); 478 if (!CB) 479 return BoundType(); 480 481 assert((isa<DIVariable>(CB) || isa<DIExpression>(CB)) && 482 "Count must be signed constant or DIVariable or DIExpression"); 483 484 if (auto *MD = dyn_cast<DIVariable>(CB)) 485 return BoundType(MD); 486 487 if (auto *MD = dyn_cast<DIExpression>(CB)) 488 return BoundType(MD); 489 490 return BoundType(); 491 } 492 493 DIGenericSubrange::BoundType DIGenericSubrange::getLowerBound() const { 494 Metadata *LB = getRawLowerBound(); 495 if (!LB) 496 return BoundType(); 497 498 assert((isa<DIVariable>(LB) || isa<DIExpression>(LB)) && 499 "LowerBound must be signed constant or DIVariable or DIExpression"); 500 501 if (auto *MD = dyn_cast<DIVariable>(LB)) 502 return BoundType(MD); 503 504 if (auto *MD = dyn_cast<DIExpression>(LB)) 505 return BoundType(MD); 506 507 return BoundType(); 508 } 509 510 DIGenericSubrange::BoundType DIGenericSubrange::getUpperBound() const { 511 Metadata *UB = getRawUpperBound(); 512 if (!UB) 513 return BoundType(); 514 515 assert((isa<DIVariable>(UB) || isa<DIExpression>(UB)) && 516 "UpperBound must be signed constant or DIVariable or DIExpression"); 517 518 if (auto *MD = dyn_cast<DIVariable>(UB)) 519 return BoundType(MD); 520 521 if (auto *MD = dyn_cast<DIExpression>(UB)) 522 return BoundType(MD); 523 524 return BoundType(); 525 } 526 527 DIGenericSubrange::BoundType DIGenericSubrange::getStride() const { 528 Metadata *ST = getRawStride(); 529 if (!ST) 530 return BoundType(); 531 532 assert((isa<DIVariable>(ST) || isa<DIExpression>(ST)) && 533 "Stride must be signed constant or DIVariable or DIExpression"); 534 535 if (auto *MD = dyn_cast<DIVariable>(ST)) 536 return BoundType(MD); 537 538 if (auto *MD = dyn_cast<DIExpression>(ST)) 539 return BoundType(MD); 540 541 return BoundType(); 542 } 543 544 DIEnumerator::DIEnumerator(LLVMContext &C, StorageType Storage, 545 const APInt &Value, bool IsUnsigned, 546 ArrayRef<Metadata *> Ops) 547 : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops), 548 Value(Value) { 549 SubclassData32 = IsUnsigned; 550 } 551 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value, 552 bool IsUnsigned, MDString *Name, 553 StorageType Storage, bool ShouldCreate) { 554 assert(isCanonical(Name) && "Expected canonical MDString"); 555 DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name)); 556 Metadata *Ops[] = {Name}; 557 DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops); 558 } 559 560 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag, 561 MDString *Name, uint64_t SizeInBits, 562 uint32_t AlignInBits, unsigned Encoding, 563 DIFlags Flags, StorageType Storage, 564 bool ShouldCreate) { 565 assert(isCanonical(Name) && "Expected canonical MDString"); 566 DEFINE_GETIMPL_LOOKUP(DIBasicType, 567 (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags)); 568 Metadata *Ops[] = {nullptr, nullptr, Name}; 569 DEFINE_GETIMPL_STORE(DIBasicType, 570 (Tag, SizeInBits, AlignInBits, Encoding, Flags), Ops); 571 } 572 573 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const { 574 switch (getEncoding()) { 575 case dwarf::DW_ATE_signed: 576 case dwarf::DW_ATE_signed_char: 577 return Signedness::Signed; 578 case dwarf::DW_ATE_unsigned: 579 case dwarf::DW_ATE_unsigned_char: 580 return Signedness::Unsigned; 581 default: 582 return None; 583 } 584 } 585 586 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag, 587 MDString *Name, Metadata *StringLength, 588 Metadata *StringLengthExp, 589 Metadata *StringLocationExp, 590 uint64_t SizeInBits, uint32_t AlignInBits, 591 unsigned Encoding, StorageType Storage, 592 bool ShouldCreate) { 593 assert(isCanonical(Name) && "Expected canonical MDString"); 594 DEFINE_GETIMPL_LOOKUP(DIStringType, 595 (Tag, Name, StringLength, StringLengthExp, 596 StringLocationExp, SizeInBits, AlignInBits, Encoding)); 597 Metadata *Ops[] = {nullptr, nullptr, Name, 598 StringLength, StringLengthExp, StringLocationExp}; 599 DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding), 600 Ops); 601 } 602 DIType *DIDerivedType::getClassType() const { 603 assert(getTag() == dwarf::DW_TAG_ptr_to_member_type); 604 return cast_or_null<DIType>(getExtraData()); 605 } 606 uint32_t DIDerivedType::getVBPtrOffset() const { 607 assert(getTag() == dwarf::DW_TAG_inheritance); 608 if (auto *CM = cast_or_null<ConstantAsMetadata>(getExtraData())) 609 if (auto *CI = dyn_cast_or_null<ConstantInt>(CM->getValue())) 610 return static_cast<uint32_t>(CI->getZExtValue()); 611 return 0; 612 } 613 Constant *DIDerivedType::getStorageOffsetInBits() const { 614 assert(getTag() == dwarf::DW_TAG_member && isBitField()); 615 if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) 616 return C->getValue(); 617 return nullptr; 618 } 619 620 Constant *DIDerivedType::getConstant() const { 621 assert(getTag() == dwarf::DW_TAG_member && isStaticMember()); 622 if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) 623 return C->getValue(); 624 return nullptr; 625 } 626 Constant *DIDerivedType::getDiscriminantValue() const { 627 assert(getTag() == dwarf::DW_TAG_member && !isStaticMember()); 628 if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) 629 return C->getValue(); 630 return nullptr; 631 } 632 633 DIDerivedType *DIDerivedType::getImpl( 634 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File, 635 unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, 636 uint32_t AlignInBits, uint64_t OffsetInBits, 637 Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData, 638 Metadata *Annotations, StorageType Storage, bool ShouldCreate) { 639 assert(isCanonical(Name) && "Expected canonical MDString"); 640 DEFINE_GETIMPL_LOOKUP(DIDerivedType, 641 (Tag, Name, File, Line, Scope, BaseType, SizeInBits, 642 AlignInBits, OffsetInBits, DWARFAddressSpace, Flags, 643 ExtraData, Annotations)); 644 Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData, Annotations}; 645 DEFINE_GETIMPL_STORE(DIDerivedType, 646 (Tag, Line, SizeInBits, AlignInBits, OffsetInBits, 647 DWARFAddressSpace, Flags), 648 Ops); 649 } 650 651 DICompositeType *DICompositeType::getImpl( 652 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File, 653 unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, 654 uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, 655 Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, 656 Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator, 657 Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, 658 Metadata *Rank, Metadata *Annotations, StorageType Storage, 659 bool ShouldCreate) { 660 assert(isCanonical(Name) && "Expected canonical MDString"); 661 662 // Keep this in sync with buildODRType. 663 DEFINE_GETIMPL_LOOKUP(DICompositeType, 664 (Tag, Name, File, Line, Scope, BaseType, SizeInBits, 665 AlignInBits, OffsetInBits, Flags, Elements, 666 RuntimeLang, VTableHolder, TemplateParams, Identifier, 667 Discriminator, DataLocation, Associated, Allocated, 668 Rank, Annotations)); 669 Metadata *Ops[] = {File, Scope, Name, BaseType, 670 Elements, VTableHolder, TemplateParams, Identifier, 671 Discriminator, DataLocation, Associated, Allocated, 672 Rank, Annotations}; 673 DEFINE_GETIMPL_STORE( 674 DICompositeType, 675 (Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, Flags), 676 Ops); 677 } 678 679 DICompositeType *DICompositeType::buildODRType( 680 LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, 681 Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, 682 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 683 DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, 684 Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, 685 Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, 686 Metadata *Rank, Metadata *Annotations) { 687 assert(!Identifier.getString().empty() && "Expected valid identifier"); 688 if (!Context.isODRUniquingDebugTypes()) 689 return nullptr; 690 auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier]; 691 if (!CT) 692 return CT = DICompositeType::getDistinct( 693 Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, 694 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, 695 VTableHolder, TemplateParams, &Identifier, Discriminator, 696 DataLocation, Associated, Allocated, Rank, Annotations); 697 698 if (CT->getTag() != Tag) 699 return nullptr; 700 701 // Only mutate CT if it's a forward declaration and the new operands aren't. 702 assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?"); 703 if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl)) 704 return CT; 705 706 // Mutate CT in place. Keep this in sync with getImpl. 707 CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, 708 Flags); 709 Metadata *Ops[] = {File, Scope, Name, BaseType, 710 Elements, VTableHolder, TemplateParams, &Identifier, 711 Discriminator, DataLocation, Associated, Allocated, 712 Rank, Annotations}; 713 assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() && 714 "Mismatched number of operands"); 715 for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I) 716 if (Ops[I] != CT->getOperand(I)) 717 CT->setOperand(I, Ops[I]); 718 return CT; 719 } 720 721 DICompositeType *DICompositeType::getODRType( 722 LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, 723 Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, 724 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 725 DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, 726 Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, 727 Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, 728 Metadata *Rank, Metadata *Annotations) { 729 assert(!Identifier.getString().empty() && "Expected valid identifier"); 730 if (!Context.isODRUniquingDebugTypes()) 731 return nullptr; 732 auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier]; 733 if (!CT) { 734 CT = DICompositeType::getDistinct( 735 Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, 736 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, 737 TemplateParams, &Identifier, Discriminator, DataLocation, Associated, 738 Allocated, Rank, Annotations); 739 } else { 740 if (CT->getTag() != Tag) 741 return nullptr; 742 } 743 return CT; 744 } 745 746 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context, 747 MDString &Identifier) { 748 assert(!Identifier.getString().empty() && "Expected valid identifier"); 749 if (!Context.isODRUniquingDebugTypes()) 750 return nullptr; 751 return Context.pImpl->DITypeMap->lookup(&Identifier); 752 } 753 DISubroutineType::DISubroutineType(LLVMContext &C, StorageType Storage, 754 DIFlags Flags, uint8_t CC, 755 ArrayRef<Metadata *> Ops) 756 : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type, 0, 757 0, 0, 0, Flags, Ops), 758 CC(CC) {} 759 760 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags, 761 uint8_t CC, Metadata *TypeArray, 762 StorageType Storage, 763 bool ShouldCreate) { 764 DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray)); 765 Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray}; 766 DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops); 767 } 768 769 DIFile::DIFile(LLVMContext &C, StorageType Storage, 770 Optional<ChecksumInfo<MDString *>> CS, Optional<MDString *> Src, 771 ArrayRef<Metadata *> Ops) 772 : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops), 773 Checksum(CS), Source(Src) {} 774 775 // FIXME: Implement this string-enum correspondence with a .def file and macros, 776 // so that the association is explicit rather than implied. 777 static const char *ChecksumKindName[DIFile::CSK_Last] = { 778 "CSK_MD5", 779 "CSK_SHA1", 780 "CSK_SHA256", 781 }; 782 783 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) { 784 assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind"); 785 // The first space was originally the CSK_None variant, which is now 786 // obsolete, but the space is still reserved in ChecksumKind, so we account 787 // for it here. 788 return ChecksumKindName[CSKind - 1]; 789 } 790 791 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) { 792 return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr) 793 .Case("CSK_MD5", DIFile::CSK_MD5) 794 .Case("CSK_SHA1", DIFile::CSK_SHA1) 795 .Case("CSK_SHA256", DIFile::CSK_SHA256) 796 .Default(None); 797 } 798 799 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename, 800 MDString *Directory, 801 Optional<DIFile::ChecksumInfo<MDString *>> CS, 802 Optional<MDString *> Source, StorageType Storage, 803 bool ShouldCreate) { 804 assert(isCanonical(Filename) && "Expected canonical MDString"); 805 assert(isCanonical(Directory) && "Expected canonical MDString"); 806 assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString"); 807 assert((!Source || isCanonical(*Source)) && "Expected canonical MDString"); 808 DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source)); 809 Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr, 810 Source.value_or(nullptr)}; 811 DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops); 812 } 813 DICompileUnit::DICompileUnit(LLVMContext &C, StorageType Storage, 814 unsigned SourceLanguage, bool IsOptimized, 815 unsigned RuntimeVersion, unsigned EmissionKind, 816 uint64_t DWOId, bool SplitDebugInlining, 817 bool DebugInfoForProfiling, unsigned NameTableKind, 818 bool RangesBaseAddress, ArrayRef<Metadata *> Ops) 819 : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops), 820 SourceLanguage(SourceLanguage), IsOptimized(IsOptimized), 821 RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind), DWOId(DWOId), 822 SplitDebugInlining(SplitDebugInlining), 823 DebugInfoForProfiling(DebugInfoForProfiling), 824 NameTableKind(NameTableKind), RangesBaseAddress(RangesBaseAddress) { 825 assert(Storage != Uniqued); 826 } 827 828 DICompileUnit *DICompileUnit::getImpl( 829 LLVMContext &Context, unsigned SourceLanguage, Metadata *File, 830 MDString *Producer, bool IsOptimized, MDString *Flags, 831 unsigned RuntimeVersion, MDString *SplitDebugFilename, 832 unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes, 833 Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros, 834 uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling, 835 unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot, 836 MDString *SDK, StorageType Storage, bool ShouldCreate) { 837 assert(Storage != Uniqued && "Cannot unique DICompileUnit"); 838 assert(isCanonical(Producer) && "Expected canonical MDString"); 839 assert(isCanonical(Flags) && "Expected canonical MDString"); 840 assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString"); 841 842 Metadata *Ops[] = {File, 843 Producer, 844 Flags, 845 SplitDebugFilename, 846 EnumTypes, 847 RetainedTypes, 848 GlobalVariables, 849 ImportedEntities, 850 Macros, 851 SysRoot, 852 SDK}; 853 return storeImpl(new (array_lengthof(Ops), Storage) DICompileUnit( 854 Context, Storage, SourceLanguage, IsOptimized, 855 RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining, 856 DebugInfoForProfiling, NameTableKind, RangesBaseAddress, 857 Ops), 858 Storage); 859 } 860 861 Optional<DICompileUnit::DebugEmissionKind> 862 DICompileUnit::getEmissionKind(StringRef Str) { 863 return StringSwitch<Optional<DebugEmissionKind>>(Str) 864 .Case("NoDebug", NoDebug) 865 .Case("FullDebug", FullDebug) 866 .Case("LineTablesOnly", LineTablesOnly) 867 .Case("DebugDirectivesOnly", DebugDirectivesOnly) 868 .Default(None); 869 } 870 871 Optional<DICompileUnit::DebugNameTableKind> 872 DICompileUnit::getNameTableKind(StringRef Str) { 873 return StringSwitch<Optional<DebugNameTableKind>>(Str) 874 .Case("Default", DebugNameTableKind::Default) 875 .Case("GNU", DebugNameTableKind::GNU) 876 .Case("None", DebugNameTableKind::None) 877 .Default(None); 878 } 879 880 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) { 881 switch (EK) { 882 case NoDebug: 883 return "NoDebug"; 884 case FullDebug: 885 return "FullDebug"; 886 case LineTablesOnly: 887 return "LineTablesOnly"; 888 case DebugDirectivesOnly: 889 return "DebugDirectivesOnly"; 890 } 891 return nullptr; 892 } 893 894 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) { 895 switch (NTK) { 896 case DebugNameTableKind::Default: 897 return nullptr; 898 case DebugNameTableKind::GNU: 899 return "GNU"; 900 case DebugNameTableKind::None: 901 return "None"; 902 } 903 return nullptr; 904 } 905 DISubprogram::DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line, 906 unsigned ScopeLine, unsigned VirtualIndex, 907 int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, 908 ArrayRef<Metadata *> Ops) 909 : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram, Ops), 910 Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex), 911 ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags) { 912 static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range"); 913 } 914 DISubprogram::DISPFlags 915 DISubprogram::toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, 916 unsigned Virtuality, bool IsMainSubprogram) { 917 // We're assuming virtuality is the low-order field. 918 static_assert(int(SPFlagVirtual) == int(dwarf::DW_VIRTUALITY_virtual) && 919 int(SPFlagPureVirtual) == 920 int(dwarf::DW_VIRTUALITY_pure_virtual), 921 "Virtuality constant mismatch"); 922 return static_cast<DISPFlags>( 923 (Virtuality & SPFlagVirtuality) | 924 (IsLocalToUnit ? SPFlagLocalToUnit : SPFlagZero) | 925 (IsDefinition ? SPFlagDefinition : SPFlagZero) | 926 (IsOptimized ? SPFlagOptimized : SPFlagZero) | 927 (IsMainSubprogram ? SPFlagMainSubprogram : SPFlagZero)); 928 } 929 930 DISubprogram *DILocalScope::getSubprogram() const { 931 if (auto *Block = dyn_cast<DILexicalBlockBase>(this)) 932 return Block->getScope()->getSubprogram(); 933 return const_cast<DISubprogram *>(cast<DISubprogram>(this)); 934 } 935 936 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const { 937 if (auto *File = dyn_cast<DILexicalBlockFile>(this)) 938 return File->getScope()->getNonLexicalBlockFileScope(); 939 return const_cast<DILocalScope *>(this); 940 } 941 942 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) { 943 return StringSwitch<DISPFlags>(Flag) 944 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME) 945 #include "llvm/IR/DebugInfoFlags.def" 946 .Default(SPFlagZero); 947 } 948 949 StringRef DISubprogram::getFlagString(DISPFlags Flag) { 950 switch (Flag) { 951 // Appease a warning. 952 case SPFlagVirtuality: 953 return ""; 954 #define HANDLE_DISP_FLAG(ID, NAME) \ 955 case SPFlag##NAME: \ 956 return "DISPFlag" #NAME; 957 #include "llvm/IR/DebugInfoFlags.def" 958 } 959 return ""; 960 } 961 962 DISubprogram::DISPFlags 963 DISubprogram::splitFlags(DISPFlags Flags, 964 SmallVectorImpl<DISPFlags> &SplitFlags) { 965 // Multi-bit fields can require special handling. In our case, however, the 966 // only multi-bit field is virtuality, and all its values happen to be 967 // single-bit values, so the right behavior just falls out. 968 #define HANDLE_DISP_FLAG(ID, NAME) \ 969 if (DISPFlags Bit = Flags & SPFlag##NAME) { \ 970 SplitFlags.push_back(Bit); \ 971 Flags &= ~Bit; \ 972 } 973 #include "llvm/IR/DebugInfoFlags.def" 974 return Flags; 975 } 976 977 DISubprogram *DISubprogram::getImpl( 978 LLVMContext &Context, Metadata *Scope, MDString *Name, 979 MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type, 980 unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex, 981 int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit, 982 Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes, 983 Metadata *ThrownTypes, Metadata *Annotations, MDString *TargetFuncName, 984 StorageType Storage, bool ShouldCreate) { 985 assert(isCanonical(Name) && "Expected canonical MDString"); 986 assert(isCanonical(LinkageName) && "Expected canonical MDString"); 987 assert(isCanonical(TargetFuncName) && "Expected canonical MDString"); 988 DEFINE_GETIMPL_LOOKUP(DISubprogram, 989 (Scope, Name, LinkageName, File, Line, Type, ScopeLine, 990 ContainingType, VirtualIndex, ThisAdjustment, Flags, 991 SPFlags, Unit, TemplateParams, Declaration, 992 RetainedNodes, ThrownTypes, Annotations, 993 TargetFuncName)); 994 SmallVector<Metadata *, 13> Ops = { 995 File, Scope, Name, LinkageName, 996 Type, Unit, Declaration, RetainedNodes, 997 ContainingType, TemplateParams, ThrownTypes, Annotations, 998 TargetFuncName}; 999 if (!TargetFuncName) { 1000 Ops.pop_back(); 1001 if (!Annotations) { 1002 Ops.pop_back(); 1003 if (!ThrownTypes) { 1004 Ops.pop_back(); 1005 if (!TemplateParams) { 1006 Ops.pop_back(); 1007 if (!ContainingType) 1008 Ops.pop_back(); 1009 } 1010 } 1011 } 1012 } 1013 DEFINE_GETIMPL_STORE_N( 1014 DISubprogram, 1015 (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops, 1016 Ops.size()); 1017 } 1018 1019 bool DISubprogram::describes(const Function *F) const { 1020 assert(F && "Invalid function"); 1021 return F->getSubprogram() == this; 1022 } 1023 DILexicalBlockBase::DILexicalBlockBase(LLVMContext &C, unsigned ID, 1024 StorageType Storage, 1025 ArrayRef<Metadata *> Ops) 1026 : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {} 1027 1028 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope, 1029 Metadata *File, unsigned Line, 1030 unsigned Column, StorageType Storage, 1031 bool ShouldCreate) { 1032 // Fixup column. 1033 adjustColumn(Column); 1034 1035 assert(Scope && "Expected scope"); 1036 DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column)); 1037 Metadata *Ops[] = {File, Scope}; 1038 DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops); 1039 } 1040 1041 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context, 1042 Metadata *Scope, Metadata *File, 1043 unsigned Discriminator, 1044 StorageType Storage, 1045 bool ShouldCreate) { 1046 assert(Scope && "Expected scope"); 1047 DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator)); 1048 Metadata *Ops[] = {File, Scope}; 1049 DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops); 1050 } 1051 1052 DINamespace::DINamespace(LLVMContext &Context, StorageType Storage, 1053 bool ExportSymbols, ArrayRef<Metadata *> Ops) 1054 : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace, Ops), 1055 ExportSymbols(ExportSymbols) {} 1056 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope, 1057 MDString *Name, bool ExportSymbols, 1058 StorageType Storage, bool ShouldCreate) { 1059 assert(isCanonical(Name) && "Expected canonical MDString"); 1060 DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols)); 1061 // The nullptr is for DIScope's File operand. This should be refactored. 1062 Metadata *Ops[] = {nullptr, Scope, Name}; 1063 DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops); 1064 } 1065 1066 DICommonBlock::DICommonBlock(LLVMContext &Context, StorageType Storage, 1067 unsigned LineNo, ArrayRef<Metadata *> Ops) 1068 : DIScope(Context, DICommonBlockKind, Storage, dwarf::DW_TAG_common_block, 1069 Ops), 1070 LineNo(LineNo) {} 1071 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope, 1072 Metadata *Decl, MDString *Name, 1073 Metadata *File, unsigned LineNo, 1074 StorageType Storage, bool ShouldCreate) { 1075 assert(isCanonical(Name) && "Expected canonical MDString"); 1076 DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo)); 1077 // The nullptr is for DIScope's File operand. This should be refactored. 1078 Metadata *Ops[] = {Scope, Decl, Name, File}; 1079 DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops); 1080 } 1081 1082 DIModule::DIModule(LLVMContext &Context, StorageType Storage, unsigned LineNo, 1083 bool IsDecl, ArrayRef<Metadata *> Ops) 1084 : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops), 1085 LineNo(LineNo), IsDecl(IsDecl) {} 1086 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File, 1087 Metadata *Scope, MDString *Name, 1088 MDString *ConfigurationMacros, 1089 MDString *IncludePath, MDString *APINotesFile, 1090 unsigned LineNo, bool IsDecl, StorageType Storage, 1091 bool ShouldCreate) { 1092 assert(isCanonical(Name) && "Expected canonical MDString"); 1093 DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros, 1094 IncludePath, APINotesFile, LineNo, IsDecl)); 1095 Metadata *Ops[] = {File, Scope, Name, ConfigurationMacros, 1096 IncludePath, APINotesFile}; 1097 DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops); 1098 } 1099 DITemplateTypeParameter::DITemplateTypeParameter(LLVMContext &Context, 1100 StorageType Storage, 1101 bool IsDefault, 1102 ArrayRef<Metadata *> Ops) 1103 : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage, 1104 dwarf::DW_TAG_template_type_parameter, IsDefault, 1105 Ops) {} 1106 1107 DITemplateTypeParameter * 1108 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name, 1109 Metadata *Type, bool isDefault, 1110 StorageType Storage, bool ShouldCreate) { 1111 assert(isCanonical(Name) && "Expected canonical MDString"); 1112 DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault)); 1113 Metadata *Ops[] = {Name, Type}; 1114 DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops); 1115 } 1116 1117 DITemplateValueParameter *DITemplateValueParameter::getImpl( 1118 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type, 1119 bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) { 1120 assert(isCanonical(Name) && "Expected canonical MDString"); 1121 DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, 1122 (Tag, Name, Type, isDefault, Value)); 1123 Metadata *Ops[] = {Name, Type, Value}; 1124 DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops); 1125 } 1126 1127 DIGlobalVariable * 1128 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 1129 MDString *LinkageName, Metadata *File, unsigned Line, 1130 Metadata *Type, bool IsLocalToUnit, bool IsDefinition, 1131 Metadata *StaticDataMemberDeclaration, 1132 Metadata *TemplateParams, uint32_t AlignInBits, 1133 Metadata *Annotations, StorageType Storage, 1134 bool ShouldCreate) { 1135 assert(isCanonical(Name) && "Expected canonical MDString"); 1136 assert(isCanonical(LinkageName) && "Expected canonical MDString"); 1137 DEFINE_GETIMPL_LOOKUP( 1138 DIGlobalVariable, 1139 (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, 1140 StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations)); 1141 Metadata *Ops[] = {Scope, 1142 Name, 1143 File, 1144 Type, 1145 Name, 1146 LinkageName, 1147 StaticDataMemberDeclaration, 1148 TemplateParams, 1149 Annotations}; 1150 DEFINE_GETIMPL_STORE(DIGlobalVariable, 1151 (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops); 1152 } 1153 1154 DILocalVariable * 1155 DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 1156 Metadata *File, unsigned Line, Metadata *Type, 1157 unsigned Arg, DIFlags Flags, uint32_t AlignInBits, 1158 Metadata *Annotations, StorageType Storage, 1159 bool ShouldCreate) { 1160 // 64K ought to be enough for any frontend. 1161 assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits"); 1162 1163 assert(Scope && "Expected scope"); 1164 assert(isCanonical(Name) && "Expected canonical MDString"); 1165 DEFINE_GETIMPL_LOOKUP(DILocalVariable, (Scope, Name, File, Line, Type, Arg, 1166 Flags, AlignInBits, Annotations)); 1167 Metadata *Ops[] = {Scope, Name, File, Type, Annotations}; 1168 DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops); 1169 } 1170 1171 DIVariable::DIVariable(LLVMContext &C, unsigned ID, StorageType Storage, 1172 signed Line, ArrayRef<Metadata *> Ops, 1173 uint32_t AlignInBits) 1174 : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line), 1175 AlignInBits(AlignInBits) {} 1176 Optional<uint64_t> DIVariable::getSizeInBits() const { 1177 // This is used by the Verifier so be mindful of broken types. 1178 const Metadata *RawType = getRawType(); 1179 while (RawType) { 1180 // Try to get the size directly. 1181 if (auto *T = dyn_cast<DIType>(RawType)) 1182 if (uint64_t Size = T->getSizeInBits()) 1183 return Size; 1184 1185 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) { 1186 // Look at the base type. 1187 RawType = DT->getRawBaseType(); 1188 continue; 1189 } 1190 1191 // Missing type or size. 1192 break; 1193 } 1194 1195 // Fail gracefully. 1196 return None; 1197 } 1198 1199 DILabel::DILabel(LLVMContext &C, StorageType Storage, unsigned Line, 1200 ArrayRef<Metadata *> Ops) 1201 : DINode(C, DILabelKind, Storage, dwarf::DW_TAG_label, Ops), Line(Line) {} 1202 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 1203 Metadata *File, unsigned Line, StorageType Storage, 1204 bool ShouldCreate) { 1205 assert(Scope && "Expected scope"); 1206 assert(isCanonical(Name) && "Expected canonical MDString"); 1207 DEFINE_GETIMPL_LOOKUP(DILabel, (Scope, Name, File, Line)); 1208 Metadata *Ops[] = {Scope, Name, File}; 1209 DEFINE_GETIMPL_STORE(DILabel, (Line), Ops); 1210 } 1211 1212 DIExpression *DIExpression::getImpl(LLVMContext &Context, 1213 ArrayRef<uint64_t> Elements, 1214 StorageType Storage, bool ShouldCreate) { 1215 DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements)); 1216 DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements)); 1217 } 1218 bool DIExpression::isEntryValue() const { 1219 return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_LLVM_entry_value; 1220 } 1221 bool DIExpression::startsWithDeref() const { 1222 return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_deref; 1223 } 1224 1225 unsigned DIExpression::ExprOperand::getSize() const { 1226 uint64_t Op = getOp(); 1227 1228 if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31) 1229 return 2; 1230 1231 switch (Op) { 1232 case dwarf::DW_OP_LLVM_convert: 1233 case dwarf::DW_OP_LLVM_fragment: 1234 case dwarf::DW_OP_bregx: 1235 return 3; 1236 case dwarf::DW_OP_constu: 1237 case dwarf::DW_OP_consts: 1238 case dwarf::DW_OP_deref_size: 1239 case dwarf::DW_OP_plus_uconst: 1240 case dwarf::DW_OP_LLVM_tag_offset: 1241 case dwarf::DW_OP_LLVM_entry_value: 1242 case dwarf::DW_OP_LLVM_arg: 1243 case dwarf::DW_OP_regx: 1244 return 2; 1245 default: 1246 return 1; 1247 } 1248 } 1249 1250 bool DIExpression::isValid() const { 1251 for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) { 1252 // Check that there's space for the operand. 1253 if (I->get() + I->getSize() > E->get()) 1254 return false; 1255 1256 uint64_t Op = I->getOp(); 1257 if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) || 1258 (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)) 1259 return true; 1260 1261 // Check that the operand is valid. 1262 switch (Op) { 1263 default: 1264 return false; 1265 case dwarf::DW_OP_LLVM_fragment: 1266 // A fragment operator must appear at the end. 1267 return I->get() + I->getSize() == E->get(); 1268 case dwarf::DW_OP_stack_value: { 1269 // Must be the last one or followed by a DW_OP_LLVM_fragment. 1270 if (I->get() + I->getSize() == E->get()) 1271 break; 1272 auto J = I; 1273 if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment) 1274 return false; 1275 break; 1276 } 1277 case dwarf::DW_OP_swap: { 1278 // Must be more than one implicit element on the stack. 1279 1280 // FIXME: A better way to implement this would be to add a local variable 1281 // that keeps track of the stack depth and introduce something like a 1282 // DW_LLVM_OP_implicit_location as a placeholder for the location this 1283 // DIExpression is attached to, or else pass the number of implicit stack 1284 // elements into isValid. 1285 if (getNumElements() == 1) 1286 return false; 1287 break; 1288 } 1289 case dwarf::DW_OP_LLVM_entry_value: { 1290 // An entry value operator must appear at the beginning and the number of 1291 // operations it cover can currently only be 1, because we support only 1292 // entry values of a simple register location. One reason for this is that 1293 // we currently can't calculate the size of the resulting DWARF block for 1294 // other expressions. 1295 return I->get() == expr_op_begin()->get() && I->getArg(0) == 1; 1296 } 1297 case dwarf::DW_OP_LLVM_implicit_pointer: 1298 case dwarf::DW_OP_LLVM_convert: 1299 case dwarf::DW_OP_LLVM_arg: 1300 case dwarf::DW_OP_LLVM_tag_offset: 1301 case dwarf::DW_OP_constu: 1302 case dwarf::DW_OP_plus_uconst: 1303 case dwarf::DW_OP_plus: 1304 case dwarf::DW_OP_minus: 1305 case dwarf::DW_OP_mul: 1306 case dwarf::DW_OP_div: 1307 case dwarf::DW_OP_mod: 1308 case dwarf::DW_OP_or: 1309 case dwarf::DW_OP_and: 1310 case dwarf::DW_OP_xor: 1311 case dwarf::DW_OP_shl: 1312 case dwarf::DW_OP_shr: 1313 case dwarf::DW_OP_shra: 1314 case dwarf::DW_OP_deref: 1315 case dwarf::DW_OP_deref_size: 1316 case dwarf::DW_OP_xderef: 1317 case dwarf::DW_OP_lit0: 1318 case dwarf::DW_OP_not: 1319 case dwarf::DW_OP_dup: 1320 case dwarf::DW_OP_regx: 1321 case dwarf::DW_OP_bregx: 1322 case dwarf::DW_OP_push_object_address: 1323 case dwarf::DW_OP_over: 1324 case dwarf::DW_OP_consts: 1325 break; 1326 } 1327 } 1328 return true; 1329 } 1330 1331 bool DIExpression::isImplicit() const { 1332 if (!isValid()) 1333 return false; 1334 1335 if (getNumElements() == 0) 1336 return false; 1337 1338 for (const auto &It : expr_ops()) { 1339 switch (It.getOp()) { 1340 default: 1341 break; 1342 case dwarf::DW_OP_stack_value: 1343 case dwarf::DW_OP_LLVM_tag_offset: 1344 return true; 1345 } 1346 } 1347 1348 return false; 1349 } 1350 1351 bool DIExpression::isComplex() const { 1352 if (!isValid()) 1353 return false; 1354 1355 if (getNumElements() == 0) 1356 return false; 1357 1358 // If there are any elements other than fragment or tag_offset, then some 1359 // kind of complex computation occurs. 1360 for (const auto &It : expr_ops()) { 1361 switch (It.getOp()) { 1362 case dwarf::DW_OP_LLVM_tag_offset: 1363 case dwarf::DW_OP_LLVM_fragment: 1364 continue; 1365 default: 1366 return true; 1367 } 1368 } 1369 1370 return false; 1371 } 1372 1373 Optional<DIExpression::FragmentInfo> 1374 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) { 1375 for (auto I = Start; I != End; ++I) 1376 if (I->getOp() == dwarf::DW_OP_LLVM_fragment) { 1377 DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)}; 1378 return Info; 1379 } 1380 return None; 1381 } 1382 1383 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops, 1384 int64_t Offset) { 1385 if (Offset > 0) { 1386 Ops.push_back(dwarf::DW_OP_plus_uconst); 1387 Ops.push_back(Offset); 1388 } else if (Offset < 0) { 1389 Ops.push_back(dwarf::DW_OP_constu); 1390 Ops.push_back(-Offset); 1391 Ops.push_back(dwarf::DW_OP_minus); 1392 } 1393 } 1394 1395 bool DIExpression::extractIfOffset(int64_t &Offset) const { 1396 if (getNumElements() == 0) { 1397 Offset = 0; 1398 return true; 1399 } 1400 1401 if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) { 1402 Offset = Elements[1]; 1403 return true; 1404 } 1405 1406 if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) { 1407 if (Elements[2] == dwarf::DW_OP_plus) { 1408 Offset = Elements[1]; 1409 return true; 1410 } 1411 if (Elements[2] == dwarf::DW_OP_minus) { 1412 Offset = -Elements[1]; 1413 return true; 1414 } 1415 } 1416 1417 return false; 1418 } 1419 1420 bool DIExpression::hasAllLocationOps(unsigned N) const { 1421 SmallDenseSet<uint64_t, 4> SeenOps; 1422 for (auto ExprOp : expr_ops()) 1423 if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg) 1424 SeenOps.insert(ExprOp.getArg(0)); 1425 for (uint64_t Idx = 0; Idx < N; ++Idx) 1426 if (!is_contained(SeenOps, Idx)) 1427 return false; 1428 return true; 1429 } 1430 1431 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr, 1432 unsigned &AddrClass) { 1433 // FIXME: This seems fragile. Nothing that verifies that these elements 1434 // actually map to ops and not operands. 1435 const unsigned PatternSize = 4; 1436 if (Expr->Elements.size() >= PatternSize && 1437 Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu && 1438 Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap && 1439 Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) { 1440 AddrClass = Expr->Elements[PatternSize - 3]; 1441 1442 if (Expr->Elements.size() == PatternSize) 1443 return nullptr; 1444 return DIExpression::get(Expr->getContext(), 1445 makeArrayRef(&*Expr->Elements.begin(), 1446 Expr->Elements.size() - PatternSize)); 1447 } 1448 return Expr; 1449 } 1450 1451 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags, 1452 int64_t Offset) { 1453 SmallVector<uint64_t, 8> Ops; 1454 if (Flags & DIExpression::DerefBefore) 1455 Ops.push_back(dwarf::DW_OP_deref); 1456 1457 appendOffset(Ops, Offset); 1458 if (Flags & DIExpression::DerefAfter) 1459 Ops.push_back(dwarf::DW_OP_deref); 1460 1461 bool StackValue = Flags & DIExpression::StackValue; 1462 bool EntryValue = Flags & DIExpression::EntryValue; 1463 1464 return prependOpcodes(Expr, Ops, StackValue, EntryValue); 1465 } 1466 1467 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr, 1468 ArrayRef<uint64_t> Ops, 1469 unsigned ArgNo, bool StackValue) { 1470 assert(Expr && "Can't add ops to this expression"); 1471 1472 // Handle non-variadic intrinsics by prepending the opcodes. 1473 if (!any_of(Expr->expr_ops(), 1474 [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) { 1475 assert(ArgNo == 0 && 1476 "Location Index must be 0 for a non-variadic expression."); 1477 SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end()); 1478 return DIExpression::prependOpcodes(Expr, NewOps, StackValue); 1479 } 1480 1481 SmallVector<uint64_t, 8> NewOps; 1482 for (auto Op : Expr->expr_ops()) { 1483 Op.appendToVector(NewOps); 1484 if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo) 1485 NewOps.insert(NewOps.end(), Ops.begin(), Ops.end()); 1486 } 1487 1488 return DIExpression::get(Expr->getContext(), NewOps); 1489 } 1490 1491 DIExpression *DIExpression::replaceArg(const DIExpression *Expr, 1492 uint64_t OldArg, uint64_t NewArg) { 1493 assert(Expr && "Can't replace args in this expression"); 1494 1495 SmallVector<uint64_t, 8> NewOps; 1496 1497 for (auto Op : Expr->expr_ops()) { 1498 if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) { 1499 Op.appendToVector(NewOps); 1500 continue; 1501 } 1502 NewOps.push_back(dwarf::DW_OP_LLVM_arg); 1503 uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0); 1504 // OldArg has been deleted from the Op list, so decrement all indices 1505 // greater than it. 1506 if (Arg > OldArg) 1507 --Arg; 1508 NewOps.push_back(Arg); 1509 } 1510 return DIExpression::get(Expr->getContext(), NewOps); 1511 } 1512 1513 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr, 1514 SmallVectorImpl<uint64_t> &Ops, 1515 bool StackValue, bool EntryValue) { 1516 assert(Expr && "Can't prepend ops to this expression"); 1517 1518 if (EntryValue) { 1519 Ops.push_back(dwarf::DW_OP_LLVM_entry_value); 1520 // Use a block size of 1 for the target register operand. The 1521 // DWARF backend currently cannot emit entry values with a block 1522 // size > 1. 1523 Ops.push_back(1); 1524 } 1525 1526 // If there are no ops to prepend, do not even add the DW_OP_stack_value. 1527 if (Ops.empty()) 1528 StackValue = false; 1529 for (auto Op : Expr->expr_ops()) { 1530 // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment. 1531 if (StackValue) { 1532 if (Op.getOp() == dwarf::DW_OP_stack_value) 1533 StackValue = false; 1534 else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1535 Ops.push_back(dwarf::DW_OP_stack_value); 1536 StackValue = false; 1537 } 1538 } 1539 Op.appendToVector(Ops); 1540 } 1541 if (StackValue) 1542 Ops.push_back(dwarf::DW_OP_stack_value); 1543 return DIExpression::get(Expr->getContext(), Ops); 1544 } 1545 1546 DIExpression *DIExpression::append(const DIExpression *Expr, 1547 ArrayRef<uint64_t> Ops) { 1548 assert(Expr && !Ops.empty() && "Can't append ops to this expression"); 1549 1550 // Copy Expr's current op list. 1551 SmallVector<uint64_t, 16> NewOps; 1552 for (auto Op : Expr->expr_ops()) { 1553 // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}. 1554 if (Op.getOp() == dwarf::DW_OP_stack_value || 1555 Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1556 NewOps.append(Ops.begin(), Ops.end()); 1557 1558 // Ensure that the new opcodes are only appended once. 1559 Ops = None; 1560 } 1561 Op.appendToVector(NewOps); 1562 } 1563 1564 NewOps.append(Ops.begin(), Ops.end()); 1565 auto *result = DIExpression::get(Expr->getContext(), NewOps); 1566 assert(result->isValid() && "concatenated expression is not valid"); 1567 return result; 1568 } 1569 1570 DIExpression *DIExpression::appendToStack(const DIExpression *Expr, 1571 ArrayRef<uint64_t> Ops) { 1572 assert(Expr && !Ops.empty() && "Can't append ops to this expression"); 1573 assert(none_of(Ops, 1574 [](uint64_t Op) { 1575 return Op == dwarf::DW_OP_stack_value || 1576 Op == dwarf::DW_OP_LLVM_fragment; 1577 }) && 1578 "Can't append this op"); 1579 1580 // Append a DW_OP_deref after Expr's current op list if it's non-empty and 1581 // has no DW_OP_stack_value. 1582 // 1583 // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?. 1584 Optional<FragmentInfo> FI = Expr->getFragmentInfo(); 1585 unsigned DropUntilStackValue = FI ? 3 : 0; 1586 ArrayRef<uint64_t> ExprOpsBeforeFragment = 1587 Expr->getElements().drop_back(DropUntilStackValue); 1588 bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) && 1589 (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value); 1590 bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty(); 1591 1592 // Append a DW_OP_deref after Expr's current op list if needed, then append 1593 // the new ops, and finally ensure that a single DW_OP_stack_value is present. 1594 SmallVector<uint64_t, 16> NewOps; 1595 if (NeedsDeref) 1596 NewOps.push_back(dwarf::DW_OP_deref); 1597 NewOps.append(Ops.begin(), Ops.end()); 1598 if (NeedsStackValue) 1599 NewOps.push_back(dwarf::DW_OP_stack_value); 1600 return DIExpression::append(Expr, NewOps); 1601 } 1602 1603 Optional<DIExpression *> DIExpression::createFragmentExpression( 1604 const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) { 1605 SmallVector<uint64_t, 8> Ops; 1606 // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment. 1607 if (Expr) { 1608 for (auto Op : Expr->expr_ops()) { 1609 switch (Op.getOp()) { 1610 default: 1611 break; 1612 case dwarf::DW_OP_shr: 1613 case dwarf::DW_OP_shra: 1614 case dwarf::DW_OP_shl: 1615 case dwarf::DW_OP_plus: 1616 case dwarf::DW_OP_plus_uconst: 1617 case dwarf::DW_OP_minus: 1618 // We can't safely split arithmetic or shift operations into multiple 1619 // fragments because we can't express carry-over between fragments. 1620 // 1621 // FIXME: We *could* preserve the lowest fragment of a constant offset 1622 // operation if the offset fits into SizeInBits. 1623 return None; 1624 case dwarf::DW_OP_LLVM_fragment: { 1625 // Make the new offset point into the existing fragment. 1626 uint64_t FragmentOffsetInBits = Op.getArg(0); 1627 uint64_t FragmentSizeInBits = Op.getArg(1); 1628 (void)FragmentSizeInBits; 1629 assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) && 1630 "new fragment outside of original fragment"); 1631 OffsetInBits += FragmentOffsetInBits; 1632 continue; 1633 } 1634 } 1635 Op.appendToVector(Ops); 1636 } 1637 } 1638 assert(Expr && "Unknown DIExpression"); 1639 Ops.push_back(dwarf::DW_OP_LLVM_fragment); 1640 Ops.push_back(OffsetInBits); 1641 Ops.push_back(SizeInBits); 1642 return DIExpression::get(Expr->getContext(), Ops); 1643 } 1644 1645 std::pair<DIExpression *, const ConstantInt *> 1646 DIExpression::constantFold(const ConstantInt *CI) { 1647 // Copy the APInt so we can modify it. 1648 APInt NewInt = CI->getValue(); 1649 SmallVector<uint64_t, 8> Ops; 1650 1651 // Fold operators only at the beginning of the expression. 1652 bool First = true; 1653 bool Changed = false; 1654 for (auto Op : expr_ops()) { 1655 switch (Op.getOp()) { 1656 default: 1657 // We fold only the leading part of the expression; if we get to a part 1658 // that we're going to copy unchanged, and haven't done any folding, 1659 // then the entire expression is unchanged and we can return early. 1660 if (!Changed) 1661 return {this, CI}; 1662 First = false; 1663 break; 1664 case dwarf::DW_OP_LLVM_convert: 1665 if (!First) 1666 break; 1667 Changed = true; 1668 if (Op.getArg(1) == dwarf::DW_ATE_signed) 1669 NewInt = NewInt.sextOrTrunc(Op.getArg(0)); 1670 else { 1671 assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand"); 1672 NewInt = NewInt.zextOrTrunc(Op.getArg(0)); 1673 } 1674 continue; 1675 } 1676 Op.appendToVector(Ops); 1677 } 1678 if (!Changed) 1679 return {this, CI}; 1680 return {DIExpression::get(getContext(), Ops), 1681 ConstantInt::get(getContext(), NewInt)}; 1682 } 1683 1684 uint64_t DIExpression::getNumLocationOperands() const { 1685 uint64_t Result = 0; 1686 for (auto ExprOp : expr_ops()) 1687 if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg) 1688 Result = std::max(Result, ExprOp.getArg(0) + 1); 1689 assert(hasAllLocationOps(Result) && 1690 "Expression is missing one or more location operands."); 1691 return Result; 1692 } 1693 1694 llvm::Optional<DIExpression::SignedOrUnsignedConstant> 1695 DIExpression::isConstant() const { 1696 1697 // Recognize signed and unsigned constants. 1698 // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value 1699 // (DW_OP_LLVM_fragment of Len). 1700 // An unsigned constant can be represented as 1701 // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len). 1702 1703 if ((getNumElements() != 2 && getNumElements() != 3 && 1704 getNumElements() != 6) || 1705 (getElement(0) != dwarf::DW_OP_consts && 1706 getElement(0) != dwarf::DW_OP_constu)) 1707 return None; 1708 1709 if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts) 1710 return SignedOrUnsignedConstant::SignedConstant; 1711 1712 if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) || 1713 (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value || 1714 getElement(3) != dwarf::DW_OP_LLVM_fragment))) 1715 return None; 1716 return getElement(0) == dwarf::DW_OP_constu 1717 ? SignedOrUnsignedConstant::UnsignedConstant 1718 : SignedOrUnsignedConstant::SignedConstant; 1719 } 1720 1721 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize, 1722 bool Signed) { 1723 dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned; 1724 DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK, 1725 dwarf::DW_OP_LLVM_convert, ToSize, TK}}; 1726 return Ops; 1727 } 1728 1729 DIExpression *DIExpression::appendExt(const DIExpression *Expr, 1730 unsigned FromSize, unsigned ToSize, 1731 bool Signed) { 1732 return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed)); 1733 } 1734 1735 DIGlobalVariableExpression * 1736 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable, 1737 Metadata *Expression, StorageType Storage, 1738 bool ShouldCreate) { 1739 DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression)); 1740 Metadata *Ops[] = {Variable, Expression}; 1741 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops); 1742 } 1743 DIObjCProperty::DIObjCProperty(LLVMContext &C, StorageType Storage, 1744 unsigned Line, unsigned Attributes, 1745 ArrayRef<Metadata *> Ops) 1746 : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property, Ops), 1747 Line(Line), Attributes(Attributes) {} 1748 1749 DIObjCProperty *DIObjCProperty::getImpl( 1750 LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line, 1751 MDString *GetterName, MDString *SetterName, unsigned Attributes, 1752 Metadata *Type, StorageType Storage, bool ShouldCreate) { 1753 assert(isCanonical(Name) && "Expected canonical MDString"); 1754 assert(isCanonical(GetterName) && "Expected canonical MDString"); 1755 assert(isCanonical(SetterName) && "Expected canonical MDString"); 1756 DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName, 1757 SetterName, Attributes, Type)); 1758 Metadata *Ops[] = {Name, File, GetterName, SetterName, Type}; 1759 DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops); 1760 } 1761 1762 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag, 1763 Metadata *Scope, Metadata *Entity, 1764 Metadata *File, unsigned Line, 1765 MDString *Name, Metadata *Elements, 1766 StorageType Storage, 1767 bool ShouldCreate) { 1768 assert(isCanonical(Name) && "Expected canonical MDString"); 1769 DEFINE_GETIMPL_LOOKUP(DIImportedEntity, 1770 (Tag, Scope, Entity, File, Line, Name, Elements)); 1771 Metadata *Ops[] = {Scope, Entity, Name, File, Elements}; 1772 DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops); 1773 } 1774 1775 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType, unsigned Line, 1776 MDString *Name, MDString *Value, StorageType Storage, 1777 bool ShouldCreate) { 1778 assert(isCanonical(Name) && "Expected canonical MDString"); 1779 DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value)); 1780 Metadata *Ops[] = {Name, Value}; 1781 DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops); 1782 } 1783 1784 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType, 1785 unsigned Line, Metadata *File, 1786 Metadata *Elements, StorageType Storage, 1787 bool ShouldCreate) { 1788 DEFINE_GETIMPL_LOOKUP(DIMacroFile, (MIType, Line, File, Elements)); 1789 Metadata *Ops[] = {File, Elements}; 1790 DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops); 1791 } 1792 1793 DIArgList *DIArgList::getImpl(LLVMContext &Context, 1794 ArrayRef<ValueAsMetadata *> Args, 1795 StorageType Storage, bool ShouldCreate) { 1796 DEFINE_GETIMPL_LOOKUP(DIArgList, (Args)); 1797 DEFINE_GETIMPL_STORE_NO_OPS(DIArgList, (Args)); 1798 } 1799 1800 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) { 1801 ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref); 1802 assert((!New || isa<ValueAsMetadata>(New)) && 1803 "DIArgList must be passed a ValueAsMetadata"); 1804 untrack(); 1805 bool Uniq = isUniqued(); 1806 if (Uniq) { 1807 // We need to update the uniqueness once the Args are updated since they 1808 // form the key to the DIArgLists store. 1809 eraseFromStore(); 1810 } 1811 ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New); 1812 for (ValueAsMetadata *&VM : Args) { 1813 if (&VM == OldVMPtr) { 1814 if (NewVM) 1815 VM = NewVM; 1816 else 1817 VM = ValueAsMetadata::get(UndefValue::get(VM->getValue()->getType())); 1818 } 1819 } 1820 if (Uniq) { 1821 if (uniquify() != this) 1822 storeDistinctInContext(); 1823 } 1824 track(); 1825 } 1826 void DIArgList::track() { 1827 for (ValueAsMetadata *&VAM : Args) 1828 if (VAM) 1829 MetadataTracking::track(&VAM, *VAM, *this); 1830 } 1831 void DIArgList::untrack() { 1832 for (ValueAsMetadata *&VAM : Args) 1833 if (VAM) 1834 MetadataTracking::untrack(&VAM, *VAM); 1835 } 1836 void DIArgList::dropAllReferences() { 1837 untrack(); 1838 Args.clear(); 1839 MDNode::dropAllReferences(); 1840 } 1841