1 //===- BTFDebug.cpp - BTF Generator ---------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains support for writing BTF debug info.
11 //===----------------------------------------------------------------------===//
16 #include "MCTargetDesc/BPFMCTargetDesc.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCSectionELF.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/Support/LineIterator.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Target/TargetLoweringObjectFile.h"
31 static const char *BTFKindStr[] = {
32 #define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
36 /// Emit a BTF common type.
37 void BTFTypeBase::emitType(MCStreamer &OS) {
38 OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
40 OS.emitInt32(BTFType.NameOff);
41 OS.AddComment("0x" + Twine::utohexstr(BTFType.Info));
42 OS.emitInt32(BTFType.Info);
43 OS.emitInt32(BTFType.Size);
46 BTFTypeDerived::BTFTypeDerived(const DIDerivedType *DTy, unsigned Tag,
48 : DTy(DTy), NeedsFixup(NeedsFixup), Name(DTy->getName()) {
50 case dwarf::DW_TAG_pointer_type:
51 Kind = BTF::BTF_KIND_PTR;
53 case dwarf::DW_TAG_const_type:
54 Kind = BTF::BTF_KIND_CONST;
56 case dwarf::DW_TAG_volatile_type:
57 Kind = BTF::BTF_KIND_VOLATILE;
59 case dwarf::DW_TAG_typedef:
60 Kind = BTF::BTF_KIND_TYPEDEF;
62 case dwarf::DW_TAG_restrict_type:
63 Kind = BTF::BTF_KIND_RESTRICT;
66 llvm_unreachable("Unknown DIDerivedType Tag");
68 BTFType.Info = Kind << 24;
71 /// Used by DW_TAG_pointer_type only.
72 BTFTypeDerived::BTFTypeDerived(unsigned NextTypeId, unsigned Tag,
74 : DTy(nullptr), NeedsFixup(false), Name(Name) {
75 Kind = BTF::BTF_KIND_PTR;
76 BTFType.Info = Kind << 24;
77 BTFType.Type = NextTypeId;
80 void BTFTypeDerived::completeType(BTFDebug &BDebug) {
85 BTFType.NameOff = BDebug.addString(Name);
87 if (NeedsFixup || !DTy)
90 // The base type for PTR/CONST/VOLATILE could be void.
91 const DIType *ResolvedType = DTy->getBaseType();
93 assert((Kind == BTF::BTF_KIND_PTR || Kind == BTF::BTF_KIND_CONST ||
94 Kind == BTF::BTF_KIND_VOLATILE) &&
95 "Invalid null basetype");
98 BTFType.Type = BDebug.getTypeId(ResolvedType);
102 void BTFTypeDerived::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
104 void BTFTypeDerived::setPointeeType(uint32_t PointeeType) {
105 BTFType.Type = PointeeType;
108 /// Represent a struct/union forward declaration.
109 BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion) : Name(Name) {
110 Kind = BTF::BTF_KIND_FWD;
111 BTFType.Info = IsUnion << 31 | Kind << 24;
115 void BTFTypeFwd::completeType(BTFDebug &BDebug) {
120 BTFType.NameOff = BDebug.addString(Name);
123 void BTFTypeFwd::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
125 BTFTypeInt::BTFTypeInt(uint32_t Encoding, uint32_t SizeInBits,
126 uint32_t OffsetInBits, StringRef TypeName)
128 // Translate IR int encoding to BTF int encoding.
131 case dwarf::DW_ATE_boolean:
132 BTFEncoding = BTF::INT_BOOL;
134 case dwarf::DW_ATE_signed:
135 case dwarf::DW_ATE_signed_char:
136 BTFEncoding = BTF::INT_SIGNED;
138 case dwarf::DW_ATE_unsigned:
139 case dwarf::DW_ATE_unsigned_char:
143 llvm_unreachable("Unknown BTFTypeInt Encoding");
146 Kind = BTF::BTF_KIND_INT;
147 BTFType.Info = Kind << 24;
148 BTFType.Size = roundupToBytes(SizeInBits);
149 IntVal = (BTFEncoding << 24) | OffsetInBits << 16 | SizeInBits;
152 void BTFTypeInt::completeType(BTFDebug &BDebug) {
157 BTFType.NameOff = BDebug.addString(Name);
160 void BTFTypeInt::emitType(MCStreamer &OS) {
161 BTFTypeBase::emitType(OS);
162 OS.AddComment("0x" + Twine::utohexstr(IntVal));
163 OS.emitInt32(IntVal);
166 BTFTypeEnum::BTFTypeEnum(const DICompositeType *ETy, uint32_t VLen,
167 bool IsSigned) : ETy(ETy) {
168 Kind = BTF::BTF_KIND_ENUM;
169 BTFType.Info = IsSigned << 31 | Kind << 24 | VLen;
170 BTFType.Size = roundupToBytes(ETy->getSizeInBits());
173 void BTFTypeEnum::completeType(BTFDebug &BDebug) {
178 BTFType.NameOff = BDebug.addString(ETy->getName());
180 DINodeArray Elements = ETy->getElements();
181 for (const auto Element : Elements) {
182 const auto *Enum = cast<DIEnumerator>(Element);
184 struct BTF::BTFEnum BTFEnum;
185 BTFEnum.NameOff = BDebug.addString(Enum->getName());
186 // BTF enum value is 32bit, enforce it.
188 if (Enum->isUnsigned())
189 Value = static_cast<uint32_t>(Enum->getValue().getZExtValue());
191 Value = static_cast<uint32_t>(Enum->getValue().getSExtValue());
193 EnumValues.push_back(BTFEnum);
197 void BTFTypeEnum::emitType(MCStreamer &OS) {
198 BTFTypeBase::emitType(OS);
199 for (const auto &Enum : EnumValues) {
200 OS.emitInt32(Enum.NameOff);
201 OS.emitInt32(Enum.Val);
205 BTFTypeEnum64::BTFTypeEnum64(const DICompositeType *ETy, uint32_t VLen,
206 bool IsSigned) : ETy(ETy) {
207 Kind = BTF::BTF_KIND_ENUM64;
208 BTFType.Info = IsSigned << 31 | Kind << 24 | VLen;
209 BTFType.Size = roundupToBytes(ETy->getSizeInBits());
212 void BTFTypeEnum64::completeType(BTFDebug &BDebug) {
217 BTFType.NameOff = BDebug.addString(ETy->getName());
219 DINodeArray Elements = ETy->getElements();
220 for (const auto Element : Elements) {
221 const auto *Enum = cast<DIEnumerator>(Element);
223 struct BTF::BTFEnum64 BTFEnum;
224 BTFEnum.NameOff = BDebug.addString(Enum->getName());
226 if (Enum->isUnsigned())
227 Value = static_cast<uint64_t>(Enum->getValue().getZExtValue());
229 Value = static_cast<uint64_t>(Enum->getValue().getSExtValue());
230 BTFEnum.Val_Lo32 = Value;
231 BTFEnum.Val_Hi32 = Value >> 32;
232 EnumValues.push_back(BTFEnum);
236 void BTFTypeEnum64::emitType(MCStreamer &OS) {
237 BTFTypeBase::emitType(OS);
238 for (const auto &Enum : EnumValues) {
239 OS.emitInt32(Enum.NameOff);
240 OS.AddComment("0x" + Twine::utohexstr(Enum.Val_Lo32));
241 OS.emitInt32(Enum.Val_Lo32);
242 OS.AddComment("0x" + Twine::utohexstr(Enum.Val_Hi32));
243 OS.emitInt32(Enum.Val_Hi32);
247 BTFTypeArray::BTFTypeArray(uint32_t ElemTypeId, uint32_t NumElems) {
248 Kind = BTF::BTF_KIND_ARRAY;
250 BTFType.Info = Kind << 24;
253 ArrayInfo.ElemType = ElemTypeId;
254 ArrayInfo.Nelems = NumElems;
257 /// Represent a BTF array.
258 void BTFTypeArray::completeType(BTFDebug &BDebug) {
263 // The IR does not really have a type for the index.
264 // A special type for array index should have been
265 // created during initial type traversal. Just
266 // retrieve that type id.
267 ArrayInfo.IndexType = BDebug.getArrayIndexTypeId();
270 void BTFTypeArray::emitType(MCStreamer &OS) {
271 BTFTypeBase::emitType(OS);
272 OS.emitInt32(ArrayInfo.ElemType);
273 OS.emitInt32(ArrayInfo.IndexType);
274 OS.emitInt32(ArrayInfo.Nelems);
277 /// Represent either a struct or a union.
278 BTFTypeStruct::BTFTypeStruct(const DICompositeType *STy, bool IsStruct,
279 bool HasBitField, uint32_t Vlen)
280 : STy(STy), HasBitField(HasBitField) {
281 Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION;
282 BTFType.Size = roundupToBytes(STy->getSizeInBits());
283 BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen;
286 void BTFTypeStruct::completeType(BTFDebug &BDebug) {
291 BTFType.NameOff = BDebug.addString(STy->getName());
293 // Add struct/union members.
294 const DINodeArray Elements = STy->getElements();
295 for (const auto *Element : Elements) {
296 struct BTF::BTFMember BTFMember;
297 const auto *DDTy = cast<DIDerivedType>(Element);
299 BTFMember.NameOff = BDebug.addString(DDTy->getName());
301 uint8_t BitFieldSize = DDTy->isBitField() ? DDTy->getSizeInBits() : 0;
302 BTFMember.Offset = BitFieldSize << 24 | DDTy->getOffsetInBits();
304 BTFMember.Offset = DDTy->getOffsetInBits();
306 const auto *BaseTy = DDTy->getBaseType();
307 BTFMember.Type = BDebug.getTypeId(BaseTy);
308 Members.push_back(BTFMember);
312 void BTFTypeStruct::emitType(MCStreamer &OS) {
313 BTFTypeBase::emitType(OS);
314 for (const auto &Member : Members) {
315 OS.emitInt32(Member.NameOff);
316 OS.emitInt32(Member.Type);
317 OS.AddComment("0x" + Twine::utohexstr(Member.Offset));
318 OS.emitInt32(Member.Offset);
322 std::string BTFTypeStruct::getName() { return std::string(STy->getName()); }
324 /// The Func kind represents both subprogram and pointee of function
325 /// pointers. If the FuncName is empty, it represents a pointee of function
326 /// pointer. Otherwise, it represents a subprogram. The func arg names
327 /// are empty for pointee of function pointer case, and are valid names
329 BTFTypeFuncProto::BTFTypeFuncProto(
330 const DISubroutineType *STy, uint32_t VLen,
331 const std::unordered_map<uint32_t, StringRef> &FuncArgNames)
332 : STy(STy), FuncArgNames(FuncArgNames) {
333 Kind = BTF::BTF_KIND_FUNC_PROTO;
334 BTFType.Info = (Kind << 24) | VLen;
337 void BTFTypeFuncProto::completeType(BTFDebug &BDebug) {
342 DITypeRefArray Elements = STy->getTypeArray();
343 auto RetType = Elements[0];
344 BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
347 // For null parameter which is typically the last one
348 // to represent the vararg, encode the NameOff/Type to be 0.
349 for (unsigned I = 1, N = Elements.size(); I < N; ++I) {
350 struct BTF::BTFParam Param;
351 auto Element = Elements[I];
353 Param.NameOff = BDebug.addString(FuncArgNames[I]);
354 Param.Type = BDebug.getTypeId(Element);
359 Parameters.push_back(Param);
363 void BTFTypeFuncProto::emitType(MCStreamer &OS) {
364 BTFTypeBase::emitType(OS);
365 for (const auto &Param : Parameters) {
366 OS.emitInt32(Param.NameOff);
367 OS.emitInt32(Param.Type);
371 BTFTypeFunc::BTFTypeFunc(StringRef FuncName, uint32_t ProtoTypeId,
374 Kind = BTF::BTF_KIND_FUNC;
375 BTFType.Info = (Kind << 24) | Scope;
376 BTFType.Type = ProtoTypeId;
379 void BTFTypeFunc::completeType(BTFDebug &BDebug) {
384 BTFType.NameOff = BDebug.addString(Name);
387 void BTFTypeFunc::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
389 BTFKindVar::BTFKindVar(StringRef VarName, uint32_t TypeId, uint32_t VarInfo)
391 Kind = BTF::BTF_KIND_VAR;
392 BTFType.Info = Kind << 24;
393 BTFType.Type = TypeId;
397 void BTFKindVar::completeType(BTFDebug &BDebug) {
398 BTFType.NameOff = BDebug.addString(Name);
401 void BTFKindVar::emitType(MCStreamer &OS) {
402 BTFTypeBase::emitType(OS);
406 BTFKindDataSec::BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
407 : Asm(AsmPrt), Name(SecName) {
408 Kind = BTF::BTF_KIND_DATASEC;
409 BTFType.Info = Kind << 24;
413 void BTFKindDataSec::completeType(BTFDebug &BDebug) {
414 BTFType.NameOff = BDebug.addString(Name);
415 BTFType.Info |= Vars.size();
418 void BTFKindDataSec::emitType(MCStreamer &OS) {
419 BTFTypeBase::emitType(OS);
421 for (const auto &V : Vars) {
422 OS.emitInt32(std::get<0>(V));
423 Asm->emitLabelReference(std::get<1>(V), 4);
424 OS.emitInt32(std::get<2>(V));
428 BTFTypeFloat::BTFTypeFloat(uint32_t SizeInBits, StringRef TypeName)
430 Kind = BTF::BTF_KIND_FLOAT;
431 BTFType.Info = Kind << 24;
432 BTFType.Size = roundupToBytes(SizeInBits);
435 void BTFTypeFloat::completeType(BTFDebug &BDebug) {
440 BTFType.NameOff = BDebug.addString(Name);
443 BTFTypeDeclTag::BTFTypeDeclTag(uint32_t BaseTypeId, int ComponentIdx,
446 Kind = BTF::BTF_KIND_DECL_TAG;
447 BTFType.Info = Kind << 24;
448 BTFType.Type = BaseTypeId;
452 void BTFTypeDeclTag::completeType(BTFDebug &BDebug) {
457 BTFType.NameOff = BDebug.addString(Tag);
460 void BTFTypeDeclTag::emitType(MCStreamer &OS) {
461 BTFTypeBase::emitType(OS);
465 BTFTypeTypeTag::BTFTypeTypeTag(uint32_t NextTypeId, StringRef Tag)
466 : DTy(nullptr), Tag(Tag) {
467 Kind = BTF::BTF_KIND_TYPE_TAG;
468 BTFType.Info = Kind << 24;
469 BTFType.Type = NextTypeId;
472 BTFTypeTypeTag::BTFTypeTypeTag(const DIDerivedType *DTy, StringRef Tag)
473 : DTy(DTy), Tag(Tag) {
474 Kind = BTF::BTF_KIND_TYPE_TAG;
475 BTFType.Info = Kind << 24;
478 void BTFTypeTypeTag::completeType(BTFDebug &BDebug) {
482 BTFType.NameOff = BDebug.addString(Tag);
484 const DIType *ResolvedType = DTy->getBaseType();
488 BTFType.Type = BDebug.getTypeId(ResolvedType);
492 uint32_t BTFStringTable::addString(StringRef S) {
493 // Check whether the string already exists.
494 for (auto &OffsetM : OffsetToIdMap) {
495 if (Table[OffsetM.second] == S)
496 return OffsetM.first;
498 // Not find, add to the string table.
499 uint32_t Offset = Size;
500 OffsetToIdMap[Offset] = Table.size();
501 Table.push_back(std::string(S));
502 Size += S.size() + 1;
506 BTFDebug::BTFDebug(AsmPrinter *AP)
507 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
508 LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
509 MapDefNotCollected(true) {
513 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry,
515 TypeEntry->setId(TypeEntries.size() + 1);
516 uint32_t Id = TypeEntry->getId();
518 TypeEntries.push_back(std::move(TypeEntry));
522 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
523 TypeEntry->setId(TypeEntries.size() + 1);
524 uint32_t Id = TypeEntry->getId();
525 TypeEntries.push_back(std::move(TypeEntry));
529 void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
530 // Only int and binary floating point types are supported in BTF.
531 uint32_t Encoding = BTy->getEncoding();
532 std::unique_ptr<BTFTypeBase> TypeEntry;
534 case dwarf::DW_ATE_boolean:
535 case dwarf::DW_ATE_signed:
536 case dwarf::DW_ATE_signed_char:
537 case dwarf::DW_ATE_unsigned:
538 case dwarf::DW_ATE_unsigned_char:
539 // Create a BTF type instance for this DIBasicType and put it into
540 // DIToIdMap for cross-type reference check.
541 TypeEntry = std::make_unique<BTFTypeInt>(
542 Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
544 case dwarf::DW_ATE_float:
546 std::make_unique<BTFTypeFloat>(BTy->getSizeInBits(), BTy->getName());
552 TypeId = addType(std::move(TypeEntry), BTy);
555 /// Handle subprogram or subroutine types.
556 void BTFDebug::visitSubroutineType(
557 const DISubroutineType *STy, bool ForSubprog,
558 const std::unordered_map<uint32_t, StringRef> &FuncArgNames,
560 DITypeRefArray Elements = STy->getTypeArray();
561 uint32_t VLen = Elements.size() - 1;
562 if (VLen > BTF::MAX_VLEN)
565 // Subprogram has a valid non-zero-length name, and the pointee of
566 // a function pointer has an empty name. The subprogram type will
567 // not be added to DIToIdMap as it should not be referenced by
569 auto TypeEntry = std::make_unique<BTFTypeFuncProto>(STy, VLen, FuncArgNames);
571 TypeId = addType(std::move(TypeEntry)); // For subprogram
573 TypeId = addType(std::move(TypeEntry), STy); // For func ptr
575 // Visit return type and func arg types.
576 for (const auto Element : Elements) {
577 visitTypeEntry(Element);
581 void BTFDebug::processDeclAnnotations(DINodeArray Annotations,
587 for (const Metadata *Annotation : Annotations->operands()) {
588 const MDNode *MD = cast<MDNode>(Annotation);
589 const MDString *Name = cast<MDString>(MD->getOperand(0));
590 if (!Name->getString().equals("btf_decl_tag"))
593 const MDString *Value = cast<MDString>(MD->getOperand(1));
594 auto TypeEntry = std::make_unique<BTFTypeDeclTag>(BaseTypeId, ComponentIdx,
596 addType(std::move(TypeEntry));
600 uint32_t BTFDebug::processDISubprogram(const DISubprogram *SP,
601 uint32_t ProtoTypeId, uint8_t Scope) {
603 std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
604 uint32_t FuncId = addType(std::move(FuncTypeEntry));
606 // Process argument annotations.
607 for (const DINode *DN : SP->getRetainedNodes()) {
608 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
609 uint32_t Arg = DV->getArg();
611 processDeclAnnotations(DV->getAnnotations(), FuncId, Arg - 1);
614 processDeclAnnotations(SP->getAnnotations(), FuncId, -1);
619 /// Generate btf_type_tag chains.
620 int BTFDebug::genBTFTypeTags(const DIDerivedType *DTy, int BaseTypeId) {
621 SmallVector<const MDString *, 4> MDStrs;
622 DINodeArray Annots = DTy->getAnnotations();
624 // For type with "int __tag1 __tag2 *p", the MDStrs will have
625 // content: [__tag1, __tag2].
626 for (const Metadata *Annotations : Annots->operands()) {
627 const MDNode *MD = cast<MDNode>(Annotations);
628 const MDString *Name = cast<MDString>(MD->getOperand(0));
629 if (!Name->getString().equals("btf_type_tag"))
631 MDStrs.push_back(cast<MDString>(MD->getOperand(1)));
635 if (MDStrs.size() == 0)
638 // With MDStrs [__tag1, __tag2], the output type chain looks like
639 // PTR -> __tag2 -> __tag1 -> BaseType
640 // In the below, we construct BTF types with the order of __tag1, __tag2
643 std::unique_ptr<BTFTypeTypeTag> TypeEntry;
646 std::make_unique<BTFTypeTypeTag>(BaseTypeId, MDStrs[0]->getString());
648 TypeEntry = std::make_unique<BTFTypeTypeTag>(DTy, MDStrs[0]->getString());
649 TmpTypeId = addType(std::move(TypeEntry));
651 for (unsigned I = 1; I < MDStrs.size(); I++) {
652 const MDString *Value = MDStrs[I];
653 TypeEntry = std::make_unique<BTFTypeTypeTag>(TmpTypeId, Value->getString());
654 TmpTypeId = addType(std::move(TypeEntry));
659 /// Handle structure/union types.
660 void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
662 const DINodeArray Elements = CTy->getElements();
663 uint32_t VLen = Elements.size();
664 if (VLen > BTF::MAX_VLEN)
667 // Check whether we have any bitfield members or not
668 bool HasBitField = false;
669 for (const auto *Element : Elements) {
670 auto E = cast<DIDerivedType>(Element);
671 if (E->isBitField()) {
678 std::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
679 StructTypes.push_back(TypeEntry.get());
680 TypeId = addType(std::move(TypeEntry), CTy);
682 // Check struct/union annotations
683 processDeclAnnotations(CTy->getAnnotations(), TypeId, -1);
685 // Visit all struct members.
687 for (const auto *Element : Elements) {
688 const auto Elem = cast<DIDerivedType>(Element);
689 visitTypeEntry(Elem);
690 processDeclAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
695 void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
696 // Visit array element type.
698 const DIType *ElemType = CTy->getBaseType();
699 visitTypeEntry(ElemType, ElemTypeId, false, false);
701 // Visit array dimensions.
702 DINodeArray Elements = CTy->getElements();
703 for (int I = Elements.size() - 1; I >= 0; --I) {
704 if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
705 if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
706 const DISubrange *SR = cast<DISubrange>(Element);
707 auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
708 int64_t Count = CI->getSExtValue();
710 // For struct s { int b; char c[]; }, the c[] will be represented
711 // as an array with Count = -1.
713 std::make_unique<BTFTypeArray>(ElemTypeId,
714 Count >= 0 ? Count : 0);
716 ElemTypeId = addType(std::move(TypeEntry), CTy);
718 ElemTypeId = addType(std::move(TypeEntry));
722 // The array TypeId is the type id of the outermost dimension.
725 // The IR does not have a type for array index while BTF wants one.
726 // So create an array index type if there is none.
727 if (!ArrayIndexTypeId) {
728 auto TypeEntry = std::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
729 0, "__ARRAY_SIZE_TYPE__");
730 ArrayIndexTypeId = addType(std::move(TypeEntry));
734 void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
735 DINodeArray Elements = CTy->getElements();
736 uint32_t VLen = Elements.size();
737 if (VLen > BTF::MAX_VLEN)
740 bool IsSigned = false;
741 unsigned NumBits = 32;
742 // No BaseType implies forward declaration in which case a
743 // BTFTypeEnum with Vlen = 0 is emitted.
744 if (CTy->getBaseType() != nullptr) {
745 const auto *BTy = cast<DIBasicType>(CTy->getBaseType());
746 IsSigned = BTy->getEncoding() == dwarf::DW_ATE_signed ||
747 BTy->getEncoding() == dwarf::DW_ATE_signed_char;
748 NumBits = BTy->getSizeInBits();
752 auto TypeEntry = std::make_unique<BTFTypeEnum>(CTy, VLen, IsSigned);
753 TypeId = addType(std::move(TypeEntry), CTy);
755 assert(NumBits == 64);
756 auto TypeEntry = std::make_unique<BTFTypeEnum64>(CTy, VLen, IsSigned);
757 TypeId = addType(std::move(TypeEntry), CTy);
759 // No need to visit base type as BTF does not encode it.
762 /// Handle structure/union forward declarations.
763 void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion,
765 auto TypeEntry = std::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
766 TypeId = addType(std::move(TypeEntry), CTy);
769 /// Handle structure, union, array and enumeration types.
770 void BTFDebug::visitCompositeType(const DICompositeType *CTy,
772 auto Tag = CTy->getTag();
773 if (Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
774 // Handle forward declaration differently as it does not have members.
775 if (CTy->isForwardDecl())
776 visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
778 visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
779 } else if (Tag == dwarf::DW_TAG_array_type)
780 visitArrayType(CTy, TypeId);
781 else if (Tag == dwarf::DW_TAG_enumeration_type)
782 visitEnumType(CTy, TypeId);
785 /// Handle pointer, typedef, const, volatile, restrict and member types.
786 void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
787 bool CheckPointer, bool SeenPointer) {
788 unsigned Tag = DTy->getTag();
790 /// Try to avoid chasing pointees, esp. structure pointees which may
791 /// unnecessary bring in a lot of types.
792 if (CheckPointer && !SeenPointer) {
793 SeenPointer = Tag == dwarf::DW_TAG_pointer_type;
796 if (CheckPointer && SeenPointer) {
797 const DIType *Base = DTy->getBaseType();
799 if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
800 auto CTag = CTy->getTag();
801 if ((CTag == dwarf::DW_TAG_structure_type ||
802 CTag == dwarf::DW_TAG_union_type) &&
803 !CTy->getName().empty() && !CTy->isForwardDecl()) {
804 /// Find a candidate, generate a fixup. Later on the struct/union
805 /// pointee type will be replaced with either a real type or
806 /// a forward declaration.
807 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, true);
808 auto &Fixup = FixupDerivedTypes[CTy];
809 Fixup.push_back(std::make_pair(DTy, TypeEntry.get()));
810 TypeId = addType(std::move(TypeEntry), DTy);
817 if (Tag == dwarf::DW_TAG_pointer_type) {
818 int TmpTypeId = genBTFTypeTags(DTy, -1);
819 if (TmpTypeId >= 0) {
821 std::make_unique<BTFTypeDerived>(TmpTypeId, Tag, DTy->getName());
822 TypeId = addType(std::move(TypeDEntry), DTy);
824 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
825 TypeId = addType(std::move(TypeEntry), DTy);
827 } else if (Tag == dwarf::DW_TAG_typedef || Tag == dwarf::DW_TAG_const_type ||
828 Tag == dwarf::DW_TAG_volatile_type ||
829 Tag == dwarf::DW_TAG_restrict_type) {
830 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
831 TypeId = addType(std::move(TypeEntry), DTy);
832 if (Tag == dwarf::DW_TAG_typedef)
833 processDeclAnnotations(DTy->getAnnotations(), TypeId, -1);
834 } else if (Tag != dwarf::DW_TAG_member) {
838 // Visit base type of pointer, typedef, const, volatile, restrict or
839 // struct/union member.
840 uint32_t TempTypeId = 0;
841 if (Tag == dwarf::DW_TAG_member)
842 visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
844 visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
847 void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
848 bool CheckPointer, bool SeenPointer) {
849 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
850 TypeId = DIToIdMap[Ty];
852 // To handle the case like the following:
854 // typedef struct t _t;
855 // struct s1 { _t *c; };
856 // int test1(struct s1 *arg) { ... }
858 // struct t { int a; int b; };
859 // struct s2 { _t c; }
860 // int test2(struct s2 *arg) { ... }
862 // During traversing test1() argument, "_t" is recorded
863 // in DIToIdMap and a forward declaration fixup is created
864 // for "struct t" to avoid pointee type traversal.
866 // During traversing test2() argument, even if we see "_t" is
867 // already defined, we should keep moving to eventually
868 // bring in types for "struct t". Otherwise, the "struct s2"
869 // definition won't be correct.
871 // In the above, we have following debuginfo:
872 // {ptr, struct_member} -> typedef -> struct
873 // and BTF type for 'typedef' is generated while 'struct' may
874 // be in FixUp. But let us generalize the above to handle
875 // {different types} -> [various derived types]+ -> another type.
877 // {func_param, struct_member} -> const -> ptr -> volatile -> struct
878 // We will traverse const/ptr/volatile which already have corresponding
879 // BTF types and generate type for 'struct' which might be in Fixup
881 if (Ty && (!CheckPointer || !SeenPointer)) {
882 if (const auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
884 const DIType *BaseTy = DTy->getBaseType();
888 if (DIToIdMap.find(BaseTy) != DIToIdMap.end()) {
889 DTy = dyn_cast<DIDerivedType>(BaseTy);
892 visitTypeEntry(BaseTy, TmpTypeId, CheckPointer, SeenPointer);
902 if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
903 visitBasicType(BTy, TypeId);
904 else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
905 visitSubroutineType(STy, false, std::unordered_map<uint32_t, StringRef>(),
907 else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
908 visitCompositeType(CTy, TypeId);
909 else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
910 visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
912 llvm_unreachable("Unknown DIType");
915 void BTFDebug::visitTypeEntry(const DIType *Ty) {
917 visitTypeEntry(Ty, TypeId, false, false);
920 void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
921 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
922 TypeId = DIToIdMap[Ty];
926 // MapDef type may be a struct type or a non-pointer derived type
927 const DIType *OrigTy = Ty;
928 while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
929 auto Tag = DTy->getTag();
930 if (Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type &&
931 Tag != dwarf::DW_TAG_volatile_type &&
932 Tag != dwarf::DW_TAG_restrict_type)
934 Ty = DTy->getBaseType();
937 const auto *CTy = dyn_cast<DICompositeType>(Ty);
941 auto Tag = CTy->getTag();
942 if (Tag != dwarf::DW_TAG_structure_type || CTy->isForwardDecl())
945 // Visit all struct members to ensure pointee type is visited
946 const DINodeArray Elements = CTy->getElements();
947 for (const auto *Element : Elements) {
948 const auto *MemberType = cast<DIDerivedType>(Element);
949 visitTypeEntry(MemberType->getBaseType());
952 // Visit this type, struct or a const/typedef/volatile/restrict type
953 visitTypeEntry(OrigTy, TypeId, false, false);
956 /// Read file contents from the actual file or from the source
957 std::string BTFDebug::populateFileContent(const DISubprogram *SP) {
958 auto File = SP->getFile();
959 std::string FileName;
961 if (!File->getFilename().startswith("/") && File->getDirectory().size())
962 FileName = File->getDirectory().str() + "/" + File->getFilename().str();
964 FileName = std::string(File->getFilename());
966 // No need to populate the contends if it has been populated!
967 if (FileContent.find(FileName) != FileContent.end())
970 std::vector<std::string> Content;
972 Content.push_back(Line); // Line 0 for empty string
974 std::unique_ptr<MemoryBuffer> Buf;
975 auto Source = File->getSource();
977 Buf = MemoryBuffer::getMemBufferCopy(*Source);
978 else if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
979 MemoryBuffer::getFile(FileName))
980 Buf = std::move(*BufOrErr);
982 for (line_iterator I(*Buf, false), E; I != E; ++I)
983 Content.push_back(std::string(*I));
985 FileContent[FileName] = Content;
989 void BTFDebug::constructLineInfo(const DISubprogram *SP, MCSymbol *Label,
990 uint32_t Line, uint32_t Column) {
991 std::string FileName = populateFileContent(SP);
992 BTFLineInfo LineInfo;
994 LineInfo.Label = Label;
995 LineInfo.FileNameOff = addString(FileName);
996 // If file content is not available, let LineOff = 0.
997 if (Line < FileContent[FileName].size())
998 LineInfo.LineOff = addString(FileContent[FileName][Line]);
1000 LineInfo.LineOff = 0;
1001 LineInfo.LineNum = Line;
1002 LineInfo.ColumnNum = Column;
1003 LineInfoTable[SecNameOff].push_back(LineInfo);
1006 void BTFDebug::emitCommonHeader() {
1007 OS.AddComment("0x" + Twine::utohexstr(BTF::MAGIC));
1008 OS.emitIntValue(BTF::MAGIC, 2);
1009 OS.emitInt8(BTF::VERSION);
1013 void BTFDebug::emitBTFSection() {
1014 // Do not emit section if no types and only "" string.
1015 if (!TypeEntries.size() && StringTable.getSize() == 1)
1018 MCContext &Ctx = OS.getContext();
1019 MCSectionELF *Sec = Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0);
1020 Sec->setAlignment(Align(4));
1021 OS.switchSection(Sec);
1025 OS.emitInt32(BTF::HeaderSize);
1027 uint32_t TypeLen = 0, StrLen;
1028 for (const auto &TypeEntry : TypeEntries)
1029 TypeLen += TypeEntry->getSize();
1030 StrLen = StringTable.getSize();
1033 OS.emitInt32(TypeLen);
1034 OS.emitInt32(TypeLen);
1035 OS.emitInt32(StrLen);
1038 for (const auto &TypeEntry : TypeEntries)
1039 TypeEntry->emitType(OS);
1041 // Emit string table.
1042 uint32_t StringOffset = 0;
1043 for (const auto &S : StringTable.getTable()) {
1044 OS.AddComment("string offset=" + std::to_string(StringOffset));
1046 OS.emitBytes(StringRef("\0", 1));
1047 StringOffset += S.size() + 1;
1051 void BTFDebug::emitBTFExtSection() {
1052 // Do not emit section if empty FuncInfoTable and LineInfoTable
1053 // and FieldRelocTable.
1054 if (!FuncInfoTable.size() && !LineInfoTable.size() &&
1055 !FieldRelocTable.size())
1058 MCContext &Ctx = OS.getContext();
1059 MCSectionELF *Sec = Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0);
1060 Sec->setAlignment(Align(4));
1061 OS.switchSection(Sec);
1065 OS.emitInt32(BTF::ExtHeaderSize);
1067 // Account for FuncInfo/LineInfo record size as well.
1068 uint32_t FuncLen = 4, LineLen = 4;
1069 // Do not account for optional FieldReloc.
1070 uint32_t FieldRelocLen = 0;
1071 for (const auto &FuncSec : FuncInfoTable) {
1072 FuncLen += BTF::SecFuncInfoSize;
1073 FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
1075 for (const auto &LineSec : LineInfoTable) {
1076 LineLen += BTF::SecLineInfoSize;
1077 LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
1079 for (const auto &FieldRelocSec : FieldRelocTable) {
1080 FieldRelocLen += BTF::SecFieldRelocSize;
1081 FieldRelocLen += FieldRelocSec.second.size() * BTF::BPFFieldRelocSize;
1088 OS.emitInt32(FuncLen);
1089 OS.emitInt32(FuncLen);
1090 OS.emitInt32(LineLen);
1091 OS.emitInt32(FuncLen + LineLen);
1092 OS.emitInt32(FieldRelocLen);
1094 // Emit func_info table.
1095 OS.AddComment("FuncInfo");
1096 OS.emitInt32(BTF::BPFFuncInfoSize);
1097 for (const auto &FuncSec : FuncInfoTable) {
1098 OS.AddComment("FuncInfo section string offset=" +
1099 std::to_string(FuncSec.first));
1100 OS.emitInt32(FuncSec.first);
1101 OS.emitInt32(FuncSec.second.size());
1102 for (const auto &FuncInfo : FuncSec.second) {
1103 Asm->emitLabelReference(FuncInfo.Label, 4);
1104 OS.emitInt32(FuncInfo.TypeId);
1108 // Emit line_info table.
1109 OS.AddComment("LineInfo");
1110 OS.emitInt32(BTF::BPFLineInfoSize);
1111 for (const auto &LineSec : LineInfoTable) {
1112 OS.AddComment("LineInfo section string offset=" +
1113 std::to_string(LineSec.first));
1114 OS.emitInt32(LineSec.first);
1115 OS.emitInt32(LineSec.second.size());
1116 for (const auto &LineInfo : LineSec.second) {
1117 Asm->emitLabelReference(LineInfo.Label, 4);
1118 OS.emitInt32(LineInfo.FileNameOff);
1119 OS.emitInt32(LineInfo.LineOff);
1120 OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
1121 std::to_string(LineInfo.ColumnNum));
1122 OS.emitInt32(LineInfo.LineNum << 10 | LineInfo.ColumnNum);
1126 // Emit field reloc table.
1127 if (FieldRelocLen) {
1128 OS.AddComment("FieldReloc");
1129 OS.emitInt32(BTF::BPFFieldRelocSize);
1130 for (const auto &FieldRelocSec : FieldRelocTable) {
1131 OS.AddComment("Field reloc section string offset=" +
1132 std::to_string(FieldRelocSec.first));
1133 OS.emitInt32(FieldRelocSec.first);
1134 OS.emitInt32(FieldRelocSec.second.size());
1135 for (const auto &FieldRelocInfo : FieldRelocSec.second) {
1136 Asm->emitLabelReference(FieldRelocInfo.Label, 4);
1137 OS.emitInt32(FieldRelocInfo.TypeID);
1138 OS.emitInt32(FieldRelocInfo.OffsetNameOff);
1139 OS.emitInt32(FieldRelocInfo.RelocKind);
1145 void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
1146 auto *SP = MF->getFunction().getSubprogram();
1147 auto *Unit = SP->getUnit();
1149 if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
1150 SkipInstruction = true;
1153 SkipInstruction = false;
1155 // Collect MapDef types. Map definition needs to collect
1156 // pointee types. Do it first. Otherwise, for the following
1162 // foo(struct t *arg);
1168 // } __attribute__((section(".maps"))) hash_map;
1170 // If subroutine foo is traversed first, a type chain
1171 // "ptr->struct m(fwd)" will be created and later on
1172 // when traversing mapdef, since "ptr->struct m" exists,
1173 // the traversal of "struct m" will be omitted.
1174 if (MapDefNotCollected) {
1175 processGlobals(true);
1176 MapDefNotCollected = false;
1179 // Collect all types locally referenced in this function.
1180 // Use RetainedNodes so we can collect all argument names
1181 // even if the argument is not used.
1182 std::unordered_map<uint32_t, StringRef> FuncArgNames;
1183 for (const DINode *DN : SP->getRetainedNodes()) {
1184 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
1185 // Collect function arguments for subprogram func type.
1186 uint32_t Arg = DV->getArg();
1188 visitTypeEntry(DV->getType());
1189 FuncArgNames[Arg] = DV->getName();
1194 // Construct subprogram func proto type.
1195 uint32_t ProtoTypeId;
1196 visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId);
1198 // Construct subprogram func type
1199 uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
1200 uint32_t FuncTypeId = processDISubprogram(SP, ProtoTypeId, Scope);
1202 for (const auto &TypeEntry : TypeEntries)
1203 TypeEntry->completeType(*this);
1205 // Construct funcinfo and the first lineinfo for the function.
1206 MCSymbol *FuncLabel = Asm->getFunctionBegin();
1207 BTFFuncInfo FuncInfo;
1208 FuncInfo.Label = FuncLabel;
1209 FuncInfo.TypeId = FuncTypeId;
1210 if (FuncLabel->isInSection()) {
1211 MCSection &Section = FuncLabel->getSection();
1212 const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section);
1213 assert(SectionELF && "Null section for Function Label");
1214 SecNameOff = addString(SectionELF->getName());
1216 SecNameOff = addString(".text");
1218 FuncInfoTable[SecNameOff].push_back(FuncInfo);
1221 void BTFDebug::endFunctionImpl(const MachineFunction *MF) {
1222 SkipInstruction = false;
1223 LineInfoGenerated = false;
1227 /// On-demand populate types as requested from abstract member
1228 /// accessing or preserve debuginfo type.
1229 unsigned BTFDebug::populateType(const DIType *Ty) {
1231 visitTypeEntry(Ty, Id, false, false);
1232 for (const auto &TypeEntry : TypeEntries)
1233 TypeEntry->completeType(*this);
1237 /// Generate a struct member field relocation.
1238 void BTFDebug::generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
1239 const GlobalVariable *GVar, bool IsAma) {
1240 BTFFieldReloc FieldReloc;
1241 FieldReloc.Label = ORSym;
1242 FieldReloc.TypeID = RootId;
1244 StringRef AccessPattern = GVar->getName();
1245 size_t FirstDollar = AccessPattern.find_first_of('$');
1247 size_t FirstColon = AccessPattern.find_first_of(':');
1248 size_t SecondColon = AccessPattern.find_first_of(':', FirstColon + 1);
1249 StringRef IndexPattern = AccessPattern.substr(FirstDollar + 1);
1250 StringRef RelocKindStr = AccessPattern.substr(FirstColon + 1,
1251 SecondColon - FirstColon);
1252 StringRef PatchImmStr = AccessPattern.substr(SecondColon + 1,
1253 FirstDollar - SecondColon);
1255 FieldReloc.OffsetNameOff = addString(IndexPattern);
1256 FieldReloc.RelocKind = std::stoull(std::string(RelocKindStr));
1257 PatchImms[GVar] = std::make_pair(std::stoll(std::string(PatchImmStr)),
1258 FieldReloc.RelocKind);
1260 StringRef RelocStr = AccessPattern.substr(FirstDollar + 1);
1261 FieldReloc.OffsetNameOff = addString("0");
1262 FieldReloc.RelocKind = std::stoull(std::string(RelocStr));
1263 PatchImms[GVar] = std::make_pair(RootId, FieldReloc.RelocKind);
1265 FieldRelocTable[SecNameOff].push_back(FieldReloc);
1268 void BTFDebug::processGlobalValue(const MachineOperand &MO) {
1269 // check whether this is a candidate or not
1270 if (MO.isGlobal()) {
1271 const GlobalValue *GVal = MO.getGlobal();
1272 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1274 // Not a global variable. Maybe an extern function reference.
1275 processFuncPrototypes(dyn_cast<Function>(GVal));
1279 if (!GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) &&
1280 !GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr))
1283 MCSymbol *ORSym = OS.getContext().createTempSymbol();
1284 OS.emitLabel(ORSym);
1286 MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
1287 uint32_t RootId = populateType(dyn_cast<DIType>(MDN));
1288 generatePatchImmReloc(ORSym, RootId, GVar,
1289 GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr));
1293 void BTFDebug::beginInstruction(const MachineInstr *MI) {
1294 DebugHandlerBase::beginInstruction(MI);
1296 if (SkipInstruction || MI->isMetaInstruction() ||
1297 MI->getFlag(MachineInstr::FrameSetup))
1300 if (MI->isInlineAsm()) {
1301 // Count the number of register definitions to find the asm string.
1302 unsigned NumDefs = 0;
1303 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1307 // Skip this inline asm instruction if the asmstr is empty.
1308 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1313 if (MI->getOpcode() == BPF::LD_imm64) {
1314 // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
1315 // add this insn into the .BTF.ext FieldReloc subsection.
1316 // Relocation looks like:
1322 // Later, the insn is replaced with "r2 = <offset>"
1323 // where "<offset>" equals to the offset based on current
1324 // type definitions.
1326 // If the insn is "r2 = LD_imm64 @<an TypeIdAttr global>",
1327 // The LD_imm64 result will be replaced with a btf type id.
1328 processGlobalValue(MI->getOperand(1));
1329 } else if (MI->getOpcode() == BPF::CORE_MEM ||
1330 MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1331 MI->getOpcode() == BPF::CORE_SHIFT) {
1332 // relocation insn is a load, store or shift insn.
1333 processGlobalValue(MI->getOperand(3));
1334 } else if (MI->getOpcode() == BPF::JAL) {
1335 // check extern function references
1336 const MachineOperand &MO = MI->getOperand(0);
1337 if (MO.isGlobal()) {
1338 processFuncPrototypes(dyn_cast<Function>(MO.getGlobal()));
1342 if (!CurMI) // no debug info
1345 // Skip this instruction if no DebugLoc or the DebugLoc
1346 // is the same as the previous instruction.
1347 const DebugLoc &DL = MI->getDebugLoc();
1348 if (!DL || PrevInstLoc == DL) {
1349 // This instruction will be skipped, no LineInfo has
1350 // been generated, construct one based on function signature.
1351 if (LineInfoGenerated == false) {
1352 auto *S = MI->getMF()->getFunction().getSubprogram();
1353 MCSymbol *FuncLabel = Asm->getFunctionBegin();
1354 constructLineInfo(S, FuncLabel, S->getLine(), 0);
1355 LineInfoGenerated = true;
1361 // Create a temporary label to remember the insn for lineinfo.
1362 MCSymbol *LineSym = OS.getContext().createTempSymbol();
1363 OS.emitLabel(LineSym);
1365 // Construct the lineinfo.
1366 auto SP = DL->getScope()->getSubprogram();
1367 constructLineInfo(SP, LineSym, DL.getLine(), DL.getCol());
1369 LineInfoGenerated = true;
1373 void BTFDebug::processGlobals(bool ProcessingMapDef) {
1374 // Collect all types referenced by globals.
1375 const Module *M = MMI->getModule();
1376 for (const GlobalVariable &Global : M->globals()) {
1377 // Decide the section name.
1379 std::optional<SectionKind> GVKind;
1381 if (!Global.isDeclarationForLinker())
1382 GVKind = TargetLoweringObjectFile::getKindForGlobal(&Global, Asm->TM);
1384 if (Global.isDeclarationForLinker())
1385 SecName = Global.hasSection() ? Global.getSection() : "";
1386 else if (GVKind->isCommon())
1389 TargetLoweringObjectFile *TLOF = Asm->TM.getObjFileLowering();
1390 MCSection *Sec = TLOF->SectionForGlobal(&Global, Asm->TM);
1391 SecName = Sec->getName();
1394 if (ProcessingMapDef != SecName.startswith(".maps"))
1397 // Create a .rodata datasec if the global variable is an initialized
1398 // constant with private linkage and if it won't be in .rodata.str<#>
1399 // and .rodata.cst<#> sections.
1400 if (SecName == ".rodata" && Global.hasPrivateLinkage() &&
1401 DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1402 // skip .rodata.str<#> and .rodata.cst<#> sections
1403 if (!GVKind->isMergeableCString() && !GVKind->isMergeableConst()) {
1404 DataSecEntries[std::string(SecName)] =
1405 std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1409 SmallVector<DIGlobalVariableExpression *, 1> GVs;
1410 Global.getDebugInfo(GVs);
1412 // No type information, mostly internal, skip it.
1413 if (GVs.size() == 0)
1416 uint32_t GVTypeId = 0;
1417 DIGlobalVariable *DIGlobal = nullptr;
1418 for (auto *GVE : GVs) {
1419 DIGlobal = GVE->getVariable();
1420 if (SecName.startswith(".maps"))
1421 visitMapDefType(DIGlobal->getType(), GVTypeId);
1423 visitTypeEntry(DIGlobal->getType(), GVTypeId, false, false);
1427 // Only support the following globals:
1428 // . static variables
1429 // . non-static weak or non-weak global variables
1430 // . weak or non-weak extern global variables
1431 // Whether DataSec is readonly or not can be found from corresponding ELF
1432 // section flags. Whether a BTF_KIND_VAR is a weak symbol or not
1433 // can be found from the corresponding ELF symbol table.
1434 auto Linkage = Global.getLinkage();
1435 if (Linkage != GlobalValue::InternalLinkage &&
1436 Linkage != GlobalValue::ExternalLinkage &&
1437 Linkage != GlobalValue::WeakAnyLinkage &&
1438 Linkage != GlobalValue::WeakODRLinkage &&
1439 Linkage != GlobalValue::ExternalWeakLinkage)
1443 if (Linkage == GlobalValue::InternalLinkage) {
1444 GVarInfo = BTF::VAR_STATIC;
1445 } else if (Global.hasInitializer()) {
1446 GVarInfo = BTF::VAR_GLOBAL_ALLOCATED;
1448 GVarInfo = BTF::VAR_GLOBAL_EXTERNAL;
1452 std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
1453 uint32_t VarId = addType(std::move(VarEntry));
1455 processDeclAnnotations(DIGlobal->getAnnotations(), VarId, -1);
1457 // An empty SecName means an extern variable without section attribute.
1458 if (SecName.empty())
1461 // Find or create a DataSec
1462 if (DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1463 DataSecEntries[std::string(SecName)] =
1464 std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1467 // Calculate symbol size
1468 const DataLayout &DL = Global.getParent()->getDataLayout();
1469 uint32_t Size = DL.getTypeAllocSize(Global.getValueType());
1471 DataSecEntries[std::string(SecName)]->addDataSecEntry(VarId,
1472 Asm->getSymbol(&Global), Size);
1476 /// Emit proper patchable instructions.
1477 bool BTFDebug::InstLower(const MachineInstr *MI, MCInst &OutMI) {
1478 if (MI->getOpcode() == BPF::LD_imm64) {
1479 const MachineOperand &MO = MI->getOperand(1);
1480 if (MO.isGlobal()) {
1481 const GlobalValue *GVal = MO.getGlobal();
1482 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1484 // Emit "mov ri, <imm>"
1487 if (GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) ||
1488 GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr)) {
1489 Imm = PatchImms[GVar].first;
1490 Reloc = PatchImms[GVar].second;
1495 if (Reloc == BPFCoreSharedInfo::ENUM_VALUE_EXISTENCE ||
1496 Reloc == BPFCoreSharedInfo::ENUM_VALUE ||
1497 Reloc == BPFCoreSharedInfo::BTF_TYPE_ID_LOCAL ||
1498 Reloc == BPFCoreSharedInfo::BTF_TYPE_ID_REMOTE)
1499 OutMI.setOpcode(BPF::LD_imm64);
1501 OutMI.setOpcode(BPF::MOV_ri);
1502 OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1503 OutMI.addOperand(MCOperand::createImm(Imm));
1507 } else if (MI->getOpcode() == BPF::CORE_MEM ||
1508 MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1509 MI->getOpcode() == BPF::CORE_SHIFT) {
1510 const MachineOperand &MO = MI->getOperand(3);
1511 if (MO.isGlobal()) {
1512 const GlobalValue *GVal = MO.getGlobal();
1513 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1514 if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
1515 uint32_t Imm = PatchImms[GVar].first;
1516 OutMI.setOpcode(MI->getOperand(1).getImm());
1517 if (MI->getOperand(0).isImm())
1518 OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
1520 OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1521 OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
1522 OutMI.addOperand(MCOperand::createImm(Imm));
1530 void BTFDebug::processFuncPrototypes(const Function *F) {
1534 const DISubprogram *SP = F->getSubprogram();
1535 if (!SP || SP->isDefinition())
1538 // Do not emit again if already emitted.
1539 if (!ProtoFunctions.insert(F).second)
1542 uint32_t ProtoTypeId;
1543 const std::unordered_map<uint32_t, StringRef> FuncArgNames;
1544 visitSubroutineType(SP->getType(), false, FuncArgNames, ProtoTypeId);
1545 uint32_t FuncId = processDISubprogram(SP, ProtoTypeId, BTF::FUNC_EXTERN);
1547 if (F->hasSection()) {
1548 StringRef SecName = F->getSection();
1550 if (DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1551 DataSecEntries[std::string(SecName)] =
1552 std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1555 // We really don't know func size, set it to 0.
1556 DataSecEntries[std::string(SecName)]->addDataSecEntry(FuncId,
1557 Asm->getSymbol(F), 0);
1561 void BTFDebug::endModule() {
1562 // Collect MapDef globals if not collected yet.
1563 if (MapDefNotCollected) {
1564 processGlobals(true);
1565 MapDefNotCollected = false;
1568 // Collect global types/variables except MapDef globals.
1569 processGlobals(false);
1571 for (auto &DataSec : DataSecEntries)
1572 addType(std::move(DataSec.second));
1575 for (auto &Fixup : FixupDerivedTypes) {
1576 const DICompositeType *CTy = Fixup.first;
1577 StringRef TypeName = CTy->getName();
1578 bool IsUnion = CTy->getTag() == dwarf::DW_TAG_union_type;
1580 // Search through struct types
1581 uint32_t StructTypeId = 0;
1582 for (const auto &StructType : StructTypes) {
1583 if (StructType->getName() == TypeName) {
1584 StructTypeId = StructType->getId();
1589 if (StructTypeId == 0) {
1590 auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
1591 StructTypeId = addType(std::move(FwdTypeEntry));
1594 for (auto &TypeInfo : Fixup.second) {
1595 const DIDerivedType *DTy = TypeInfo.first;
1596 BTFTypeDerived *BDType = TypeInfo.second;
1598 int TmpTypeId = genBTFTypeTags(DTy, StructTypeId);
1600 BDType->setPointeeType(TmpTypeId);
1602 BDType->setPointeeType(StructTypeId);
1606 // Complete BTF type cross refereences.
1607 for (const auto &TypeEntry : TypeEntries)
1608 TypeEntry->completeType(*this);
1610 // Emit BTF sections.
1612 emitBTFExtSection();