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