1 //===- BTFDebug.cpp - BTF Generator ---------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains support for writing BTF debug info. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "BTFDebug.h" 15 #include "llvm/BinaryFormat/ELF.h" 16 #include "llvm/CodeGen/AsmPrinter.h" 17 #include "llvm/CodeGen/MachineModuleInfo.h" 18 #include "llvm/MC/MCContext.h" 19 #include "llvm/MC/MCObjectFileInfo.h" 20 #include "llvm/MC/MCSectionELF.h" 21 #include "llvm/MC/MCStreamer.h" 22 #include <fstream> 23 #include <sstream> 24 25 using namespace llvm; 26 27 static const char *BTFKindStr[] = { 28 #define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME, 29 #include "BTF.def" 30 }; 31 32 /// Emit a BTF common type. 33 void BTFTypeBase::emitType(MCStreamer &OS) { 34 OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) + 35 ")"); 36 OS.EmitIntValue(BTFType.NameOff, 4); 37 OS.AddComment("0x" + Twine::utohexstr(BTFType.Info)); 38 OS.EmitIntValue(BTFType.Info, 4); 39 OS.EmitIntValue(BTFType.Size, 4); 40 } 41 42 BTFTypeDerived::BTFTypeDerived(const DIDerivedType *DTy, unsigned Tag) 43 : DTy(DTy) { 44 switch (Tag) { 45 case dwarf::DW_TAG_pointer_type: 46 Kind = BTF::BTF_KIND_PTR; 47 break; 48 case dwarf::DW_TAG_const_type: 49 Kind = BTF::BTF_KIND_CONST; 50 break; 51 case dwarf::DW_TAG_volatile_type: 52 Kind = BTF::BTF_KIND_VOLATILE; 53 break; 54 case dwarf::DW_TAG_typedef: 55 Kind = BTF::BTF_KIND_TYPEDEF; 56 break; 57 case dwarf::DW_TAG_restrict_type: 58 Kind = BTF::BTF_KIND_RESTRICT; 59 break; 60 default: 61 llvm_unreachable("Unknown DIDerivedType Tag"); 62 } 63 BTFType.Info = Kind << 24; 64 } 65 66 void BTFTypeDerived::completeType(BTFDebug &BDebug) { 67 BTFType.NameOff = BDebug.addString(DTy->getName()); 68 69 // The base type for PTR/CONST/VOLATILE could be void. 70 const DIType *ResolvedType = DTy->getBaseType().resolve(); 71 if (!ResolvedType) { 72 assert((Kind == BTF::BTF_KIND_PTR || Kind == BTF::BTF_KIND_CONST || 73 Kind == BTF::BTF_KIND_VOLATILE) && 74 "Invalid null basetype"); 75 BTFType.Type = 0; 76 } else { 77 BTFType.Type = BDebug.getTypeId(ResolvedType); 78 } 79 } 80 81 void BTFTypeDerived::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); } 82 83 /// Represent a struct/union forward declaration. 84 BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion) : Name(Name) { 85 Kind = BTF::BTF_KIND_FWD; 86 BTFType.Info = IsUnion << 31 | Kind << 24; 87 BTFType.Type = 0; 88 } 89 90 void BTFTypeFwd::completeType(BTFDebug &BDebug) { 91 BTFType.NameOff = BDebug.addString(Name); 92 } 93 94 void BTFTypeFwd::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); } 95 96 BTFTypeInt::BTFTypeInt(uint32_t Encoding, uint32_t SizeInBits, 97 uint32_t OffsetInBits, StringRef TypeName) 98 : Name(TypeName) { 99 // Translate IR int encoding to BTF int encoding. 100 uint8_t BTFEncoding; 101 switch (Encoding) { 102 case dwarf::DW_ATE_boolean: 103 BTFEncoding = BTF::INT_BOOL; 104 break; 105 case dwarf::DW_ATE_signed: 106 case dwarf::DW_ATE_signed_char: 107 BTFEncoding = BTF::INT_SIGNED; 108 break; 109 case dwarf::DW_ATE_unsigned: 110 case dwarf::DW_ATE_unsigned_char: 111 BTFEncoding = 0; 112 break; 113 default: 114 llvm_unreachable("Unknown BTFTypeInt Encoding"); 115 } 116 117 Kind = BTF::BTF_KIND_INT; 118 BTFType.Info = Kind << 24; 119 BTFType.Size = roundupToBytes(SizeInBits); 120 IntVal = (BTFEncoding << 24) | OffsetInBits << 16 | SizeInBits; 121 } 122 123 void BTFTypeInt::completeType(BTFDebug &BDebug) { 124 BTFType.NameOff = BDebug.addString(Name); 125 } 126 127 void BTFTypeInt::emitType(MCStreamer &OS) { 128 BTFTypeBase::emitType(OS); 129 OS.AddComment("0x" + Twine::utohexstr(IntVal)); 130 OS.EmitIntValue(IntVal, 4); 131 } 132 133 BTFTypeEnum::BTFTypeEnum(const DICompositeType *ETy, uint32_t VLen) : ETy(ETy) { 134 Kind = BTF::BTF_KIND_ENUM; 135 BTFType.Info = Kind << 24 | VLen; 136 BTFType.Size = roundupToBytes(ETy->getSizeInBits()); 137 } 138 139 void BTFTypeEnum::completeType(BTFDebug &BDebug) { 140 BTFType.NameOff = BDebug.addString(ETy->getName()); 141 142 DINodeArray Elements = ETy->getElements(); 143 for (const auto Element : Elements) { 144 const auto *Enum = cast<DIEnumerator>(Element); 145 146 struct BTF::BTFEnum BTFEnum; 147 BTFEnum.NameOff = BDebug.addString(Enum->getName()); 148 // BTF enum value is 32bit, enforce it. 149 BTFEnum.Val = static_cast<uint32_t>(Enum->getValue()); 150 EnumValues.push_back(BTFEnum); 151 } 152 } 153 154 void BTFTypeEnum::emitType(MCStreamer &OS) { 155 BTFTypeBase::emitType(OS); 156 for (const auto &Enum : EnumValues) { 157 OS.EmitIntValue(Enum.NameOff, 4); 158 OS.EmitIntValue(Enum.Val, 4); 159 } 160 } 161 162 BTFTypeArray::BTFTypeArray(const DICompositeType *ATy) : ATy(ATy) { 163 Kind = BTF::BTF_KIND_ARRAY; 164 BTFType.Info = Kind << 24; 165 } 166 167 /// Represent a BTF array. BTF does not record array dimensions, 168 /// so conceptually a BTF array is a one-dimensional array. 169 void BTFTypeArray::completeType(BTFDebug &BDebug) { 170 BTFType.NameOff = BDebug.addString(ATy->getName()); 171 BTFType.Size = 0; 172 173 auto *BaseType = ATy->getBaseType().resolve(); 174 ArrayInfo.ElemType = BDebug.getTypeId(BaseType); 175 176 // The IR does not really have a type for the index. 177 // A special type for array index should have been 178 // created during initial type traversal. Just 179 // retrieve that type id. 180 ArrayInfo.IndexType = BDebug.getArrayIndexTypeId(); 181 182 // Get the number of array elements. 183 // If the array size is 0, set the number of elements as 0. 184 // Otherwise, recursively traverse the base types to 185 // find the element size. The number of elements is 186 // the totoal array size in bits divided by 187 // element size in bits. 188 uint64_t ArraySizeInBits = ATy->getSizeInBits(); 189 if (!ArraySizeInBits) { 190 ArrayInfo.Nelems = 0; 191 } else { 192 uint32_t BaseTypeSize = BaseType->getSizeInBits(); 193 while (!BaseTypeSize) { 194 const auto *DDTy = cast<DIDerivedType>(BaseType); 195 BaseType = DDTy->getBaseType().resolve(); 196 assert(BaseType); 197 BaseTypeSize = BaseType->getSizeInBits(); 198 } 199 ArrayInfo.Nelems = ATy->getSizeInBits() / BaseTypeSize; 200 } 201 } 202 203 void BTFTypeArray::emitType(MCStreamer &OS) { 204 BTFTypeBase::emitType(OS); 205 OS.EmitIntValue(ArrayInfo.ElemType, 4); 206 OS.EmitIntValue(ArrayInfo.IndexType, 4); 207 OS.EmitIntValue(ArrayInfo.Nelems, 4); 208 } 209 210 /// Represent either a struct or a union. 211 BTFTypeStruct::BTFTypeStruct(const DICompositeType *STy, bool IsStruct, 212 bool HasBitField, uint32_t Vlen) 213 : STy(STy), HasBitField(HasBitField) { 214 Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION; 215 BTFType.Size = roundupToBytes(STy->getSizeInBits()); 216 BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen; 217 } 218 219 void BTFTypeStruct::completeType(BTFDebug &BDebug) { 220 BTFType.NameOff = BDebug.addString(STy->getName()); 221 222 // Add struct/union members. 223 const DINodeArray Elements = STy->getElements(); 224 for (const auto *Element : Elements) { 225 struct BTF::BTFMember BTFMember; 226 const auto *DDTy = cast<DIDerivedType>(Element); 227 228 BTFMember.NameOff = BDebug.addString(DDTy->getName()); 229 if (HasBitField) { 230 uint8_t BitFieldSize = DDTy->isBitField() ? DDTy->getSizeInBits() : 0; 231 BTFMember.Offset = BitFieldSize << 24 | DDTy->getOffsetInBits(); 232 } else { 233 BTFMember.Offset = DDTy->getOffsetInBits(); 234 } 235 BTFMember.Type = BDebug.getTypeId(DDTy->getBaseType().resolve()); 236 Members.push_back(BTFMember); 237 } 238 } 239 240 void BTFTypeStruct::emitType(MCStreamer &OS) { 241 BTFTypeBase::emitType(OS); 242 for (const auto &Member : Members) { 243 OS.EmitIntValue(Member.NameOff, 4); 244 OS.EmitIntValue(Member.Type, 4); 245 OS.AddComment("0x" + Twine::utohexstr(Member.Offset)); 246 OS.EmitIntValue(Member.Offset, 4); 247 } 248 } 249 250 /// The Func kind represents both subprogram and pointee of function 251 /// pointers. If the FuncName is empty, it represents a pointee of function 252 /// pointer. Otherwise, it represents a subprogram. The func arg names 253 /// are empty for pointee of function pointer case, and are valid names 254 /// for subprogram. 255 BTFTypeFuncProto::BTFTypeFuncProto( 256 const DISubroutineType *STy, uint32_t VLen, 257 const std::unordered_map<uint32_t, StringRef> &FuncArgNames) 258 : STy(STy), FuncArgNames(FuncArgNames) { 259 Kind = BTF::BTF_KIND_FUNC_PROTO; 260 BTFType.Info = (Kind << 24) | VLen; 261 } 262 263 void BTFTypeFuncProto::completeType(BTFDebug &BDebug) { 264 DITypeRefArray Elements = STy->getTypeArray(); 265 auto RetType = Elements[0].resolve(); 266 BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0; 267 BTFType.NameOff = 0; 268 269 // For null parameter which is typically the last one 270 // to represent the vararg, encode the NameOff/Type to be 0. 271 for (unsigned I = 1, N = Elements.size(); I < N; ++I) { 272 struct BTF::BTFParam Param; 273 auto Element = Elements[I].resolve(); 274 if (Element) { 275 Param.NameOff = BDebug.addString(FuncArgNames[I]); 276 Param.Type = BDebug.getTypeId(Element); 277 } else { 278 Param.NameOff = 0; 279 Param.Type = 0; 280 } 281 Parameters.push_back(Param); 282 } 283 } 284 285 void BTFTypeFuncProto::emitType(MCStreamer &OS) { 286 BTFTypeBase::emitType(OS); 287 for (const auto &Param : Parameters) { 288 OS.EmitIntValue(Param.NameOff, 4); 289 OS.EmitIntValue(Param.Type, 4); 290 } 291 } 292 293 BTFTypeFunc::BTFTypeFunc(StringRef FuncName, uint32_t ProtoTypeId) 294 : Name(FuncName) { 295 Kind = BTF::BTF_KIND_FUNC; 296 BTFType.Info = Kind << 24; 297 BTFType.Type = ProtoTypeId; 298 } 299 300 void BTFTypeFunc::completeType(BTFDebug &BDebug) { 301 BTFType.NameOff = BDebug.addString(Name); 302 } 303 304 void BTFTypeFunc::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); } 305 306 uint32_t BTFStringTable::addString(StringRef S) { 307 // Check whether the string already exists. 308 for (auto &OffsetM : OffsetToIdMap) { 309 if (Table[OffsetM.second] == S) 310 return OffsetM.first; 311 } 312 // Not find, add to the string table. 313 uint32_t Offset = Size; 314 OffsetToIdMap[Offset] = Table.size(); 315 Table.push_back(S); 316 Size += S.size() + 1; 317 return Offset; 318 } 319 320 BTFDebug::BTFDebug(AsmPrinter *AP) 321 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false), 322 LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0) { 323 addString("\0"); 324 } 325 326 void BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry, 327 const DIType *Ty) { 328 TypeEntry->setId(TypeEntries.size() + 1); 329 DIToIdMap[Ty] = TypeEntry->getId(); 330 TypeEntries.push_back(std::move(TypeEntry)); 331 } 332 333 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) { 334 TypeEntry->setId(TypeEntries.size() + 1); 335 uint32_t Id = TypeEntry->getId(); 336 TypeEntries.push_back(std::move(TypeEntry)); 337 return Id; 338 } 339 340 void BTFDebug::visitBasicType(const DIBasicType *BTy) { 341 // Only int types are supported in BTF. 342 uint32_t Encoding = BTy->getEncoding(); 343 if (Encoding != dwarf::DW_ATE_boolean && Encoding != dwarf::DW_ATE_signed && 344 Encoding != dwarf::DW_ATE_signed_char && 345 Encoding != dwarf::DW_ATE_unsigned && 346 Encoding != dwarf::DW_ATE_unsigned_char) 347 return; 348 349 // Create a BTF type instance for this DIBasicType and put it into 350 // DIToIdMap for cross-type reference check. 351 auto TypeEntry = llvm::make_unique<BTFTypeInt>( 352 Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName()); 353 addType(std::move(TypeEntry), BTy); 354 } 355 356 /// Handle subprogram or subroutine types. 357 void BTFDebug::visitSubroutineType( 358 const DISubroutineType *STy, bool ForSubprog, 359 const std::unordered_map<uint32_t, StringRef> &FuncArgNames, 360 uint32_t &TypeId) { 361 DITypeRefArray Elements = STy->getTypeArray(); 362 uint32_t VLen = Elements.size() - 1; 363 if (VLen > BTF::MAX_VLEN) 364 return; 365 366 // Subprogram has a valid non-zero-length name, and the pointee of 367 // a function pointer has an empty name. The subprogram type will 368 // not be added to DIToIdMap as it should not be referenced by 369 // any other types. 370 auto TypeEntry = llvm::make_unique<BTFTypeFuncProto>(STy, VLen, FuncArgNames); 371 if (ForSubprog) 372 TypeId = addType(std::move(TypeEntry)); // For subprogram 373 else 374 addType(std::move(TypeEntry), STy); // For func ptr 375 376 // Visit return type and func arg types. 377 for (const auto Element : Elements) { 378 visitTypeEntry(Element.resolve()); 379 } 380 } 381 382 /// Handle structure/union types. 383 void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct) { 384 const DINodeArray Elements = CTy->getElements(); 385 uint32_t VLen = Elements.size(); 386 if (VLen > BTF::MAX_VLEN) 387 return; 388 389 // Check whether we have any bitfield members or not 390 bool HasBitField = false; 391 for (const auto *Element : Elements) { 392 auto E = cast<DIDerivedType>(Element); 393 if (E->isBitField()) { 394 HasBitField = true; 395 break; 396 } 397 } 398 399 auto TypeEntry = 400 llvm::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen); 401 addType(std::move(TypeEntry), CTy); 402 403 // Visit all struct members. 404 for (const auto *Element : Elements) 405 visitTypeEntry(cast<DIDerivedType>(Element)); 406 } 407 408 void BTFDebug::visitArrayType(const DICompositeType *CTy) { 409 auto TypeEntry = llvm::make_unique<BTFTypeArray>(CTy); 410 addType(std::move(TypeEntry), CTy); 411 412 // The IR does not have a type for array index while BTF wants one. 413 // So create an array index type if there is none. 414 if (!ArrayIndexTypeId) { 415 auto TypeEntry = llvm::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32, 416 0, "__ARRAY_SIZE_TYPE__"); 417 ArrayIndexTypeId = addType(std::move(TypeEntry)); 418 } 419 420 // Visit array element type. 421 visitTypeEntry(CTy->getBaseType().resolve()); 422 } 423 424 void BTFDebug::visitEnumType(const DICompositeType *CTy) { 425 DINodeArray Elements = CTy->getElements(); 426 uint32_t VLen = Elements.size(); 427 if (VLen > BTF::MAX_VLEN) 428 return; 429 430 auto TypeEntry = llvm::make_unique<BTFTypeEnum>(CTy, VLen); 431 addType(std::move(TypeEntry), CTy); 432 // No need to visit base type as BTF does not encode it. 433 } 434 435 /// Handle structure/union forward declarations. 436 void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion) { 437 auto TypeEntry = llvm::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion); 438 addType(std::move(TypeEntry), CTy); 439 } 440 441 /// Handle structure, union, array and enumeration types. 442 void BTFDebug::visitCompositeType(const DICompositeType *CTy) { 443 auto Tag = CTy->getTag(); 444 if (Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) { 445 // Handle forward declaration differently as it does not have members. 446 if (CTy->isForwardDecl()) 447 visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type); 448 else 449 visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type); 450 } else if (Tag == dwarf::DW_TAG_array_type) 451 visitArrayType(CTy); 452 else if (Tag == dwarf::DW_TAG_enumeration_type) 453 visitEnumType(CTy); 454 } 455 456 /// Handle pointer, typedef, const, volatile, restrict and member types. 457 void BTFDebug::visitDerivedType(const DIDerivedType *DTy) { 458 unsigned Tag = DTy->getTag(); 459 460 if (Tag == dwarf::DW_TAG_pointer_type || Tag == dwarf::DW_TAG_typedef || 461 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type || 462 Tag == dwarf::DW_TAG_restrict_type) { 463 auto TypeEntry = llvm::make_unique<BTFTypeDerived>(DTy, Tag); 464 addType(std::move(TypeEntry), DTy); 465 } else if (Tag != dwarf::DW_TAG_member) { 466 return; 467 } 468 469 // Visit base type of pointer, typedef, const, volatile, restrict or 470 // struct/union member. 471 visitTypeEntry(DTy->getBaseType().resolve()); 472 } 473 474 void BTFDebug::visitTypeEntry(const DIType *Ty) { 475 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) 476 return; 477 478 uint32_t TypeId; 479 if (const auto *BTy = dyn_cast<DIBasicType>(Ty)) 480 visitBasicType(BTy); 481 else if (const auto *STy = dyn_cast<DISubroutineType>(Ty)) 482 visitSubroutineType(STy, false, std::unordered_map<uint32_t, StringRef>(), 483 TypeId); 484 else if (const auto *CTy = dyn_cast<DICompositeType>(Ty)) 485 visitCompositeType(CTy); 486 else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty)) 487 visitDerivedType(DTy); 488 else 489 llvm_unreachable("Unknown DIType"); 490 } 491 492 /// Read file contents from the actual file or from the source 493 std::string BTFDebug::populateFileContent(const DISubprogram *SP) { 494 auto File = SP->getFile(); 495 std::string FileName; 496 497 if (File->getDirectory().size()) 498 FileName = File->getDirectory().str() + "/" + File->getFilename().str(); 499 else 500 FileName = File->getFilename(); 501 502 // No need to populate the contends if it has been populated! 503 if (FileContent.find(FileName) != FileContent.end()) 504 return FileName; 505 506 std::vector<std::string> Content; 507 std::string Line; 508 Content.push_back(Line); // Line 0 for empty string 509 510 auto Source = File->getSource(); 511 if (Source) { 512 std::istringstream InputString(Source.getValue()); 513 while (std::getline(InputString, Line)) 514 Content.push_back(Line); 515 } else { 516 std::ifstream InputFile(FileName); 517 while (std::getline(InputFile, Line)) 518 Content.push_back(Line); 519 } 520 521 FileContent[FileName] = Content; 522 return FileName; 523 } 524 525 void BTFDebug::constructLineInfo(const DISubprogram *SP, MCSymbol *Label, 526 uint32_t Line, uint32_t Column) { 527 std::string FileName = populateFileContent(SP); 528 BTFLineInfo LineInfo; 529 530 LineInfo.Label = Label; 531 LineInfo.FileNameOff = addString(FileName); 532 // If file content is not available, let LineOff = 0. 533 if (Line < FileContent[FileName].size()) 534 LineInfo.LineOff = addString(FileContent[FileName][Line]); 535 else 536 LineInfo.LineOff = 0; 537 LineInfo.LineNum = Line; 538 LineInfo.ColumnNum = Column; 539 LineInfoTable[SecNameOff].push_back(LineInfo); 540 } 541 542 void BTFDebug::emitCommonHeader() { 543 OS.AddComment("0x" + Twine::utohexstr(BTF::MAGIC)); 544 OS.EmitIntValue(BTF::MAGIC, 2); 545 OS.EmitIntValue(BTF::VERSION, 1); 546 OS.EmitIntValue(0, 1); 547 } 548 549 void BTFDebug::emitBTFSection() { 550 MCContext &Ctx = OS.getContext(); 551 OS.SwitchSection(Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0)); 552 553 // Emit header. 554 emitCommonHeader(); 555 OS.EmitIntValue(BTF::HeaderSize, 4); 556 557 uint32_t TypeLen = 0, StrLen; 558 for (const auto &TypeEntry : TypeEntries) 559 TypeLen += TypeEntry->getSize(); 560 StrLen = StringTable.getSize(); 561 562 OS.EmitIntValue(0, 4); 563 OS.EmitIntValue(TypeLen, 4); 564 OS.EmitIntValue(TypeLen, 4); 565 OS.EmitIntValue(StrLen, 4); 566 567 // Emit type table. 568 for (const auto &TypeEntry : TypeEntries) 569 TypeEntry->emitType(OS); 570 571 // Emit string table. 572 uint32_t StringOffset = 0; 573 for (const auto &S : StringTable.getTable()) { 574 OS.AddComment("string offset=" + std::to_string(StringOffset)); 575 OS.EmitBytes(S); 576 OS.EmitBytes(StringRef("\0", 1)); 577 StringOffset += S.size() + 1; 578 } 579 } 580 581 void BTFDebug::emitBTFExtSection() { 582 MCContext &Ctx = OS.getContext(); 583 OS.SwitchSection(Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0)); 584 585 // Emit header. 586 emitCommonHeader(); 587 OS.EmitIntValue(BTF::ExtHeaderSize, 4); 588 589 // Account for FuncInfo/LineInfo record size as well. 590 uint32_t FuncLen = 4, LineLen = 4; 591 for (const auto &FuncSec : FuncInfoTable) { 592 FuncLen += BTF::SecFuncInfoSize; 593 FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize; 594 } 595 for (const auto &LineSec : LineInfoTable) { 596 LineLen += BTF::SecLineInfoSize; 597 LineLen += LineSec.second.size() * BTF::BPFLineInfoSize; 598 } 599 600 OS.EmitIntValue(0, 4); 601 OS.EmitIntValue(FuncLen, 4); 602 OS.EmitIntValue(FuncLen, 4); 603 OS.EmitIntValue(LineLen, 4); 604 605 // Emit func_info table. 606 OS.AddComment("FuncInfo"); 607 OS.EmitIntValue(BTF::BPFFuncInfoSize, 4); 608 for (const auto &FuncSec : FuncInfoTable) { 609 OS.AddComment("FuncInfo section string offset=" + 610 std::to_string(FuncSec.first)); 611 OS.EmitIntValue(FuncSec.first, 4); 612 OS.EmitIntValue(FuncSec.second.size(), 4); 613 for (const auto &FuncInfo : FuncSec.second) { 614 Asm->EmitLabelReference(FuncInfo.Label, 4); 615 OS.EmitIntValue(FuncInfo.TypeId, 4); 616 } 617 } 618 619 // Emit line_info table. 620 OS.AddComment("LineInfo"); 621 OS.EmitIntValue(BTF::BPFLineInfoSize, 4); 622 for (const auto &LineSec : LineInfoTable) { 623 OS.AddComment("LineInfo section string offset=" + 624 std::to_string(LineSec.first)); 625 OS.EmitIntValue(LineSec.first, 4); 626 OS.EmitIntValue(LineSec.second.size(), 4); 627 for (const auto &LineInfo : LineSec.second) { 628 Asm->EmitLabelReference(LineInfo.Label, 4); 629 OS.EmitIntValue(LineInfo.FileNameOff, 4); 630 OS.EmitIntValue(LineInfo.LineOff, 4); 631 OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " + 632 std::to_string(LineInfo.ColumnNum)); 633 OS.EmitIntValue(LineInfo.LineNum << 10 | LineInfo.ColumnNum, 4); 634 } 635 } 636 } 637 638 void BTFDebug::beginFunctionImpl(const MachineFunction *MF) { 639 auto *SP = MF->getFunction().getSubprogram(); 640 auto *Unit = SP->getUnit(); 641 642 if (Unit->getEmissionKind() == DICompileUnit::NoDebug) { 643 SkipInstruction = true; 644 return; 645 } 646 SkipInstruction = false; 647 648 // Collect all types locally referenced in this function. 649 // Use RetainedNodes so we can collect all argument names 650 // even if the argument is not used. 651 std::unordered_map<uint32_t, StringRef> FuncArgNames; 652 for (const DINode *DN : SP->getRetainedNodes()) { 653 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) { 654 visitTypeEntry(DV->getType().resolve()); 655 656 // Collect function arguments for subprogram func type. 657 uint32_t Arg = DV->getArg(); 658 if (Arg) 659 FuncArgNames[Arg] = DV->getName(); 660 } 661 } 662 663 // Construct subprogram func proto type. 664 uint32_t ProtoTypeId; 665 visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId); 666 667 // Construct subprogram func type 668 auto FuncTypeEntry = 669 llvm::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId); 670 uint32_t FuncTypeId = addType(std::move(FuncTypeEntry)); 671 672 // Construct funcinfo and the first lineinfo for the function. 673 MCSymbol *FuncLabel = Asm->getFunctionBegin(); 674 BTFFuncInfo FuncInfo; 675 FuncInfo.Label = FuncLabel; 676 FuncInfo.TypeId = FuncTypeId; 677 if (FuncLabel->isInSection()) { 678 MCSection &Section = FuncLabel->getSection(); 679 const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section); 680 assert(SectionELF && "Null section for Function Label"); 681 SecNameOff = addString(SectionELF->getSectionName()); 682 } else { 683 SecNameOff = addString(".text"); 684 } 685 FuncInfoTable[SecNameOff].push_back(FuncInfo); 686 } 687 688 void BTFDebug::endFunctionImpl(const MachineFunction *MF) { 689 SkipInstruction = false; 690 LineInfoGenerated = false; 691 SecNameOff = 0; 692 } 693 694 void BTFDebug::beginInstruction(const MachineInstr *MI) { 695 DebugHandlerBase::beginInstruction(MI); 696 697 if (SkipInstruction || MI->isMetaInstruction() || 698 MI->getFlag(MachineInstr::FrameSetup)) 699 return; 700 701 if (MI->isInlineAsm()) { 702 // Count the number of register definitions to find the asm string. 703 unsigned NumDefs = 0; 704 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef(); 705 ++NumDefs) 706 ; 707 708 // Skip this inline asm instruction if the asmstr is empty. 709 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName(); 710 if (AsmStr[0] == 0) 711 return; 712 } 713 714 // Skip this instruction if no DebugLoc or the DebugLoc 715 // is the same as the previous instruction. 716 const DebugLoc &DL = MI->getDebugLoc(); 717 if (!DL || PrevInstLoc == DL) { 718 // This instruction will be skipped, no LineInfo has 719 // been generated, construct one based on function signature. 720 if (LineInfoGenerated == false) { 721 auto *S = MI->getMF()->getFunction().getSubprogram(); 722 MCSymbol *FuncLabel = Asm->getFunctionBegin(); 723 constructLineInfo(S, FuncLabel, S->getLine(), 0); 724 LineInfoGenerated = true; 725 } 726 727 return; 728 } 729 730 // Create a temporary label to remember the insn for lineinfo. 731 MCSymbol *LineSym = OS.getContext().createTempSymbol(); 732 OS.EmitLabel(LineSym); 733 734 // Construct the lineinfo. 735 auto SP = DL.get()->getScope()->getSubprogram(); 736 constructLineInfo(SP, LineSym, DL.getLine(), DL.getCol()); 737 738 LineInfoGenerated = true; 739 PrevInstLoc = DL; 740 } 741 742 void BTFDebug::endModule() { 743 // Collect all types referenced by globals. 744 const Module *M = MMI->getModule(); 745 for (const DICompileUnit *CUNode : M->debug_compile_units()) { 746 for (const auto *GVE : CUNode->getGlobalVariables()) { 747 DIGlobalVariable *GV = GVE->getVariable(); 748 visitTypeEntry(GV->getType().resolve()); 749 } 750 } 751 752 // Complete BTF type cross refereences. 753 for (const auto &TypeEntry : TypeEntries) 754 TypeEntry->completeType(*this); 755 756 // Emit BTF sections. 757 emitBTFSection(); 758 emitBTFExtSection(); 759 } 760