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/IR/DIBuilder.h" 19 #include "llvm/IR/Function.h" 20 #include "llvm/IR/Instructions.h" 21 22 #include <numeric> 23 24 using namespace llvm; 25 26 const DIExpression::FragmentInfo DebugVariable::DefaultFragment = { 27 std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()}; 28 29 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line, 30 unsigned Column, ArrayRef<Metadata *> MDs, 31 bool ImplicitCode) 32 : MDNode(C, DILocationKind, Storage, MDs) { 33 assert((MDs.size() == 1 || MDs.size() == 2) && 34 "Expected a scope and optional inlined-at"); 35 36 // Set line and column. 37 assert(Column < (1u << 16) && "Expected 16-bit column"); 38 39 SubclassData32 = Line; 40 SubclassData16 = Column; 41 42 setImplicitCode(ImplicitCode); 43 } 44 45 static void adjustColumn(unsigned &Column) { 46 // Set to unknown on overflow. We only have 16 bits to play with here. 47 if (Column >= (1u << 16)) 48 Column = 0; 49 } 50 51 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line, 52 unsigned Column, Metadata *Scope, 53 Metadata *InlinedAt, bool ImplicitCode, 54 StorageType Storage, bool ShouldCreate) { 55 // Fixup column. 56 adjustColumn(Column); 57 58 if (Storage == Uniqued) { 59 if (auto *N = getUniqued(Context.pImpl->DILocations, 60 DILocationInfo::KeyTy(Line, Column, Scope, 61 InlinedAt, ImplicitCode))) 62 return N; 63 if (!ShouldCreate) 64 return nullptr; 65 } else { 66 assert(ShouldCreate && "Expected non-uniqued nodes to always be created"); 67 } 68 69 SmallVector<Metadata *, 2> Ops; 70 Ops.push_back(Scope); 71 if (InlinedAt) 72 Ops.push_back(InlinedAt); 73 return storeImpl(new (Ops.size()) DILocation(Context, Storage, Line, Column, 74 Ops, ImplicitCode), 75 Storage, Context.pImpl->DILocations); 76 } 77 78 const 79 DILocation *DILocation::getMergedLocations(ArrayRef<const DILocation *> Locs) { 80 if (Locs.empty()) 81 return nullptr; 82 if (Locs.size() == 1) 83 return Locs[0]; 84 auto *Merged = Locs[0]; 85 for (auto I = std::next(Locs.begin()), E = Locs.end(); I != E; ++I) { 86 Merged = getMergedLocation(Merged, *I); 87 if (Merged == nullptr) 88 break; 89 } 90 return Merged; 91 } 92 93 const DILocation *DILocation::getMergedLocation(const DILocation *LocA, 94 const DILocation *LocB) { 95 if (!LocA || !LocB) 96 return nullptr; 97 98 if (LocA == LocB) 99 return LocA; 100 101 SmallPtrSet<DILocation *, 5> InlinedLocationsA; 102 for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt()) 103 InlinedLocationsA.insert(L); 104 SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations; 105 DIScope *S = LocA->getScope(); 106 DILocation *L = LocA->getInlinedAt(); 107 while (S) { 108 Locations.insert(std::make_pair(S, L)); 109 S = S->getScope(); 110 if (!S && L) { 111 S = L->getScope(); 112 L = L->getInlinedAt(); 113 } 114 } 115 const DILocation *Result = LocB; 116 S = LocB->getScope(); 117 L = LocB->getInlinedAt(); 118 while (S) { 119 if (Locations.count(std::make_pair(S, L))) 120 break; 121 S = S->getScope(); 122 if (!S && L) { 123 S = L->getScope(); 124 L = L->getInlinedAt(); 125 } 126 } 127 128 // If the two locations are irreconsilable, just pick one. This is misleading, 129 // but on the other hand, it's a "line 0" location. 130 if (!S || !isa<DILocalScope>(S)) 131 S = LocA->getScope(); 132 return DILocation::get(Result->getContext(), 0, 0, S, L); 133 } 134 135 Optional<unsigned> DILocation::encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI) { 136 std::array<unsigned, 3> Components = {BD, DF, CI}; 137 uint64_t RemainingWork = 0U; 138 // We use RemainingWork to figure out if we have no remaining components to 139 // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to 140 // encode anything for the latter 2. 141 // Since any of the input components is at most 32 bits, their sum will be 142 // less than 34 bits, and thus RemainingWork won't overflow. 143 RemainingWork = std::accumulate(Components.begin(), Components.end(), RemainingWork); 144 145 int I = 0; 146 unsigned Ret = 0; 147 unsigned NextBitInsertionIndex = 0; 148 while (RemainingWork > 0) { 149 unsigned C = Components[I++]; 150 RemainingWork -= C; 151 unsigned EC = encodeComponent(C); 152 Ret |= (EC << NextBitInsertionIndex); 153 NextBitInsertionIndex += encodingBits(C); 154 } 155 156 // Encoding may be unsuccessful because of overflow. We determine success by 157 // checking equivalence of components before & after encoding. Alternatively, 158 // we could determine Success during encoding, but the current alternative is 159 // simpler. 160 unsigned TBD, TDF, TCI = 0; 161 decodeDiscriminator(Ret, TBD, TDF, TCI); 162 if (TBD == BD && TDF == DF && TCI == CI) 163 return Ret; 164 return None; 165 } 166 167 void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF, 168 unsigned &CI) { 169 BD = getUnsignedFromPrefixEncoding(D); 170 DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D)); 171 CI = getUnsignedFromPrefixEncoding( 172 getNextComponentInDiscriminator(getNextComponentInDiscriminator(D))); 173 } 174 175 176 DINode::DIFlags DINode::getFlag(StringRef Flag) { 177 return StringSwitch<DIFlags>(Flag) 178 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME) 179 #include "llvm/IR/DebugInfoFlags.def" 180 .Default(DINode::FlagZero); 181 } 182 183 StringRef DINode::getFlagString(DIFlags Flag) { 184 switch (Flag) { 185 #define HANDLE_DI_FLAG(ID, NAME) \ 186 case Flag##NAME: \ 187 return "DIFlag" #NAME; 188 #include "llvm/IR/DebugInfoFlags.def" 189 } 190 return ""; 191 } 192 193 DINode::DIFlags DINode::splitFlags(DIFlags Flags, 194 SmallVectorImpl<DIFlags> &SplitFlags) { 195 // Flags that are packed together need to be specially handled, so 196 // that, for example, we emit "DIFlagPublic" and not 197 // "DIFlagPrivate | DIFlagProtected". 198 if (DIFlags A = Flags & FlagAccessibility) { 199 if (A == FlagPrivate) 200 SplitFlags.push_back(FlagPrivate); 201 else if (A == FlagProtected) 202 SplitFlags.push_back(FlagProtected); 203 else 204 SplitFlags.push_back(FlagPublic); 205 Flags &= ~A; 206 } 207 if (DIFlags R = Flags & FlagPtrToMemberRep) { 208 if (R == FlagSingleInheritance) 209 SplitFlags.push_back(FlagSingleInheritance); 210 else if (R == FlagMultipleInheritance) 211 SplitFlags.push_back(FlagMultipleInheritance); 212 else 213 SplitFlags.push_back(FlagVirtualInheritance); 214 Flags &= ~R; 215 } 216 if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) { 217 Flags &= ~FlagIndirectVirtualBase; 218 SplitFlags.push_back(FlagIndirectVirtualBase); 219 } 220 221 #define HANDLE_DI_FLAG(ID, NAME) \ 222 if (DIFlags Bit = Flags & Flag##NAME) { \ 223 SplitFlags.push_back(Bit); \ 224 Flags &= ~Bit; \ 225 } 226 #include "llvm/IR/DebugInfoFlags.def" 227 return Flags; 228 } 229 230 DIScope *DIScope::getScope() const { 231 if (auto *T = dyn_cast<DIType>(this)) 232 return T->getScope(); 233 234 if (auto *SP = dyn_cast<DISubprogram>(this)) 235 return SP->getScope(); 236 237 if (auto *LB = dyn_cast<DILexicalBlockBase>(this)) 238 return LB->getScope(); 239 240 if (auto *NS = dyn_cast<DINamespace>(this)) 241 return NS->getScope(); 242 243 if (auto *CB = dyn_cast<DICommonBlock>(this)) 244 return CB->getScope(); 245 246 if (auto *M = dyn_cast<DIModule>(this)) 247 return M->getScope(); 248 249 assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) && 250 "Unhandled type of scope."); 251 return nullptr; 252 } 253 254 StringRef DIScope::getName() const { 255 if (auto *T = dyn_cast<DIType>(this)) 256 return T->getName(); 257 if (auto *SP = dyn_cast<DISubprogram>(this)) 258 return SP->getName(); 259 if (auto *NS = dyn_cast<DINamespace>(this)) 260 return NS->getName(); 261 if (auto *CB = dyn_cast<DICommonBlock>(this)) 262 return CB->getName(); 263 if (auto *M = dyn_cast<DIModule>(this)) 264 return M->getName(); 265 assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) || 266 isa<DICompileUnit>(this)) && 267 "Unhandled type of scope."); 268 return ""; 269 } 270 271 #ifndef NDEBUG 272 static bool isCanonical(const MDString *S) { 273 return !S || !S->getString().empty(); 274 } 275 #endif 276 277 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag, 278 MDString *Header, 279 ArrayRef<Metadata *> DwarfOps, 280 StorageType Storage, bool ShouldCreate) { 281 unsigned Hash = 0; 282 if (Storage == Uniqued) { 283 GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps); 284 if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key)) 285 return N; 286 if (!ShouldCreate) 287 return nullptr; 288 Hash = Key.getHash(); 289 } else { 290 assert(ShouldCreate && "Expected non-uniqued nodes to always be created"); 291 } 292 293 // Use a nullptr for empty headers. 294 assert(isCanonical(Header) && "Expected canonical MDString"); 295 Metadata *PreOps[] = {Header}; 296 return storeImpl(new (DwarfOps.size() + 1) GenericDINode( 297 Context, Storage, Hash, Tag, PreOps, DwarfOps), 298 Storage, Context.pImpl->GenericDINodes); 299 } 300 301 void GenericDINode::recalculateHash() { 302 setHash(GenericDINodeInfo::KeyTy::calculateHash(this)); 303 } 304 305 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__ 306 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS 307 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS) \ 308 do { \ 309 if (Storage == Uniqued) { \ 310 if (auto *N = getUniqued(Context.pImpl->CLASS##s, \ 311 CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS)))) \ 312 return N; \ 313 if (!ShouldCreate) \ 314 return nullptr; \ 315 } else { \ 316 assert(ShouldCreate && \ 317 "Expected non-uniqued nodes to always be created"); \ 318 } \ 319 } while (false) 320 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS) \ 321 return storeImpl(new (array_lengthof(OPS)) \ 322 CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \ 323 Storage, Context.pImpl->CLASS##s) 324 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS) \ 325 return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)), \ 326 Storage, Context.pImpl->CLASS##s) 327 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS) \ 328 return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS), \ 329 Storage, Context.pImpl->CLASS##s) 330 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS) \ 331 return storeImpl(new (NUM_OPS) \ 332 CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \ 333 Storage, Context.pImpl->CLASS##s) 334 335 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo, 336 StorageType Storage, bool ShouldCreate) { 337 auto *CountNode = ConstantAsMetadata::get( 338 ConstantInt::getSigned(Type::getInt64Ty(Context), Count)); 339 auto *LB = ConstantAsMetadata::get( 340 ConstantInt::getSigned(Type::getInt64Ty(Context), Lo)); 341 return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage, 342 ShouldCreate); 343 } 344 345 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode, 346 int64_t Lo, StorageType Storage, 347 bool ShouldCreate) { 348 auto *LB = ConstantAsMetadata::get( 349 ConstantInt::getSigned(Type::getInt64Ty(Context), Lo)); 350 return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage, 351 ShouldCreate); 352 } 353 354 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode, 355 Metadata *LB, Metadata *UB, Metadata *Stride, 356 StorageType Storage, bool ShouldCreate) { 357 DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride)); 358 Metadata *Ops[] = {CountNode, LB, UB, Stride}; 359 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops); 360 } 361 362 DISubrange::CountType DISubrange::getCount() const { 363 if (!getRawCountNode()) 364 return CountType(); 365 366 if (auto *MD = dyn_cast<ConstantAsMetadata>(getRawCountNode())) 367 return CountType(cast<ConstantInt>(MD->getValue())); 368 369 if (auto *DV = dyn_cast<DIVariable>(getRawCountNode())) 370 return CountType(DV); 371 372 return CountType(); 373 } 374 375 DISubrange::BoundType DISubrange::getLowerBound() const { 376 Metadata *LB = getRawLowerBound(); 377 if (!LB) 378 return BoundType(); 379 380 assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) || 381 isa<DIExpression>(LB)) && 382 "LowerBound must be signed constant or DIVariable or DIExpression"); 383 384 if (auto *MD = dyn_cast<ConstantAsMetadata>(LB)) 385 return BoundType(cast<ConstantInt>(MD->getValue())); 386 387 if (auto *MD = dyn_cast<DIVariable>(LB)) 388 return BoundType(MD); 389 390 if (auto *MD = dyn_cast<DIExpression>(LB)) 391 return BoundType(MD); 392 393 return BoundType(); 394 } 395 396 DISubrange::BoundType DISubrange::getUpperBound() const { 397 Metadata *UB = getRawUpperBound(); 398 if (!UB) 399 return BoundType(); 400 401 assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) || 402 isa<DIExpression>(UB)) && 403 "UpperBound must be signed constant or DIVariable or DIExpression"); 404 405 if (auto *MD = dyn_cast<ConstantAsMetadata>(UB)) 406 return BoundType(cast<ConstantInt>(MD->getValue())); 407 408 if (auto *MD = dyn_cast<DIVariable>(UB)) 409 return BoundType(MD); 410 411 if (auto *MD = dyn_cast<DIExpression>(UB)) 412 return BoundType(MD); 413 414 return BoundType(); 415 } 416 417 DISubrange::BoundType DISubrange::getStride() const { 418 Metadata *ST = getRawStride(); 419 if (!ST) 420 return BoundType(); 421 422 assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) || 423 isa<DIExpression>(ST)) && 424 "Stride must be signed constant or DIVariable or DIExpression"); 425 426 if (auto *MD = dyn_cast<ConstantAsMetadata>(ST)) 427 return BoundType(cast<ConstantInt>(MD->getValue())); 428 429 if (auto *MD = dyn_cast<DIVariable>(ST)) 430 return BoundType(MD); 431 432 if (auto *MD = dyn_cast<DIExpression>(ST)) 433 return BoundType(MD); 434 435 return BoundType(); 436 } 437 438 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value, 439 bool IsUnsigned, MDString *Name, 440 StorageType Storage, bool ShouldCreate) { 441 assert(isCanonical(Name) && "Expected canonical MDString"); 442 DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name)); 443 Metadata *Ops[] = {Name}; 444 DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops); 445 } 446 447 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag, 448 MDString *Name, uint64_t SizeInBits, 449 uint32_t AlignInBits, unsigned Encoding, 450 DIFlags Flags, StorageType Storage, 451 bool ShouldCreate) { 452 assert(isCanonical(Name) && "Expected canonical MDString"); 453 DEFINE_GETIMPL_LOOKUP(DIBasicType, 454 (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags)); 455 Metadata *Ops[] = {nullptr, nullptr, Name}; 456 DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding, 457 Flags), Ops); 458 } 459 460 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const { 461 switch (getEncoding()) { 462 case dwarf::DW_ATE_signed: 463 case dwarf::DW_ATE_signed_char: 464 return Signedness::Signed; 465 case dwarf::DW_ATE_unsigned: 466 case dwarf::DW_ATE_unsigned_char: 467 return Signedness::Unsigned; 468 default: 469 return None; 470 } 471 } 472 473 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag, 474 MDString *Name, Metadata *StringLength, 475 Metadata *StringLengthExp, 476 uint64_t SizeInBits, uint32_t AlignInBits, 477 unsigned Encoding, StorageType Storage, 478 bool ShouldCreate) { 479 assert(isCanonical(Name) && "Expected canonical MDString"); 480 DEFINE_GETIMPL_LOOKUP(DIStringType, (Tag, Name, StringLength, StringLengthExp, 481 SizeInBits, AlignInBits, Encoding)); 482 Metadata *Ops[] = {nullptr, nullptr, Name, StringLength, StringLengthExp}; 483 DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding), 484 Ops); 485 } 486 487 DIDerivedType *DIDerivedType::getImpl( 488 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File, 489 unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, 490 uint32_t AlignInBits, uint64_t OffsetInBits, 491 Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData, 492 StorageType Storage, bool ShouldCreate) { 493 assert(isCanonical(Name) && "Expected canonical MDString"); 494 DEFINE_GETIMPL_LOOKUP(DIDerivedType, 495 (Tag, Name, File, Line, Scope, BaseType, SizeInBits, 496 AlignInBits, OffsetInBits, DWARFAddressSpace, Flags, 497 ExtraData)); 498 Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData}; 499 DEFINE_GETIMPL_STORE( 500 DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits, 501 DWARFAddressSpace, Flags), Ops); 502 } 503 504 DICompositeType *DICompositeType::getImpl( 505 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File, 506 unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, 507 uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, 508 Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, 509 Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator, 510 Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, 511 Metadata *Rank, StorageType Storage, bool ShouldCreate) { 512 assert(isCanonical(Name) && "Expected canonical MDString"); 513 514 // Keep this in sync with buildODRType. 515 DEFINE_GETIMPL_LOOKUP( 516 DICompositeType, 517 (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, 518 OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, 519 Identifier, Discriminator, DataLocation, Associated, Allocated, Rank)); 520 Metadata *Ops[] = {File, Scope, Name, BaseType, 521 Elements, VTableHolder, TemplateParams, Identifier, 522 Discriminator, DataLocation, Associated, Allocated, 523 Rank}; 524 DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits, 525 AlignInBits, OffsetInBits, Flags), 526 Ops); 527 } 528 529 DICompositeType *DICompositeType::buildODRType( 530 LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, 531 Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, 532 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 533 DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, 534 Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, 535 Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, 536 Metadata *Rank) { 537 assert(!Identifier.getString().empty() && "Expected valid identifier"); 538 if (!Context.isODRUniquingDebugTypes()) 539 return nullptr; 540 auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier]; 541 if (!CT) 542 return CT = DICompositeType::getDistinct( 543 Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, 544 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, 545 VTableHolder, TemplateParams, &Identifier, Discriminator, 546 DataLocation, Associated, Allocated, Rank); 547 548 // Only mutate CT if it's a forward declaration and the new operands aren't. 549 assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?"); 550 if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl)) 551 return CT; 552 553 // Mutate CT in place. Keep this in sync with getImpl. 554 CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, 555 Flags); 556 Metadata *Ops[] = {File, Scope, Name, BaseType, 557 Elements, VTableHolder, TemplateParams, &Identifier, 558 Discriminator, DataLocation, Associated, Allocated, 559 Rank}; 560 assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() && 561 "Mismatched number of operands"); 562 for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I) 563 if (Ops[I] != CT->getOperand(I)) 564 CT->setOperand(I, Ops[I]); 565 return CT; 566 } 567 568 DICompositeType *DICompositeType::getODRType( 569 LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, 570 Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, 571 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 572 DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, 573 Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, 574 Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, 575 Metadata *Rank) { 576 assert(!Identifier.getString().empty() && "Expected valid identifier"); 577 if (!Context.isODRUniquingDebugTypes()) 578 return nullptr; 579 auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier]; 580 if (!CT) 581 CT = DICompositeType::getDistinct( 582 Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, 583 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, 584 TemplateParams, &Identifier, Discriminator, DataLocation, Associated, 585 Allocated, Rank); 586 return CT; 587 } 588 589 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context, 590 MDString &Identifier) { 591 assert(!Identifier.getString().empty() && "Expected valid identifier"); 592 if (!Context.isODRUniquingDebugTypes()) 593 return nullptr; 594 return Context.pImpl->DITypeMap->lookup(&Identifier); 595 } 596 597 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags, 598 uint8_t CC, Metadata *TypeArray, 599 StorageType Storage, 600 bool ShouldCreate) { 601 DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray)); 602 Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray}; 603 DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops); 604 } 605 606 // FIXME: Implement this string-enum correspondence with a .def file and macros, 607 // so that the association is explicit rather than implied. 608 static const char *ChecksumKindName[DIFile::CSK_Last] = { 609 "CSK_MD5", 610 "CSK_SHA1", 611 "CSK_SHA256", 612 }; 613 614 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) { 615 assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind"); 616 // The first space was originally the CSK_None variant, which is now 617 // obsolete, but the space is still reserved in ChecksumKind, so we account 618 // for it here. 619 return ChecksumKindName[CSKind - 1]; 620 } 621 622 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) { 623 return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr) 624 .Case("CSK_MD5", DIFile::CSK_MD5) 625 .Case("CSK_SHA1", DIFile::CSK_SHA1) 626 .Case("CSK_SHA256", DIFile::CSK_SHA256) 627 .Default(None); 628 } 629 630 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename, 631 MDString *Directory, 632 Optional<DIFile::ChecksumInfo<MDString *>> CS, 633 Optional<MDString *> Source, StorageType Storage, 634 bool ShouldCreate) { 635 assert(isCanonical(Filename) && "Expected canonical MDString"); 636 assert(isCanonical(Directory) && "Expected canonical MDString"); 637 assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString"); 638 assert((!Source || isCanonical(*Source)) && "Expected canonical MDString"); 639 DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source)); 640 Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr, 641 Source.getValueOr(nullptr)}; 642 DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops); 643 } 644 645 DICompileUnit *DICompileUnit::getImpl( 646 LLVMContext &Context, unsigned SourceLanguage, Metadata *File, 647 MDString *Producer, bool IsOptimized, MDString *Flags, 648 unsigned RuntimeVersion, MDString *SplitDebugFilename, 649 unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes, 650 Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros, 651 uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling, 652 unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot, 653 MDString *SDK, StorageType Storage, bool ShouldCreate) { 654 assert(Storage != Uniqued && "Cannot unique DICompileUnit"); 655 assert(isCanonical(Producer) && "Expected canonical MDString"); 656 assert(isCanonical(Flags) && "Expected canonical MDString"); 657 assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString"); 658 659 Metadata *Ops[] = {File, 660 Producer, 661 Flags, 662 SplitDebugFilename, 663 EnumTypes, 664 RetainedTypes, 665 GlobalVariables, 666 ImportedEntities, 667 Macros, 668 SysRoot, 669 SDK}; 670 return storeImpl(new (array_lengthof(Ops)) DICompileUnit( 671 Context, Storage, SourceLanguage, IsOptimized, 672 RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining, 673 DebugInfoForProfiling, NameTableKind, RangesBaseAddress, 674 Ops), 675 Storage); 676 } 677 678 Optional<DICompileUnit::DebugEmissionKind> 679 DICompileUnit::getEmissionKind(StringRef Str) { 680 return StringSwitch<Optional<DebugEmissionKind>>(Str) 681 .Case("NoDebug", NoDebug) 682 .Case("FullDebug", FullDebug) 683 .Case("LineTablesOnly", LineTablesOnly) 684 .Case("DebugDirectivesOnly", DebugDirectivesOnly) 685 .Default(None); 686 } 687 688 Optional<DICompileUnit::DebugNameTableKind> 689 DICompileUnit::getNameTableKind(StringRef Str) { 690 return StringSwitch<Optional<DebugNameTableKind>>(Str) 691 .Case("Default", DebugNameTableKind::Default) 692 .Case("GNU", DebugNameTableKind::GNU) 693 .Case("None", DebugNameTableKind::None) 694 .Default(None); 695 } 696 697 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) { 698 switch (EK) { 699 case NoDebug: return "NoDebug"; 700 case FullDebug: return "FullDebug"; 701 case LineTablesOnly: return "LineTablesOnly"; 702 case DebugDirectivesOnly: return "DebugDirectivesOnly"; 703 } 704 return nullptr; 705 } 706 707 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) { 708 switch (NTK) { 709 case DebugNameTableKind::Default: 710 return nullptr; 711 case DebugNameTableKind::GNU: 712 return "GNU"; 713 case DebugNameTableKind::None: 714 return "None"; 715 } 716 return nullptr; 717 } 718 719 DISubprogram *DILocalScope::getSubprogram() const { 720 if (auto *Block = dyn_cast<DILexicalBlockBase>(this)) 721 return Block->getScope()->getSubprogram(); 722 return const_cast<DISubprogram *>(cast<DISubprogram>(this)); 723 } 724 725 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const { 726 if (auto *File = dyn_cast<DILexicalBlockFile>(this)) 727 return File->getScope()->getNonLexicalBlockFileScope(); 728 return const_cast<DILocalScope *>(this); 729 } 730 731 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) { 732 return StringSwitch<DISPFlags>(Flag) 733 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME) 734 #include "llvm/IR/DebugInfoFlags.def" 735 .Default(SPFlagZero); 736 } 737 738 StringRef DISubprogram::getFlagString(DISPFlags Flag) { 739 switch (Flag) { 740 // Appease a warning. 741 case SPFlagVirtuality: 742 return ""; 743 #define HANDLE_DISP_FLAG(ID, NAME) \ 744 case SPFlag##NAME: \ 745 return "DISPFlag" #NAME; 746 #include "llvm/IR/DebugInfoFlags.def" 747 } 748 return ""; 749 } 750 751 DISubprogram::DISPFlags 752 DISubprogram::splitFlags(DISPFlags Flags, 753 SmallVectorImpl<DISPFlags> &SplitFlags) { 754 // Multi-bit fields can require special handling. In our case, however, the 755 // only multi-bit field is virtuality, and all its values happen to be 756 // single-bit values, so the right behavior just falls out. 757 #define HANDLE_DISP_FLAG(ID, NAME) \ 758 if (DISPFlags Bit = Flags & SPFlag##NAME) { \ 759 SplitFlags.push_back(Bit); \ 760 Flags &= ~Bit; \ 761 } 762 #include "llvm/IR/DebugInfoFlags.def" 763 return Flags; 764 } 765 766 DISubprogram *DISubprogram::getImpl( 767 LLVMContext &Context, Metadata *Scope, MDString *Name, 768 MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type, 769 unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex, 770 int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit, 771 Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes, 772 Metadata *ThrownTypes, StorageType Storage, bool ShouldCreate) { 773 assert(isCanonical(Name) && "Expected canonical MDString"); 774 assert(isCanonical(LinkageName) && "Expected canonical MDString"); 775 DEFINE_GETIMPL_LOOKUP(DISubprogram, 776 (Scope, Name, LinkageName, File, Line, Type, ScopeLine, 777 ContainingType, VirtualIndex, ThisAdjustment, Flags, 778 SPFlags, Unit, TemplateParams, Declaration, 779 RetainedNodes, ThrownTypes)); 780 SmallVector<Metadata *, 11> Ops = { 781 File, Scope, Name, LinkageName, Type, Unit, 782 Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes}; 783 if (!ThrownTypes) { 784 Ops.pop_back(); 785 if (!TemplateParams) { 786 Ops.pop_back(); 787 if (!ContainingType) 788 Ops.pop_back(); 789 } 790 } 791 DEFINE_GETIMPL_STORE_N( 792 DISubprogram, 793 (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops, 794 Ops.size()); 795 } 796 797 bool DISubprogram::describes(const Function *F) const { 798 assert(F && "Invalid function"); 799 return F->getSubprogram() == this; 800 } 801 802 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope, 803 Metadata *File, unsigned Line, 804 unsigned Column, StorageType Storage, 805 bool ShouldCreate) { 806 // Fixup column. 807 adjustColumn(Column); 808 809 assert(Scope && "Expected scope"); 810 DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column)); 811 Metadata *Ops[] = {File, Scope}; 812 DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops); 813 } 814 815 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context, 816 Metadata *Scope, Metadata *File, 817 unsigned Discriminator, 818 StorageType Storage, 819 bool ShouldCreate) { 820 assert(Scope && "Expected scope"); 821 DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator)); 822 Metadata *Ops[] = {File, Scope}; 823 DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops); 824 } 825 826 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope, 827 MDString *Name, bool ExportSymbols, 828 StorageType Storage, bool ShouldCreate) { 829 assert(isCanonical(Name) && "Expected canonical MDString"); 830 DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols)); 831 // The nullptr is for DIScope's File operand. This should be refactored. 832 Metadata *Ops[] = {nullptr, Scope, Name}; 833 DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops); 834 } 835 836 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope, 837 Metadata *Decl, MDString *Name, 838 Metadata *File, unsigned LineNo, 839 StorageType Storage, bool ShouldCreate) { 840 assert(isCanonical(Name) && "Expected canonical MDString"); 841 DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo)); 842 // The nullptr is for DIScope's File operand. This should be refactored. 843 Metadata *Ops[] = {Scope, Decl, Name, File}; 844 DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops); 845 } 846 847 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File, 848 Metadata *Scope, MDString *Name, 849 MDString *ConfigurationMacros, 850 MDString *IncludePath, MDString *APINotesFile, 851 unsigned LineNo, StorageType Storage, 852 bool ShouldCreate) { 853 assert(isCanonical(Name) && "Expected canonical MDString"); 854 DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros, 855 IncludePath, APINotesFile, LineNo)); 856 Metadata *Ops[] = {File, Scope, Name, ConfigurationMacros, 857 IncludePath, APINotesFile}; 858 DEFINE_GETIMPL_STORE(DIModule, (LineNo), Ops); 859 } 860 861 DITemplateTypeParameter * 862 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name, 863 Metadata *Type, bool isDefault, 864 StorageType Storage, bool ShouldCreate) { 865 assert(isCanonical(Name) && "Expected canonical MDString"); 866 DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault)); 867 Metadata *Ops[] = {Name, Type}; 868 DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops); 869 } 870 871 DITemplateValueParameter *DITemplateValueParameter::getImpl( 872 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type, 873 bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) { 874 assert(isCanonical(Name) && "Expected canonical MDString"); 875 DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, 876 (Tag, Name, Type, isDefault, Value)); 877 Metadata *Ops[] = {Name, Type, Value}; 878 DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops); 879 } 880 881 DIGlobalVariable * 882 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 883 MDString *LinkageName, Metadata *File, unsigned Line, 884 Metadata *Type, bool IsLocalToUnit, bool IsDefinition, 885 Metadata *StaticDataMemberDeclaration, 886 Metadata *TemplateParams, uint32_t AlignInBits, 887 StorageType Storage, bool ShouldCreate) { 888 assert(isCanonical(Name) && "Expected canonical MDString"); 889 assert(isCanonical(LinkageName) && "Expected canonical MDString"); 890 DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line, 891 Type, IsLocalToUnit, IsDefinition, 892 StaticDataMemberDeclaration, 893 TemplateParams, AlignInBits)); 894 Metadata *Ops[] = {Scope, 895 Name, 896 File, 897 Type, 898 Name, 899 LinkageName, 900 StaticDataMemberDeclaration, 901 TemplateParams}; 902 DEFINE_GETIMPL_STORE(DIGlobalVariable, 903 (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops); 904 } 905 906 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope, 907 MDString *Name, Metadata *File, 908 unsigned Line, Metadata *Type, 909 unsigned Arg, DIFlags Flags, 910 uint32_t AlignInBits, 911 StorageType Storage, 912 bool ShouldCreate) { 913 // 64K ought to be enough for any frontend. 914 assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits"); 915 916 assert(Scope && "Expected scope"); 917 assert(isCanonical(Name) && "Expected canonical MDString"); 918 DEFINE_GETIMPL_LOOKUP(DILocalVariable, 919 (Scope, Name, File, Line, Type, Arg, Flags, 920 AlignInBits)); 921 Metadata *Ops[] = {Scope, Name, File, Type}; 922 DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops); 923 } 924 925 Optional<uint64_t> DIVariable::getSizeInBits() const { 926 // This is used by the Verifier so be mindful of broken types. 927 const Metadata *RawType = getRawType(); 928 while (RawType) { 929 // Try to get the size directly. 930 if (auto *T = dyn_cast<DIType>(RawType)) 931 if (uint64_t Size = T->getSizeInBits()) 932 return Size; 933 934 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) { 935 // Look at the base type. 936 RawType = DT->getRawBaseType(); 937 continue; 938 } 939 940 // Missing type or size. 941 break; 942 } 943 944 // Fail gracefully. 945 return None; 946 } 947 948 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope, 949 MDString *Name, Metadata *File, unsigned Line, 950 StorageType Storage, 951 bool ShouldCreate) { 952 assert(Scope && "Expected scope"); 953 assert(isCanonical(Name) && "Expected canonical MDString"); 954 DEFINE_GETIMPL_LOOKUP(DILabel, 955 (Scope, Name, File, Line)); 956 Metadata *Ops[] = {Scope, Name, File}; 957 DEFINE_GETIMPL_STORE(DILabel, (Line), Ops); 958 } 959 960 DIExpression *DIExpression::getImpl(LLVMContext &Context, 961 ArrayRef<uint64_t> Elements, 962 StorageType Storage, bool ShouldCreate) { 963 DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements)); 964 DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements)); 965 } 966 967 unsigned DIExpression::ExprOperand::getSize() const { 968 uint64_t Op = getOp(); 969 970 if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31) 971 return 2; 972 973 switch (Op) { 974 case dwarf::DW_OP_LLVM_convert: 975 case dwarf::DW_OP_LLVM_fragment: 976 case dwarf::DW_OP_bregx: 977 return 3; 978 case dwarf::DW_OP_constu: 979 case dwarf::DW_OP_consts: 980 case dwarf::DW_OP_deref_size: 981 case dwarf::DW_OP_plus_uconst: 982 case dwarf::DW_OP_LLVM_tag_offset: 983 case dwarf::DW_OP_LLVM_entry_value: 984 case dwarf::DW_OP_regx: 985 return 2; 986 default: 987 return 1; 988 } 989 } 990 991 bool DIExpression::isValid() const { 992 for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) { 993 // Check that there's space for the operand. 994 if (I->get() + I->getSize() > E->get()) 995 return false; 996 997 uint64_t Op = I->getOp(); 998 if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) || 999 (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)) 1000 return true; 1001 1002 // Check that the operand is valid. 1003 switch (Op) { 1004 default: 1005 return false; 1006 case dwarf::DW_OP_LLVM_fragment: 1007 // A fragment operator must appear at the end. 1008 return I->get() + I->getSize() == E->get(); 1009 case dwarf::DW_OP_stack_value: { 1010 // Must be the last one or followed by a DW_OP_LLVM_fragment. 1011 if (I->get() + I->getSize() == E->get()) 1012 break; 1013 auto J = I; 1014 if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment) 1015 return false; 1016 break; 1017 } 1018 case dwarf::DW_OP_swap: { 1019 // Must be more than one implicit element on the stack. 1020 1021 // FIXME: A better way to implement this would be to add a local variable 1022 // that keeps track of the stack depth and introduce something like a 1023 // DW_LLVM_OP_implicit_location as a placeholder for the location this 1024 // DIExpression is attached to, or else pass the number of implicit stack 1025 // elements into isValid. 1026 if (getNumElements() == 1) 1027 return false; 1028 break; 1029 } 1030 case dwarf::DW_OP_LLVM_entry_value: { 1031 // An entry value operator must appear at the beginning and the number of 1032 // operations it cover can currently only be 1, because we support only 1033 // entry values of a simple register location. One reason for this is that 1034 // we currently can't calculate the size of the resulting DWARF block for 1035 // other expressions. 1036 return I->get() == expr_op_begin()->get() && I->getArg(0) == 1 && 1037 getNumElements() == 2; 1038 } 1039 case dwarf::DW_OP_LLVM_convert: 1040 case dwarf::DW_OP_LLVM_tag_offset: 1041 case dwarf::DW_OP_constu: 1042 case dwarf::DW_OP_plus_uconst: 1043 case dwarf::DW_OP_plus: 1044 case dwarf::DW_OP_minus: 1045 case dwarf::DW_OP_mul: 1046 case dwarf::DW_OP_div: 1047 case dwarf::DW_OP_mod: 1048 case dwarf::DW_OP_or: 1049 case dwarf::DW_OP_and: 1050 case dwarf::DW_OP_xor: 1051 case dwarf::DW_OP_shl: 1052 case dwarf::DW_OP_shr: 1053 case dwarf::DW_OP_shra: 1054 case dwarf::DW_OP_deref: 1055 case dwarf::DW_OP_deref_size: 1056 case dwarf::DW_OP_xderef: 1057 case dwarf::DW_OP_lit0: 1058 case dwarf::DW_OP_not: 1059 case dwarf::DW_OP_dup: 1060 case dwarf::DW_OP_regx: 1061 case dwarf::DW_OP_bregx: 1062 case dwarf::DW_OP_push_object_address: 1063 break; 1064 } 1065 } 1066 return true; 1067 } 1068 1069 bool DIExpression::isImplicit() const { 1070 if (!isValid()) 1071 return false; 1072 1073 if (getNumElements() == 0) 1074 return false; 1075 1076 for (const auto &It : expr_ops()) { 1077 switch (It.getOp()) { 1078 default: 1079 break; 1080 case dwarf::DW_OP_stack_value: 1081 case dwarf::DW_OP_LLVM_tag_offset: 1082 return true; 1083 } 1084 } 1085 1086 return false; 1087 } 1088 1089 bool DIExpression::isComplex() const { 1090 if (!isValid()) 1091 return false; 1092 1093 if (getNumElements() == 0) 1094 return false; 1095 1096 // If there are any elements other than fragment or tag_offset, then some 1097 // kind of complex computation occurs. 1098 for (const auto &It : expr_ops()) { 1099 switch (It.getOp()) { 1100 case dwarf::DW_OP_LLVM_tag_offset: 1101 case dwarf::DW_OP_LLVM_fragment: 1102 continue; 1103 default: return true; 1104 } 1105 } 1106 1107 return false; 1108 } 1109 1110 Optional<DIExpression::FragmentInfo> 1111 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) { 1112 for (auto I = Start; I != End; ++I) 1113 if (I->getOp() == dwarf::DW_OP_LLVM_fragment) { 1114 DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)}; 1115 return Info; 1116 } 1117 return None; 1118 } 1119 1120 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops, 1121 int64_t Offset) { 1122 if (Offset > 0) { 1123 Ops.push_back(dwarf::DW_OP_plus_uconst); 1124 Ops.push_back(Offset); 1125 } else if (Offset < 0) { 1126 Ops.push_back(dwarf::DW_OP_constu); 1127 Ops.push_back(-Offset); 1128 Ops.push_back(dwarf::DW_OP_minus); 1129 } 1130 } 1131 1132 bool DIExpression::extractIfOffset(int64_t &Offset) const { 1133 if (getNumElements() == 0) { 1134 Offset = 0; 1135 return true; 1136 } 1137 1138 if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) { 1139 Offset = Elements[1]; 1140 return true; 1141 } 1142 1143 if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) { 1144 if (Elements[2] == dwarf::DW_OP_plus) { 1145 Offset = Elements[1]; 1146 return true; 1147 } 1148 if (Elements[2] == dwarf::DW_OP_minus) { 1149 Offset = -Elements[1]; 1150 return true; 1151 } 1152 } 1153 1154 return false; 1155 } 1156 1157 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr, 1158 unsigned &AddrClass) { 1159 // FIXME: This seems fragile. Nothing that verifies that these elements 1160 // actually map to ops and not operands. 1161 const unsigned PatternSize = 4; 1162 if (Expr->Elements.size() >= PatternSize && 1163 Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu && 1164 Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap && 1165 Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) { 1166 AddrClass = Expr->Elements[PatternSize - 3]; 1167 1168 if (Expr->Elements.size() == PatternSize) 1169 return nullptr; 1170 return DIExpression::get(Expr->getContext(), 1171 makeArrayRef(&*Expr->Elements.begin(), 1172 Expr->Elements.size() - PatternSize)); 1173 } 1174 return Expr; 1175 } 1176 1177 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags, 1178 int64_t Offset) { 1179 SmallVector<uint64_t, 8> Ops; 1180 if (Flags & DIExpression::DerefBefore) 1181 Ops.push_back(dwarf::DW_OP_deref); 1182 1183 appendOffset(Ops, Offset); 1184 if (Flags & DIExpression::DerefAfter) 1185 Ops.push_back(dwarf::DW_OP_deref); 1186 1187 bool StackValue = Flags & DIExpression::StackValue; 1188 bool EntryValue = Flags & DIExpression::EntryValue; 1189 1190 return prependOpcodes(Expr, Ops, StackValue, EntryValue); 1191 } 1192 1193 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr, 1194 SmallVectorImpl<uint64_t> &Ops, 1195 bool StackValue, 1196 bool EntryValue) { 1197 assert(Expr && "Can't prepend ops to this expression"); 1198 1199 if (EntryValue) { 1200 Ops.push_back(dwarf::DW_OP_LLVM_entry_value); 1201 // Add size info needed for entry value expression. 1202 // Add plus one for target register operand. 1203 Ops.push_back(Expr->getNumElements() + 1); 1204 } 1205 1206 // If there are no ops to prepend, do not even add the DW_OP_stack_value. 1207 if (Ops.empty()) 1208 StackValue = false; 1209 for (auto Op : Expr->expr_ops()) { 1210 // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment. 1211 if (StackValue) { 1212 if (Op.getOp() == dwarf::DW_OP_stack_value) 1213 StackValue = false; 1214 else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1215 Ops.push_back(dwarf::DW_OP_stack_value); 1216 StackValue = false; 1217 } 1218 } 1219 Op.appendToVector(Ops); 1220 } 1221 if (StackValue) 1222 Ops.push_back(dwarf::DW_OP_stack_value); 1223 return DIExpression::get(Expr->getContext(), Ops); 1224 } 1225 1226 DIExpression *DIExpression::append(const DIExpression *Expr, 1227 ArrayRef<uint64_t> Ops) { 1228 assert(Expr && !Ops.empty() && "Can't append ops to this expression"); 1229 1230 // Copy Expr's current op list. 1231 SmallVector<uint64_t, 16> NewOps; 1232 for (auto Op : Expr->expr_ops()) { 1233 // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}. 1234 if (Op.getOp() == dwarf::DW_OP_stack_value || 1235 Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1236 NewOps.append(Ops.begin(), Ops.end()); 1237 1238 // Ensure that the new opcodes are only appended once. 1239 Ops = None; 1240 } 1241 Op.appendToVector(NewOps); 1242 } 1243 1244 NewOps.append(Ops.begin(), Ops.end()); 1245 auto *result = DIExpression::get(Expr->getContext(), NewOps); 1246 assert(result->isValid() && "concatenated expression is not valid"); 1247 return result; 1248 } 1249 1250 DIExpression *DIExpression::appendToStack(const DIExpression *Expr, 1251 ArrayRef<uint64_t> Ops) { 1252 assert(Expr && !Ops.empty() && "Can't append ops to this expression"); 1253 assert(none_of(Ops, 1254 [](uint64_t Op) { 1255 return Op == dwarf::DW_OP_stack_value || 1256 Op == dwarf::DW_OP_LLVM_fragment; 1257 }) && 1258 "Can't append this op"); 1259 1260 // Append a DW_OP_deref after Expr's current op list if it's non-empty and 1261 // has no DW_OP_stack_value. 1262 // 1263 // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?. 1264 Optional<FragmentInfo> FI = Expr->getFragmentInfo(); 1265 unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0; 1266 ArrayRef<uint64_t> ExprOpsBeforeFragment = 1267 Expr->getElements().drop_back(DropUntilStackValue); 1268 bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) && 1269 (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value); 1270 bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty(); 1271 1272 // Append a DW_OP_deref after Expr's current op list if needed, then append 1273 // the new ops, and finally ensure that a single DW_OP_stack_value is present. 1274 SmallVector<uint64_t, 16> NewOps; 1275 if (NeedsDeref) 1276 NewOps.push_back(dwarf::DW_OP_deref); 1277 NewOps.append(Ops.begin(), Ops.end()); 1278 if (NeedsStackValue) 1279 NewOps.push_back(dwarf::DW_OP_stack_value); 1280 return DIExpression::append(Expr, NewOps); 1281 } 1282 1283 Optional<DIExpression *> DIExpression::createFragmentExpression( 1284 const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) { 1285 SmallVector<uint64_t, 8> Ops; 1286 // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment. 1287 if (Expr) { 1288 for (auto Op : Expr->expr_ops()) { 1289 switch (Op.getOp()) { 1290 default: break; 1291 case dwarf::DW_OP_shr: 1292 case dwarf::DW_OP_shra: 1293 case dwarf::DW_OP_shl: 1294 case dwarf::DW_OP_plus: 1295 case dwarf::DW_OP_plus_uconst: 1296 case dwarf::DW_OP_minus: 1297 // We can't safely split arithmetic or shift operations into multiple 1298 // fragments because we can't express carry-over between fragments. 1299 // 1300 // FIXME: We *could* preserve the lowest fragment of a constant offset 1301 // operation if the offset fits into SizeInBits. 1302 return None; 1303 case dwarf::DW_OP_LLVM_fragment: { 1304 // Make the new offset point into the existing fragment. 1305 uint64_t FragmentOffsetInBits = Op.getArg(0); 1306 uint64_t FragmentSizeInBits = Op.getArg(1); 1307 (void)FragmentSizeInBits; 1308 assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) && 1309 "new fragment outside of original fragment"); 1310 OffsetInBits += FragmentOffsetInBits; 1311 continue; 1312 } 1313 } 1314 Op.appendToVector(Ops); 1315 } 1316 } 1317 assert(Expr && "Unknown DIExpression"); 1318 Ops.push_back(dwarf::DW_OP_LLVM_fragment); 1319 Ops.push_back(OffsetInBits); 1320 Ops.push_back(SizeInBits); 1321 return DIExpression::get(Expr->getContext(), Ops); 1322 } 1323 1324 bool DIExpression::isConstant() const { 1325 // Recognize DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment Len Ofs)?. 1326 if (getNumElements() != 3 && getNumElements() != 6) 1327 return false; 1328 if (getElement(0) != dwarf::DW_OP_constu || 1329 getElement(2) != dwarf::DW_OP_stack_value) 1330 return false; 1331 if (getNumElements() == 6 && getElement(3) != dwarf::DW_OP_LLVM_fragment) 1332 return false; 1333 return true; 1334 } 1335 1336 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize, 1337 bool Signed) { 1338 dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned; 1339 DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK, 1340 dwarf::DW_OP_LLVM_convert, ToSize, TK}}; 1341 return Ops; 1342 } 1343 1344 DIExpression *DIExpression::appendExt(const DIExpression *Expr, 1345 unsigned FromSize, unsigned ToSize, 1346 bool Signed) { 1347 return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed)); 1348 } 1349 1350 DIGlobalVariableExpression * 1351 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable, 1352 Metadata *Expression, StorageType Storage, 1353 bool ShouldCreate) { 1354 DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression)); 1355 Metadata *Ops[] = {Variable, Expression}; 1356 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops); 1357 } 1358 1359 DIObjCProperty *DIObjCProperty::getImpl( 1360 LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line, 1361 MDString *GetterName, MDString *SetterName, unsigned Attributes, 1362 Metadata *Type, StorageType Storage, bool ShouldCreate) { 1363 assert(isCanonical(Name) && "Expected canonical MDString"); 1364 assert(isCanonical(GetterName) && "Expected canonical MDString"); 1365 assert(isCanonical(SetterName) && "Expected canonical MDString"); 1366 DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName, 1367 SetterName, Attributes, Type)); 1368 Metadata *Ops[] = {Name, File, GetterName, SetterName, Type}; 1369 DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops); 1370 } 1371 1372 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag, 1373 Metadata *Scope, Metadata *Entity, 1374 Metadata *File, unsigned Line, 1375 MDString *Name, StorageType Storage, 1376 bool ShouldCreate) { 1377 assert(isCanonical(Name) && "Expected canonical MDString"); 1378 DEFINE_GETIMPL_LOOKUP(DIImportedEntity, 1379 (Tag, Scope, Entity, File, Line, Name)); 1380 Metadata *Ops[] = {Scope, Entity, Name, File}; 1381 DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops); 1382 } 1383 1384 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType, 1385 unsigned Line, MDString *Name, MDString *Value, 1386 StorageType Storage, bool ShouldCreate) { 1387 assert(isCanonical(Name) && "Expected canonical MDString"); 1388 DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value)); 1389 Metadata *Ops[] = { Name, Value }; 1390 DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops); 1391 } 1392 1393 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType, 1394 unsigned Line, Metadata *File, 1395 Metadata *Elements, StorageType Storage, 1396 bool ShouldCreate) { 1397 DEFINE_GETIMPL_LOOKUP(DIMacroFile, 1398 (MIType, Line, File, Elements)); 1399 Metadata *Ops[] = { File, Elements }; 1400 DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops); 1401 } 1402