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 SmallVector<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 return getImpl(Context, CountNode, Lo, Storage, ShouldCreate); 340 } 341 342 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode, 343 int64_t Lo, StorageType Storage, 344 bool ShouldCreate) { 345 DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, Lo)); 346 Metadata *Ops[] = { CountNode }; 347 DEFINE_GETIMPL_STORE(DISubrange, (CountNode, Lo), Ops); 348 } 349 350 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, APInt Value, 351 bool IsUnsigned, MDString *Name, 352 StorageType Storage, bool ShouldCreate) { 353 assert(isCanonical(Name) && "Expected canonical MDString"); 354 DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name)); 355 Metadata *Ops[] = {Name}; 356 DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops); 357 } 358 359 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag, 360 MDString *Name, uint64_t SizeInBits, 361 uint32_t AlignInBits, unsigned Encoding, 362 DIFlags Flags, StorageType Storage, 363 bool ShouldCreate) { 364 assert(isCanonical(Name) && "Expected canonical MDString"); 365 DEFINE_GETIMPL_LOOKUP(DIBasicType, 366 (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags)); 367 Metadata *Ops[] = {nullptr, nullptr, Name}; 368 DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding, 369 Flags), Ops); 370 } 371 372 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const { 373 switch (getEncoding()) { 374 case dwarf::DW_ATE_signed: 375 case dwarf::DW_ATE_signed_char: 376 return Signedness::Signed; 377 case dwarf::DW_ATE_unsigned: 378 case dwarf::DW_ATE_unsigned_char: 379 return Signedness::Unsigned; 380 default: 381 return None; 382 } 383 } 384 385 DIDerivedType *DIDerivedType::getImpl( 386 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File, 387 unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, 388 uint32_t AlignInBits, uint64_t OffsetInBits, 389 Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData, 390 StorageType Storage, bool ShouldCreate) { 391 assert(isCanonical(Name) && "Expected canonical MDString"); 392 DEFINE_GETIMPL_LOOKUP(DIDerivedType, 393 (Tag, Name, File, Line, Scope, BaseType, SizeInBits, 394 AlignInBits, OffsetInBits, DWARFAddressSpace, Flags, 395 ExtraData)); 396 Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData}; 397 DEFINE_GETIMPL_STORE( 398 DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits, 399 DWARFAddressSpace, Flags), Ops); 400 } 401 402 DICompositeType *DICompositeType::getImpl( 403 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File, 404 unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, 405 uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, 406 Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, 407 Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator, 408 Metadata *DataLocation, StorageType Storage, bool ShouldCreate) { 409 assert(isCanonical(Name) && "Expected canonical MDString"); 410 411 // Keep this in sync with buildODRType. 412 DEFINE_GETIMPL_LOOKUP(DICompositeType, 413 (Tag, Name, File, Line, Scope, BaseType, SizeInBits, 414 AlignInBits, OffsetInBits, Flags, Elements, 415 RuntimeLang, VTableHolder, TemplateParams, Identifier, 416 Discriminator, DataLocation)); 417 Metadata *Ops[] = {File, Scope, Name, BaseType, 418 Elements, VTableHolder, TemplateParams, Identifier, 419 Discriminator, DataLocation}; 420 DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits, 421 AlignInBits, OffsetInBits, Flags), 422 Ops); 423 } 424 425 DICompositeType *DICompositeType::buildODRType( 426 LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, 427 Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, 428 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 429 DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, 430 Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, 431 Metadata *DataLocation) { 432 assert(!Identifier.getString().empty() && "Expected valid identifier"); 433 if (!Context.isODRUniquingDebugTypes()) 434 return nullptr; 435 auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier]; 436 if (!CT) 437 return CT = DICompositeType::getDistinct( 438 Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, 439 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, 440 VTableHolder, TemplateParams, &Identifier, Discriminator, 441 DataLocation); 442 443 // Only mutate CT if it's a forward declaration and the new operands aren't. 444 assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?"); 445 if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl)) 446 return CT; 447 448 // Mutate CT in place. Keep this in sync with getImpl. 449 CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, 450 Flags); 451 Metadata *Ops[] = {File, Scope, Name, BaseType, 452 Elements, VTableHolder, TemplateParams, &Identifier, 453 Discriminator, DataLocation}; 454 assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() && 455 "Mismatched number of operands"); 456 for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I) 457 if (Ops[I] != CT->getOperand(I)) 458 CT->setOperand(I, Ops[I]); 459 return CT; 460 } 461 462 DICompositeType *DICompositeType::getODRType( 463 LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, 464 Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, 465 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, 466 DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, 467 Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, 468 Metadata *DataLocation) { 469 assert(!Identifier.getString().empty() && "Expected valid identifier"); 470 if (!Context.isODRUniquingDebugTypes()) 471 return nullptr; 472 auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier]; 473 if (!CT) 474 CT = DICompositeType::getDistinct( 475 Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, 476 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, 477 TemplateParams, &Identifier, Discriminator, DataLocation); 478 return CT; 479 } 480 481 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context, 482 MDString &Identifier) { 483 assert(!Identifier.getString().empty() && "Expected valid identifier"); 484 if (!Context.isODRUniquingDebugTypes()) 485 return nullptr; 486 return Context.pImpl->DITypeMap->lookup(&Identifier); 487 } 488 489 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags, 490 uint8_t CC, Metadata *TypeArray, 491 StorageType Storage, 492 bool ShouldCreate) { 493 DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray)); 494 Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray}; 495 DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops); 496 } 497 498 // FIXME: Implement this string-enum correspondence with a .def file and macros, 499 // so that the association is explicit rather than implied. 500 static const char *ChecksumKindName[DIFile::CSK_Last] = { 501 "CSK_MD5", 502 "CSK_SHA1", 503 "CSK_SHA256", 504 }; 505 506 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) { 507 assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind"); 508 // The first space was originally the CSK_None variant, which is now 509 // obsolete, but the space is still reserved in ChecksumKind, so we account 510 // for it here. 511 return ChecksumKindName[CSKind - 1]; 512 } 513 514 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) { 515 return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr) 516 .Case("CSK_MD5", DIFile::CSK_MD5) 517 .Case("CSK_SHA1", DIFile::CSK_SHA1) 518 .Case("CSK_SHA256", DIFile::CSK_SHA256) 519 .Default(None); 520 } 521 522 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename, 523 MDString *Directory, 524 Optional<DIFile::ChecksumInfo<MDString *>> CS, 525 Optional<MDString *> Source, StorageType Storage, 526 bool ShouldCreate) { 527 assert(isCanonical(Filename) && "Expected canonical MDString"); 528 assert(isCanonical(Directory) && "Expected canonical MDString"); 529 assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString"); 530 assert((!Source || isCanonical(*Source)) && "Expected canonical MDString"); 531 DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source)); 532 Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr, 533 Source.getValueOr(nullptr)}; 534 DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops); 535 } 536 537 DICompileUnit *DICompileUnit::getImpl( 538 LLVMContext &Context, unsigned SourceLanguage, Metadata *File, 539 MDString *Producer, bool IsOptimized, MDString *Flags, 540 unsigned RuntimeVersion, MDString *SplitDebugFilename, 541 unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes, 542 Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros, 543 uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling, 544 unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot, 545 MDString *SDK, StorageType Storage, bool ShouldCreate) { 546 assert(Storage != Uniqued && "Cannot unique DICompileUnit"); 547 assert(isCanonical(Producer) && "Expected canonical MDString"); 548 assert(isCanonical(Flags) && "Expected canonical MDString"); 549 assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString"); 550 551 Metadata *Ops[] = {File, 552 Producer, 553 Flags, 554 SplitDebugFilename, 555 EnumTypes, 556 RetainedTypes, 557 GlobalVariables, 558 ImportedEntities, 559 Macros, 560 SysRoot, 561 SDK}; 562 return storeImpl(new (array_lengthof(Ops)) DICompileUnit( 563 Context, Storage, SourceLanguage, IsOptimized, 564 RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining, 565 DebugInfoForProfiling, NameTableKind, RangesBaseAddress, 566 Ops), 567 Storage); 568 } 569 570 Optional<DICompileUnit::DebugEmissionKind> 571 DICompileUnit::getEmissionKind(StringRef Str) { 572 return StringSwitch<Optional<DebugEmissionKind>>(Str) 573 .Case("NoDebug", NoDebug) 574 .Case("FullDebug", FullDebug) 575 .Case("LineTablesOnly", LineTablesOnly) 576 .Case("DebugDirectivesOnly", DebugDirectivesOnly) 577 .Default(None); 578 } 579 580 Optional<DICompileUnit::DebugNameTableKind> 581 DICompileUnit::getNameTableKind(StringRef Str) { 582 return StringSwitch<Optional<DebugNameTableKind>>(Str) 583 .Case("Default", DebugNameTableKind::Default) 584 .Case("GNU", DebugNameTableKind::GNU) 585 .Case("None", DebugNameTableKind::None) 586 .Default(None); 587 } 588 589 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) { 590 switch (EK) { 591 case NoDebug: return "NoDebug"; 592 case FullDebug: return "FullDebug"; 593 case LineTablesOnly: return "LineTablesOnly"; 594 case DebugDirectivesOnly: return "DebugDirectivesOnly"; 595 } 596 return nullptr; 597 } 598 599 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) { 600 switch (NTK) { 601 case DebugNameTableKind::Default: 602 return nullptr; 603 case DebugNameTableKind::GNU: 604 return "GNU"; 605 case DebugNameTableKind::None: 606 return "None"; 607 } 608 return nullptr; 609 } 610 611 DISubprogram *DILocalScope::getSubprogram() const { 612 if (auto *Block = dyn_cast<DILexicalBlockBase>(this)) 613 return Block->getScope()->getSubprogram(); 614 return const_cast<DISubprogram *>(cast<DISubprogram>(this)); 615 } 616 617 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const { 618 if (auto *File = dyn_cast<DILexicalBlockFile>(this)) 619 return File->getScope()->getNonLexicalBlockFileScope(); 620 return const_cast<DILocalScope *>(this); 621 } 622 623 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) { 624 return StringSwitch<DISPFlags>(Flag) 625 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME) 626 #include "llvm/IR/DebugInfoFlags.def" 627 .Default(SPFlagZero); 628 } 629 630 StringRef DISubprogram::getFlagString(DISPFlags Flag) { 631 switch (Flag) { 632 // Appease a warning. 633 case SPFlagVirtuality: 634 return ""; 635 #define HANDLE_DISP_FLAG(ID, NAME) \ 636 case SPFlag##NAME: \ 637 return "DISPFlag" #NAME; 638 #include "llvm/IR/DebugInfoFlags.def" 639 } 640 return ""; 641 } 642 643 DISubprogram::DISPFlags 644 DISubprogram::splitFlags(DISPFlags Flags, 645 SmallVectorImpl<DISPFlags> &SplitFlags) { 646 // Multi-bit fields can require special handling. In our case, however, the 647 // only multi-bit field is virtuality, and all its values happen to be 648 // single-bit values, so the right behavior just falls out. 649 #define HANDLE_DISP_FLAG(ID, NAME) \ 650 if (DISPFlags Bit = Flags & SPFlag##NAME) { \ 651 SplitFlags.push_back(Bit); \ 652 Flags &= ~Bit; \ 653 } 654 #include "llvm/IR/DebugInfoFlags.def" 655 return Flags; 656 } 657 658 DISubprogram *DISubprogram::getImpl( 659 LLVMContext &Context, Metadata *Scope, MDString *Name, 660 MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type, 661 unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex, 662 int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit, 663 Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes, 664 Metadata *ThrownTypes, StorageType Storage, bool ShouldCreate) { 665 assert(isCanonical(Name) && "Expected canonical MDString"); 666 assert(isCanonical(LinkageName) && "Expected canonical MDString"); 667 DEFINE_GETIMPL_LOOKUP(DISubprogram, 668 (Scope, Name, LinkageName, File, Line, Type, ScopeLine, 669 ContainingType, VirtualIndex, ThisAdjustment, Flags, 670 SPFlags, Unit, TemplateParams, Declaration, 671 RetainedNodes, ThrownTypes)); 672 SmallVector<Metadata *, 11> Ops = { 673 File, Scope, Name, LinkageName, Type, Unit, 674 Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes}; 675 if (!ThrownTypes) { 676 Ops.pop_back(); 677 if (!TemplateParams) { 678 Ops.pop_back(); 679 if (!ContainingType) 680 Ops.pop_back(); 681 } 682 } 683 DEFINE_GETIMPL_STORE_N( 684 DISubprogram, 685 (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops, 686 Ops.size()); 687 } 688 689 bool DISubprogram::describes(const Function *F) const { 690 assert(F && "Invalid function"); 691 return F->getSubprogram() == this; 692 } 693 694 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope, 695 Metadata *File, unsigned Line, 696 unsigned Column, StorageType Storage, 697 bool ShouldCreate) { 698 // Fixup column. 699 adjustColumn(Column); 700 701 assert(Scope && "Expected scope"); 702 DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column)); 703 Metadata *Ops[] = {File, Scope}; 704 DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops); 705 } 706 707 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context, 708 Metadata *Scope, Metadata *File, 709 unsigned Discriminator, 710 StorageType Storage, 711 bool ShouldCreate) { 712 assert(Scope && "Expected scope"); 713 DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator)); 714 Metadata *Ops[] = {File, Scope}; 715 DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops); 716 } 717 718 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope, 719 MDString *Name, bool ExportSymbols, 720 StorageType Storage, bool ShouldCreate) { 721 assert(isCanonical(Name) && "Expected canonical MDString"); 722 DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols)); 723 // The nullptr is for DIScope's File operand. This should be refactored. 724 Metadata *Ops[] = {nullptr, Scope, Name}; 725 DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops); 726 } 727 728 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope, 729 Metadata *Decl, MDString *Name, 730 Metadata *File, unsigned LineNo, 731 StorageType Storage, bool ShouldCreate) { 732 assert(isCanonical(Name) && "Expected canonical MDString"); 733 DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo)); 734 // The nullptr is for DIScope's File operand. This should be refactored. 735 Metadata *Ops[] = {Scope, Decl, Name, File}; 736 DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops); 737 } 738 739 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File, 740 Metadata *Scope, MDString *Name, 741 MDString *ConfigurationMacros, 742 MDString *IncludePath, MDString *APINotesFile, 743 unsigned LineNo, StorageType Storage, 744 bool ShouldCreate) { 745 assert(isCanonical(Name) && "Expected canonical MDString"); 746 DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros, 747 IncludePath, APINotesFile, LineNo)); 748 Metadata *Ops[] = {File, Scope, Name, ConfigurationMacros, 749 IncludePath, APINotesFile}; 750 DEFINE_GETIMPL_STORE(DIModule, (LineNo), Ops); 751 } 752 753 DITemplateTypeParameter * 754 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name, 755 Metadata *Type, bool isDefault, 756 StorageType Storage, bool ShouldCreate) { 757 assert(isCanonical(Name) && "Expected canonical MDString"); 758 DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault)); 759 Metadata *Ops[] = {Name, Type}; 760 DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops); 761 } 762 763 DITemplateValueParameter *DITemplateValueParameter::getImpl( 764 LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type, 765 bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) { 766 assert(isCanonical(Name) && "Expected canonical MDString"); 767 DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, 768 (Tag, Name, Type, isDefault, Value)); 769 Metadata *Ops[] = {Name, Type, Value}; 770 DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops); 771 } 772 773 DIGlobalVariable * 774 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name, 775 MDString *LinkageName, Metadata *File, unsigned Line, 776 Metadata *Type, bool IsLocalToUnit, bool IsDefinition, 777 Metadata *StaticDataMemberDeclaration, 778 Metadata *TemplateParams, uint32_t AlignInBits, 779 StorageType Storage, bool ShouldCreate) { 780 assert(isCanonical(Name) && "Expected canonical MDString"); 781 assert(isCanonical(LinkageName) && "Expected canonical MDString"); 782 DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line, 783 Type, IsLocalToUnit, IsDefinition, 784 StaticDataMemberDeclaration, 785 TemplateParams, AlignInBits)); 786 Metadata *Ops[] = {Scope, 787 Name, 788 File, 789 Type, 790 Name, 791 LinkageName, 792 StaticDataMemberDeclaration, 793 TemplateParams}; 794 DEFINE_GETIMPL_STORE(DIGlobalVariable, 795 (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops); 796 } 797 798 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope, 799 MDString *Name, Metadata *File, 800 unsigned Line, Metadata *Type, 801 unsigned Arg, DIFlags Flags, 802 uint32_t AlignInBits, 803 StorageType Storage, 804 bool ShouldCreate) { 805 // 64K ought to be enough for any frontend. 806 assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits"); 807 808 assert(Scope && "Expected scope"); 809 assert(isCanonical(Name) && "Expected canonical MDString"); 810 DEFINE_GETIMPL_LOOKUP(DILocalVariable, 811 (Scope, Name, File, Line, Type, Arg, Flags, 812 AlignInBits)); 813 Metadata *Ops[] = {Scope, Name, File, Type}; 814 DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops); 815 } 816 817 Optional<uint64_t> DIVariable::getSizeInBits() const { 818 // This is used by the Verifier so be mindful of broken types. 819 const Metadata *RawType = getRawType(); 820 while (RawType) { 821 // Try to get the size directly. 822 if (auto *T = dyn_cast<DIType>(RawType)) 823 if (uint64_t Size = T->getSizeInBits()) 824 return Size; 825 826 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) { 827 // Look at the base type. 828 RawType = DT->getRawBaseType(); 829 continue; 830 } 831 832 // Missing type or size. 833 break; 834 } 835 836 // Fail gracefully. 837 return None; 838 } 839 840 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope, 841 MDString *Name, Metadata *File, unsigned Line, 842 StorageType Storage, 843 bool ShouldCreate) { 844 assert(Scope && "Expected scope"); 845 assert(isCanonical(Name) && "Expected canonical MDString"); 846 DEFINE_GETIMPL_LOOKUP(DILabel, 847 (Scope, Name, File, Line)); 848 Metadata *Ops[] = {Scope, Name, File}; 849 DEFINE_GETIMPL_STORE(DILabel, (Line), Ops); 850 } 851 852 DIExpression *DIExpression::getImpl(LLVMContext &Context, 853 ArrayRef<uint64_t> Elements, 854 StorageType Storage, bool ShouldCreate) { 855 DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements)); 856 DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements)); 857 } 858 859 unsigned DIExpression::ExprOperand::getSize() const { 860 uint64_t Op = getOp(); 861 862 if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31) 863 return 2; 864 865 switch (Op) { 866 case dwarf::DW_OP_LLVM_convert: 867 case dwarf::DW_OP_LLVM_fragment: 868 case dwarf::DW_OP_bregx: 869 return 3; 870 case dwarf::DW_OP_constu: 871 case dwarf::DW_OP_consts: 872 case dwarf::DW_OP_deref_size: 873 case dwarf::DW_OP_plus_uconst: 874 case dwarf::DW_OP_LLVM_tag_offset: 875 case dwarf::DW_OP_LLVM_entry_value: 876 case dwarf::DW_OP_regx: 877 return 2; 878 default: 879 return 1; 880 } 881 } 882 883 bool DIExpression::isValid() const { 884 for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) { 885 // Check that there's space for the operand. 886 if (I->get() + I->getSize() > E->get()) 887 return false; 888 889 uint64_t Op = I->getOp(); 890 if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) || 891 (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)) 892 return true; 893 894 // Check that the operand is valid. 895 switch (Op) { 896 default: 897 return false; 898 case dwarf::DW_OP_LLVM_fragment: 899 // A fragment operator must appear at the end. 900 return I->get() + I->getSize() == E->get(); 901 case dwarf::DW_OP_stack_value: { 902 // Must be the last one or followed by a DW_OP_LLVM_fragment. 903 if (I->get() + I->getSize() == E->get()) 904 break; 905 auto J = I; 906 if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment) 907 return false; 908 break; 909 } 910 case dwarf::DW_OP_swap: { 911 // Must be more than one implicit element on the stack. 912 913 // FIXME: A better way to implement this would be to add a local variable 914 // that keeps track of the stack depth and introduce something like a 915 // DW_LLVM_OP_implicit_location as a placeholder for the location this 916 // DIExpression is attached to, or else pass the number of implicit stack 917 // elements into isValid. 918 if (getNumElements() == 1) 919 return false; 920 break; 921 } 922 case dwarf::DW_OP_LLVM_entry_value: { 923 // An entry value operator must appear at the beginning and the number of 924 // operations it cover can currently only be 1, because we support only 925 // entry values of a simple register location. One reason for this is that 926 // we currently can't calculate the size of the resulting DWARF block for 927 // other expressions. 928 return I->get() == expr_op_begin()->get() && I->getArg(0) == 1 && 929 getNumElements() == 2; 930 } 931 case dwarf::DW_OP_LLVM_convert: 932 case dwarf::DW_OP_LLVM_tag_offset: 933 case dwarf::DW_OP_constu: 934 case dwarf::DW_OP_plus_uconst: 935 case dwarf::DW_OP_plus: 936 case dwarf::DW_OP_minus: 937 case dwarf::DW_OP_mul: 938 case dwarf::DW_OP_div: 939 case dwarf::DW_OP_mod: 940 case dwarf::DW_OP_or: 941 case dwarf::DW_OP_and: 942 case dwarf::DW_OP_xor: 943 case dwarf::DW_OP_shl: 944 case dwarf::DW_OP_shr: 945 case dwarf::DW_OP_shra: 946 case dwarf::DW_OP_deref: 947 case dwarf::DW_OP_deref_size: 948 case dwarf::DW_OP_xderef: 949 case dwarf::DW_OP_lit0: 950 case dwarf::DW_OP_not: 951 case dwarf::DW_OP_dup: 952 case dwarf::DW_OP_regx: 953 case dwarf::DW_OP_bregx: 954 case dwarf::DW_OP_push_object_address: 955 break; 956 } 957 } 958 return true; 959 } 960 961 bool DIExpression::isImplicit() const { 962 if (!isValid()) 963 return false; 964 965 if (getNumElements() == 0) 966 return false; 967 968 for (const auto &It : expr_ops()) { 969 switch (It.getOp()) { 970 default: 971 break; 972 case dwarf::DW_OP_stack_value: 973 case dwarf::DW_OP_LLVM_tag_offset: 974 return true; 975 } 976 } 977 978 return false; 979 } 980 981 bool DIExpression::isComplex() const { 982 if (!isValid()) 983 return false; 984 985 if (getNumElements() == 0) 986 return false; 987 988 // If there are any elements other than fragment or tag_offset, then some 989 // kind of complex computation occurs. 990 for (const auto &It : expr_ops()) { 991 switch (It.getOp()) { 992 case dwarf::DW_OP_LLVM_tag_offset: 993 case dwarf::DW_OP_LLVM_fragment: 994 continue; 995 default: return true; 996 } 997 } 998 999 return false; 1000 } 1001 1002 Optional<DIExpression::FragmentInfo> 1003 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) { 1004 for (auto I = Start; I != End; ++I) 1005 if (I->getOp() == dwarf::DW_OP_LLVM_fragment) { 1006 DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)}; 1007 return Info; 1008 } 1009 return None; 1010 } 1011 1012 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops, 1013 int64_t Offset) { 1014 if (Offset > 0) { 1015 Ops.push_back(dwarf::DW_OP_plus_uconst); 1016 Ops.push_back(Offset); 1017 } else if (Offset < 0) { 1018 Ops.push_back(dwarf::DW_OP_constu); 1019 Ops.push_back(-Offset); 1020 Ops.push_back(dwarf::DW_OP_minus); 1021 } 1022 } 1023 1024 bool DIExpression::extractIfOffset(int64_t &Offset) const { 1025 if (getNumElements() == 0) { 1026 Offset = 0; 1027 return true; 1028 } 1029 1030 if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) { 1031 Offset = Elements[1]; 1032 return true; 1033 } 1034 1035 if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) { 1036 if (Elements[2] == dwarf::DW_OP_plus) { 1037 Offset = Elements[1]; 1038 return true; 1039 } 1040 if (Elements[2] == dwarf::DW_OP_minus) { 1041 Offset = -Elements[1]; 1042 return true; 1043 } 1044 } 1045 1046 return false; 1047 } 1048 1049 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr, 1050 unsigned &AddrClass) { 1051 // FIXME: This seems fragile. Nothing that verifies that these elements 1052 // actually map to ops and not operands. 1053 const unsigned PatternSize = 4; 1054 if (Expr->Elements.size() >= PatternSize && 1055 Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu && 1056 Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap && 1057 Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) { 1058 AddrClass = Expr->Elements[PatternSize - 3]; 1059 1060 if (Expr->Elements.size() == PatternSize) 1061 return nullptr; 1062 return DIExpression::get(Expr->getContext(), 1063 makeArrayRef(&*Expr->Elements.begin(), 1064 Expr->Elements.size() - PatternSize)); 1065 } 1066 return Expr; 1067 } 1068 1069 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags, 1070 int64_t Offset) { 1071 SmallVector<uint64_t, 8> Ops; 1072 if (Flags & DIExpression::DerefBefore) 1073 Ops.push_back(dwarf::DW_OP_deref); 1074 1075 appendOffset(Ops, Offset); 1076 if (Flags & DIExpression::DerefAfter) 1077 Ops.push_back(dwarf::DW_OP_deref); 1078 1079 bool StackValue = Flags & DIExpression::StackValue; 1080 bool EntryValue = Flags & DIExpression::EntryValue; 1081 1082 return prependOpcodes(Expr, Ops, StackValue, EntryValue); 1083 } 1084 1085 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr, 1086 SmallVectorImpl<uint64_t> &Ops, 1087 bool StackValue, 1088 bool EntryValue) { 1089 assert(Expr && "Can't prepend ops to this expression"); 1090 1091 if (EntryValue) { 1092 Ops.push_back(dwarf::DW_OP_LLVM_entry_value); 1093 // Add size info needed for entry value expression. 1094 // Add plus one for target register operand. 1095 Ops.push_back(Expr->getNumElements() + 1); 1096 } 1097 1098 // If there are no ops to prepend, do not even add the DW_OP_stack_value. 1099 if (Ops.empty()) 1100 StackValue = false; 1101 for (auto Op : Expr->expr_ops()) { 1102 // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment. 1103 if (StackValue) { 1104 if (Op.getOp() == dwarf::DW_OP_stack_value) 1105 StackValue = false; 1106 else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1107 Ops.push_back(dwarf::DW_OP_stack_value); 1108 StackValue = false; 1109 } 1110 } 1111 Op.appendToVector(Ops); 1112 } 1113 if (StackValue) 1114 Ops.push_back(dwarf::DW_OP_stack_value); 1115 return DIExpression::get(Expr->getContext(), Ops); 1116 } 1117 1118 DIExpression *DIExpression::append(const DIExpression *Expr, 1119 ArrayRef<uint64_t> Ops) { 1120 assert(Expr && !Ops.empty() && "Can't append ops to this expression"); 1121 1122 // Copy Expr's current op list. 1123 SmallVector<uint64_t, 16> NewOps; 1124 for (auto Op : Expr->expr_ops()) { 1125 // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}. 1126 if (Op.getOp() == dwarf::DW_OP_stack_value || 1127 Op.getOp() == dwarf::DW_OP_LLVM_fragment) { 1128 NewOps.append(Ops.begin(), Ops.end()); 1129 1130 // Ensure that the new opcodes are only appended once. 1131 Ops = None; 1132 } 1133 Op.appendToVector(NewOps); 1134 } 1135 1136 NewOps.append(Ops.begin(), Ops.end()); 1137 auto *result = DIExpression::get(Expr->getContext(), NewOps); 1138 assert(result->isValid() && "concatenated expression is not valid"); 1139 return result; 1140 } 1141 1142 DIExpression *DIExpression::appendToStack(const DIExpression *Expr, 1143 ArrayRef<uint64_t> Ops) { 1144 assert(Expr && !Ops.empty() && "Can't append ops to this expression"); 1145 assert(none_of(Ops, 1146 [](uint64_t Op) { 1147 return Op == dwarf::DW_OP_stack_value || 1148 Op == dwarf::DW_OP_LLVM_fragment; 1149 }) && 1150 "Can't append this op"); 1151 1152 // Append a DW_OP_deref after Expr's current op list if it's non-empty and 1153 // has no DW_OP_stack_value. 1154 // 1155 // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?. 1156 Optional<FragmentInfo> FI = Expr->getFragmentInfo(); 1157 unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0; 1158 ArrayRef<uint64_t> ExprOpsBeforeFragment = 1159 Expr->getElements().drop_back(DropUntilStackValue); 1160 bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) && 1161 (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value); 1162 bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty(); 1163 1164 // Append a DW_OP_deref after Expr's current op list if needed, then append 1165 // the new ops, and finally ensure that a single DW_OP_stack_value is present. 1166 SmallVector<uint64_t, 16> NewOps; 1167 if (NeedsDeref) 1168 NewOps.push_back(dwarf::DW_OP_deref); 1169 NewOps.append(Ops.begin(), Ops.end()); 1170 if (NeedsStackValue) 1171 NewOps.push_back(dwarf::DW_OP_stack_value); 1172 return DIExpression::append(Expr, NewOps); 1173 } 1174 1175 Optional<DIExpression *> DIExpression::createFragmentExpression( 1176 const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) { 1177 SmallVector<uint64_t, 8> Ops; 1178 // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment. 1179 if (Expr) { 1180 for (auto Op : Expr->expr_ops()) { 1181 switch (Op.getOp()) { 1182 default: break; 1183 case dwarf::DW_OP_shr: 1184 case dwarf::DW_OP_shra: 1185 case dwarf::DW_OP_shl: 1186 case dwarf::DW_OP_plus: 1187 case dwarf::DW_OP_plus_uconst: 1188 case dwarf::DW_OP_minus: 1189 // We can't safely split arithmetic or shift operations into multiple 1190 // fragments because we can't express carry-over between fragments. 1191 // 1192 // FIXME: We *could* preserve the lowest fragment of a constant offset 1193 // operation if the offset fits into SizeInBits. 1194 return None; 1195 case dwarf::DW_OP_LLVM_fragment: { 1196 // Make the new offset point into the existing fragment. 1197 uint64_t FragmentOffsetInBits = Op.getArg(0); 1198 uint64_t FragmentSizeInBits = Op.getArg(1); 1199 (void)FragmentSizeInBits; 1200 assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) && 1201 "new fragment outside of original fragment"); 1202 OffsetInBits += FragmentOffsetInBits; 1203 continue; 1204 } 1205 } 1206 Op.appendToVector(Ops); 1207 } 1208 } 1209 assert(Expr && "Unknown DIExpression"); 1210 Ops.push_back(dwarf::DW_OP_LLVM_fragment); 1211 Ops.push_back(OffsetInBits); 1212 Ops.push_back(SizeInBits); 1213 return DIExpression::get(Expr->getContext(), Ops); 1214 } 1215 1216 bool DIExpression::isConstant() const { 1217 // Recognize DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment Len Ofs)?. 1218 if (getNumElements() != 3 && getNumElements() != 6) 1219 return false; 1220 if (getElement(0) != dwarf::DW_OP_constu || 1221 getElement(2) != dwarf::DW_OP_stack_value) 1222 return false; 1223 if (getNumElements() == 6 && getElement(3) != dwarf::DW_OP_LLVM_fragment) 1224 return false; 1225 return true; 1226 } 1227 1228 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize, 1229 bool Signed) { 1230 dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned; 1231 DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK, 1232 dwarf::DW_OP_LLVM_convert, ToSize, TK}}; 1233 return Ops; 1234 } 1235 1236 DIExpression *DIExpression::appendExt(const DIExpression *Expr, 1237 unsigned FromSize, unsigned ToSize, 1238 bool Signed) { 1239 return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed)); 1240 } 1241 1242 DIGlobalVariableExpression * 1243 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable, 1244 Metadata *Expression, StorageType Storage, 1245 bool ShouldCreate) { 1246 DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression)); 1247 Metadata *Ops[] = {Variable, Expression}; 1248 DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops); 1249 } 1250 1251 DIObjCProperty *DIObjCProperty::getImpl( 1252 LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line, 1253 MDString *GetterName, MDString *SetterName, unsigned Attributes, 1254 Metadata *Type, StorageType Storage, bool ShouldCreate) { 1255 assert(isCanonical(Name) && "Expected canonical MDString"); 1256 assert(isCanonical(GetterName) && "Expected canonical MDString"); 1257 assert(isCanonical(SetterName) && "Expected canonical MDString"); 1258 DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName, 1259 SetterName, Attributes, Type)); 1260 Metadata *Ops[] = {Name, File, GetterName, SetterName, Type}; 1261 DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops); 1262 } 1263 1264 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag, 1265 Metadata *Scope, Metadata *Entity, 1266 Metadata *File, unsigned Line, 1267 MDString *Name, StorageType Storage, 1268 bool ShouldCreate) { 1269 assert(isCanonical(Name) && "Expected canonical MDString"); 1270 DEFINE_GETIMPL_LOOKUP(DIImportedEntity, 1271 (Tag, Scope, Entity, File, Line, Name)); 1272 Metadata *Ops[] = {Scope, Entity, Name, File}; 1273 DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops); 1274 } 1275 1276 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType, 1277 unsigned Line, MDString *Name, MDString *Value, 1278 StorageType Storage, bool ShouldCreate) { 1279 assert(isCanonical(Name) && "Expected canonical MDString"); 1280 DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value)); 1281 Metadata *Ops[] = { Name, Value }; 1282 DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops); 1283 } 1284 1285 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType, 1286 unsigned Line, Metadata *File, 1287 Metadata *Elements, StorageType Storage, 1288 bool ShouldCreate) { 1289 DEFINE_GETIMPL_LOOKUP(DIMacroFile, 1290 (MIType, Line, File, Elements)); 1291 Metadata *Ops[] = { File, Elements }; 1292 DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops); 1293 } 1294