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