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