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 "BPF.h"
15 #include "BPFCORE.h"
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/Target/TargetLoweringObjectFile.h"
26 
27 using namespace llvm;
28 
29 static const char *BTFKindStr[] = {
30 #define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
31 #include "BTF.def"
32 };
33 
34 /// Emit a BTF common type.
35 void BTFTypeBase::emitType(MCStreamer &OS) {
36   OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
37                 ")");
38   OS.emitInt32(BTFType.NameOff);
39   OS.AddComment("0x" + Twine::utohexstr(BTFType.Info));
40   OS.emitInt32(BTFType.Info);
41   OS.emitInt32(BTFType.Size);
42 }
43 
44 BTFTypeDerived::BTFTypeDerived(const DIDerivedType *DTy, unsigned Tag,
45                                bool NeedsFixup)
46     : DTy(DTy), NeedsFixup(NeedsFixup), Name(DTy->getName()) {
47   switch (Tag) {
48   case dwarf::DW_TAG_pointer_type:
49     Kind = BTF::BTF_KIND_PTR;
50     break;
51   case dwarf::DW_TAG_const_type:
52     Kind = BTF::BTF_KIND_CONST;
53     break;
54   case dwarf::DW_TAG_volatile_type:
55     Kind = BTF::BTF_KIND_VOLATILE;
56     break;
57   case dwarf::DW_TAG_typedef:
58     Kind = BTF::BTF_KIND_TYPEDEF;
59     break;
60   case dwarf::DW_TAG_restrict_type:
61     Kind = BTF::BTF_KIND_RESTRICT;
62     break;
63   default:
64     llvm_unreachable("Unknown DIDerivedType Tag");
65   }
66   BTFType.Info = Kind << 24;
67 }
68 
69 /// Used by DW_TAG_pointer_type only.
70 BTFTypeDerived::BTFTypeDerived(unsigned NextTypeId, unsigned Tag,
71                                StringRef Name)
72     : DTy(nullptr), NeedsFixup(false), Name(Name) {
73   Kind = BTF::BTF_KIND_PTR;
74   BTFType.Info = Kind << 24;
75   BTFType.Type = NextTypeId;
76 }
77 
78 void BTFTypeDerived::completeType(BTFDebug &BDebug) {
79   if (IsCompleted)
80     return;
81   IsCompleted = true;
82 
83   BTFType.NameOff = BDebug.addString(Name);
84 
85   if (NeedsFixup || !DTy)
86     return;
87 
88   // The base type for PTR/CONST/VOLATILE could be void.
89   const DIType *ResolvedType = DTy->getBaseType();
90   if (!ResolvedType) {
91     assert((Kind == BTF::BTF_KIND_PTR || Kind == BTF::BTF_KIND_CONST ||
92             Kind == BTF::BTF_KIND_VOLATILE) &&
93            "Invalid null basetype");
94     BTFType.Type = 0;
95   } else {
96     BTFType.Type = BDebug.getTypeId(ResolvedType);
97   }
98 }
99 
100 void BTFTypeDerived::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
101 
102 void BTFTypeDerived::setPointeeType(uint32_t PointeeType) {
103   BTFType.Type = PointeeType;
104 }
105 
106 /// Represent a struct/union forward declaration.
107 BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion) : Name(Name) {
108   Kind = BTF::BTF_KIND_FWD;
109   BTFType.Info = IsUnion << 31 | Kind << 24;
110   BTFType.Type = 0;
111 }
112 
113 void BTFTypeFwd::completeType(BTFDebug &BDebug) {
114   if (IsCompleted)
115     return;
116   IsCompleted = true;
117 
118   BTFType.NameOff = BDebug.addString(Name);
119 }
120 
121 void BTFTypeFwd::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
122 
123 BTFTypeInt::BTFTypeInt(uint32_t Encoding, uint32_t SizeInBits,
124                        uint32_t OffsetInBits, StringRef TypeName)
125     : Name(TypeName) {
126   // Translate IR int encoding to BTF int encoding.
127   uint8_t BTFEncoding;
128   switch (Encoding) {
129   case dwarf::DW_ATE_boolean:
130     BTFEncoding = BTF::INT_BOOL;
131     break;
132   case dwarf::DW_ATE_signed:
133   case dwarf::DW_ATE_signed_char:
134     BTFEncoding = BTF::INT_SIGNED;
135     break;
136   case dwarf::DW_ATE_unsigned:
137   case dwarf::DW_ATE_unsigned_char:
138     BTFEncoding = 0;
139     break;
140   default:
141     llvm_unreachable("Unknown BTFTypeInt Encoding");
142   }
143 
144   Kind = BTF::BTF_KIND_INT;
145   BTFType.Info = Kind << 24;
146   BTFType.Size = roundupToBytes(SizeInBits);
147   IntVal = (BTFEncoding << 24) | OffsetInBits << 16 | SizeInBits;
148 }
149 
150 void BTFTypeInt::completeType(BTFDebug &BDebug) {
151   if (IsCompleted)
152     return;
153   IsCompleted = true;
154 
155   BTFType.NameOff = BDebug.addString(Name);
156 }
157 
158 void BTFTypeInt::emitType(MCStreamer &OS) {
159   BTFTypeBase::emitType(OS);
160   OS.AddComment("0x" + Twine::utohexstr(IntVal));
161   OS.emitInt32(IntVal);
162 }
163 
164 BTFTypeEnum::BTFTypeEnum(const DICompositeType *ETy, uint32_t VLen) : ETy(ETy) {
165   Kind = BTF::BTF_KIND_ENUM;
166   BTFType.Info = Kind << 24 | VLen;
167   BTFType.Size = roundupToBytes(ETy->getSizeInBits());
168 }
169 
170 void BTFTypeEnum::completeType(BTFDebug &BDebug) {
171   if (IsCompleted)
172     return;
173   IsCompleted = true;
174 
175   BTFType.NameOff = BDebug.addString(ETy->getName());
176 
177   DINodeArray Elements = ETy->getElements();
178   for (const auto Element : Elements) {
179     const auto *Enum = cast<DIEnumerator>(Element);
180 
181     struct BTF::BTFEnum BTFEnum;
182     BTFEnum.NameOff = BDebug.addString(Enum->getName());
183     // BTF enum value is 32bit, enforce it.
184     uint32_t Value;
185     if (Enum->isUnsigned())
186       Value = static_cast<uint32_t>(Enum->getValue().getZExtValue());
187     else
188       Value = static_cast<uint32_t>(Enum->getValue().getSExtValue());
189     BTFEnum.Val = Value;
190     EnumValues.push_back(BTFEnum);
191   }
192 }
193 
194 void BTFTypeEnum::emitType(MCStreamer &OS) {
195   BTFTypeBase::emitType(OS);
196   for (const auto &Enum : EnumValues) {
197     OS.emitInt32(Enum.NameOff);
198     OS.emitInt32(Enum.Val);
199   }
200 }
201 
202 BTFTypeArray::BTFTypeArray(uint32_t ElemTypeId, uint32_t NumElems) {
203   Kind = BTF::BTF_KIND_ARRAY;
204   BTFType.NameOff = 0;
205   BTFType.Info = Kind << 24;
206   BTFType.Size = 0;
207 
208   ArrayInfo.ElemType = ElemTypeId;
209   ArrayInfo.Nelems = NumElems;
210 }
211 
212 /// Represent a BTF array.
213 void BTFTypeArray::completeType(BTFDebug &BDebug) {
214   if (IsCompleted)
215     return;
216   IsCompleted = true;
217 
218   // The IR does not really have a type for the index.
219   // A special type for array index should have been
220   // created during initial type traversal. Just
221   // retrieve that type id.
222   ArrayInfo.IndexType = BDebug.getArrayIndexTypeId();
223 }
224 
225 void BTFTypeArray::emitType(MCStreamer &OS) {
226   BTFTypeBase::emitType(OS);
227   OS.emitInt32(ArrayInfo.ElemType);
228   OS.emitInt32(ArrayInfo.IndexType);
229   OS.emitInt32(ArrayInfo.Nelems);
230 }
231 
232 /// Represent either a struct or a union.
233 BTFTypeStruct::BTFTypeStruct(const DICompositeType *STy, bool IsStruct,
234                              bool HasBitField, uint32_t Vlen)
235     : STy(STy), HasBitField(HasBitField) {
236   Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION;
237   BTFType.Size = roundupToBytes(STy->getSizeInBits());
238   BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen;
239 }
240 
241 void BTFTypeStruct::completeType(BTFDebug &BDebug) {
242   if (IsCompleted)
243     return;
244   IsCompleted = true;
245 
246   BTFType.NameOff = BDebug.addString(STy->getName());
247 
248   // Add struct/union members.
249   const DINodeArray Elements = STy->getElements();
250   for (const auto *Element : Elements) {
251     struct BTF::BTFMember BTFMember;
252     const auto *DDTy = cast<DIDerivedType>(Element);
253 
254     BTFMember.NameOff = BDebug.addString(DDTy->getName());
255     if (HasBitField) {
256       uint8_t BitFieldSize = DDTy->isBitField() ? DDTy->getSizeInBits() : 0;
257       BTFMember.Offset = BitFieldSize << 24 | DDTy->getOffsetInBits();
258     } else {
259       BTFMember.Offset = DDTy->getOffsetInBits();
260     }
261     const auto *BaseTy = DDTy->getBaseType();
262     BTFMember.Type = BDebug.getTypeId(BaseTy);
263     Members.push_back(BTFMember);
264   }
265 }
266 
267 void BTFTypeStruct::emitType(MCStreamer &OS) {
268   BTFTypeBase::emitType(OS);
269   for (const auto &Member : Members) {
270     OS.emitInt32(Member.NameOff);
271     OS.emitInt32(Member.Type);
272     OS.AddComment("0x" + Twine::utohexstr(Member.Offset));
273     OS.emitInt32(Member.Offset);
274   }
275 }
276 
277 std::string BTFTypeStruct::getName() { return std::string(STy->getName()); }
278 
279 /// The Func kind represents both subprogram and pointee of function
280 /// pointers. If the FuncName is empty, it represents a pointee of function
281 /// pointer. Otherwise, it represents a subprogram. The func arg names
282 /// are empty for pointee of function pointer case, and are valid names
283 /// for subprogram.
284 BTFTypeFuncProto::BTFTypeFuncProto(
285     const DISubroutineType *STy, uint32_t VLen,
286     const std::unordered_map<uint32_t, StringRef> &FuncArgNames)
287     : STy(STy), FuncArgNames(FuncArgNames) {
288   Kind = BTF::BTF_KIND_FUNC_PROTO;
289   BTFType.Info = (Kind << 24) | VLen;
290 }
291 
292 void BTFTypeFuncProto::completeType(BTFDebug &BDebug) {
293   if (IsCompleted)
294     return;
295   IsCompleted = true;
296 
297   DITypeRefArray Elements = STy->getTypeArray();
298   auto RetType = Elements[0];
299   BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
300   BTFType.NameOff = 0;
301 
302   // For null parameter which is typically the last one
303   // to represent the vararg, encode the NameOff/Type to be 0.
304   for (unsigned I = 1, N = Elements.size(); I < N; ++I) {
305     struct BTF::BTFParam Param;
306     auto Element = Elements[I];
307     if (Element) {
308       Param.NameOff = BDebug.addString(FuncArgNames[I]);
309       Param.Type = BDebug.getTypeId(Element);
310     } else {
311       Param.NameOff = 0;
312       Param.Type = 0;
313     }
314     Parameters.push_back(Param);
315   }
316 }
317 
318 void BTFTypeFuncProto::emitType(MCStreamer &OS) {
319   BTFTypeBase::emitType(OS);
320   for (const auto &Param : Parameters) {
321     OS.emitInt32(Param.NameOff);
322     OS.emitInt32(Param.Type);
323   }
324 }
325 
326 BTFTypeFunc::BTFTypeFunc(StringRef FuncName, uint32_t ProtoTypeId,
327     uint32_t Scope)
328     : Name(FuncName) {
329   Kind = BTF::BTF_KIND_FUNC;
330   BTFType.Info = (Kind << 24) | Scope;
331   BTFType.Type = ProtoTypeId;
332 }
333 
334 void BTFTypeFunc::completeType(BTFDebug &BDebug) {
335   if (IsCompleted)
336     return;
337   IsCompleted = true;
338 
339   BTFType.NameOff = BDebug.addString(Name);
340 }
341 
342 void BTFTypeFunc::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
343 
344 BTFKindVar::BTFKindVar(StringRef VarName, uint32_t TypeId, uint32_t VarInfo)
345     : Name(VarName) {
346   Kind = BTF::BTF_KIND_VAR;
347   BTFType.Info = Kind << 24;
348   BTFType.Type = TypeId;
349   Info = VarInfo;
350 }
351 
352 void BTFKindVar::completeType(BTFDebug &BDebug) {
353   BTFType.NameOff = BDebug.addString(Name);
354 }
355 
356 void BTFKindVar::emitType(MCStreamer &OS) {
357   BTFTypeBase::emitType(OS);
358   OS.emitInt32(Info);
359 }
360 
361 BTFKindDataSec::BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
362     : Asm(AsmPrt), Name(SecName) {
363   Kind = BTF::BTF_KIND_DATASEC;
364   BTFType.Info = Kind << 24;
365   BTFType.Size = 0;
366 }
367 
368 void BTFKindDataSec::completeType(BTFDebug &BDebug) {
369   BTFType.NameOff = BDebug.addString(Name);
370   BTFType.Info |= Vars.size();
371 }
372 
373 void BTFKindDataSec::emitType(MCStreamer &OS) {
374   BTFTypeBase::emitType(OS);
375 
376   for (const auto &V : Vars) {
377     OS.emitInt32(std::get<0>(V));
378     Asm->emitLabelReference(std::get<1>(V), 4);
379     OS.emitInt32(std::get<2>(V));
380   }
381 }
382 
383 BTFTypeFloat::BTFTypeFloat(uint32_t SizeInBits, StringRef TypeName)
384     : Name(TypeName) {
385   Kind = BTF::BTF_KIND_FLOAT;
386   BTFType.Info = Kind << 24;
387   BTFType.Size = roundupToBytes(SizeInBits);
388 }
389 
390 void BTFTypeFloat::completeType(BTFDebug &BDebug) {
391   if (IsCompleted)
392     return;
393   IsCompleted = true;
394 
395   BTFType.NameOff = BDebug.addString(Name);
396 }
397 
398 BTFTypeDeclTag::BTFTypeDeclTag(uint32_t BaseTypeId, int ComponentIdx,
399                                StringRef Tag)
400     : Tag(Tag) {
401   Kind = BTF::BTF_KIND_DECL_TAG;
402   BTFType.Info = Kind << 24;
403   BTFType.Type = BaseTypeId;
404   Info = ComponentIdx;
405 }
406 
407 void BTFTypeDeclTag::completeType(BTFDebug &BDebug) {
408   if (IsCompleted)
409     return;
410   IsCompleted = true;
411 
412   BTFType.NameOff = BDebug.addString(Tag);
413 }
414 
415 void BTFTypeDeclTag::emitType(MCStreamer &OS) {
416   BTFTypeBase::emitType(OS);
417   OS.emitInt32(Info);
418 }
419 
420 BTFTypeTypeTag::BTFTypeTypeTag(uint32_t NextTypeId, StringRef Tag)
421     : DTy(nullptr), Tag(Tag) {
422   Kind = BTF::BTF_KIND_TYPE_TAG;
423   BTFType.Info = Kind << 24;
424   BTFType.Type = NextTypeId;
425 }
426 
427 BTFTypeTypeTag::BTFTypeTypeTag(const DIDerivedType *DTy, StringRef Tag)
428     : DTy(DTy), Tag(Tag) {
429   Kind = BTF::BTF_KIND_TYPE_TAG;
430   BTFType.Info = Kind << 24;
431 }
432 
433 void BTFTypeTypeTag::completeType(BTFDebug &BDebug) {
434   if (IsCompleted)
435     return;
436   IsCompleted = true;
437   BTFType.NameOff = BDebug.addString(Tag);
438   if (DTy) {
439     const DIType *ResolvedType = DTy->getBaseType();
440     if (!ResolvedType)
441       BTFType.Type = 0;
442     else
443       BTFType.Type = BDebug.getTypeId(ResolvedType);
444   }
445 }
446 
447 uint32_t BTFStringTable::addString(StringRef S) {
448   // Check whether the string already exists.
449   for (auto &OffsetM : OffsetToIdMap) {
450     if (Table[OffsetM.second] == S)
451       return OffsetM.first;
452   }
453   // Not find, add to the string table.
454   uint32_t Offset = Size;
455   OffsetToIdMap[Offset] = Table.size();
456   Table.push_back(std::string(S));
457   Size += S.size() + 1;
458   return Offset;
459 }
460 
461 BTFDebug::BTFDebug(AsmPrinter *AP)
462     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
463       LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
464       MapDefNotCollected(true) {
465   addString("\0");
466 }
467 
468 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry,
469                            const DIType *Ty) {
470   TypeEntry->setId(TypeEntries.size() + 1);
471   uint32_t Id = TypeEntry->getId();
472   DIToIdMap[Ty] = Id;
473   TypeEntries.push_back(std::move(TypeEntry));
474   return Id;
475 }
476 
477 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
478   TypeEntry->setId(TypeEntries.size() + 1);
479   uint32_t Id = TypeEntry->getId();
480   TypeEntries.push_back(std::move(TypeEntry));
481   return Id;
482 }
483 
484 void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
485   // Only int and binary floating point types are supported in BTF.
486   uint32_t Encoding = BTy->getEncoding();
487   std::unique_ptr<BTFTypeBase> TypeEntry;
488   switch (Encoding) {
489   case dwarf::DW_ATE_boolean:
490   case dwarf::DW_ATE_signed:
491   case dwarf::DW_ATE_signed_char:
492   case dwarf::DW_ATE_unsigned:
493   case dwarf::DW_ATE_unsigned_char:
494     // Create a BTF type instance for this DIBasicType and put it into
495     // DIToIdMap for cross-type reference check.
496     TypeEntry = std::make_unique<BTFTypeInt>(
497         Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
498     break;
499   case dwarf::DW_ATE_float:
500     TypeEntry =
501         std::make_unique<BTFTypeFloat>(BTy->getSizeInBits(), BTy->getName());
502     break;
503   default:
504     return;
505   }
506 
507   TypeId = addType(std::move(TypeEntry), BTy);
508 }
509 
510 /// Handle subprogram or subroutine types.
511 void BTFDebug::visitSubroutineType(
512     const DISubroutineType *STy, bool ForSubprog,
513     const std::unordered_map<uint32_t, StringRef> &FuncArgNames,
514     uint32_t &TypeId) {
515   DITypeRefArray Elements = STy->getTypeArray();
516   uint32_t VLen = Elements.size() - 1;
517   if (VLen > BTF::MAX_VLEN)
518     return;
519 
520   // Subprogram has a valid non-zero-length name, and the pointee of
521   // a function pointer has an empty name. The subprogram type will
522   // not be added to DIToIdMap as it should not be referenced by
523   // any other types.
524   auto TypeEntry = std::make_unique<BTFTypeFuncProto>(STy, VLen, FuncArgNames);
525   if (ForSubprog)
526     TypeId = addType(std::move(TypeEntry)); // For subprogram
527   else
528     TypeId = addType(std::move(TypeEntry), STy); // For func ptr
529 
530   // Visit return type and func arg types.
531   for (const auto Element : Elements) {
532     visitTypeEntry(Element);
533   }
534 }
535 
536 void BTFDebug::processDeclAnnotations(DINodeArray Annotations,
537                                       uint32_t BaseTypeId,
538                                       int ComponentIdx) {
539   if (!Annotations)
540      return;
541 
542   for (const Metadata *Annotation : Annotations->operands()) {
543     const MDNode *MD = cast<MDNode>(Annotation);
544     const MDString *Name = cast<MDString>(MD->getOperand(0));
545     if (!Name->getString().equals("btf_decl_tag"))
546       continue;
547 
548     const MDString *Value = cast<MDString>(MD->getOperand(1));
549     auto TypeEntry = std::make_unique<BTFTypeDeclTag>(BaseTypeId, ComponentIdx,
550                                                       Value->getString());
551     addType(std::move(TypeEntry));
552   }
553 }
554 
555 /// Generate btf_type_tag chains.
556 int BTFDebug::genBTFTypeTags(const DIDerivedType *DTy, int BaseTypeId) {
557   SmallVector<const MDString *, 4> MDStrs;
558   DINodeArray Annots = DTy->getAnnotations();
559   if (Annots) {
560     // For type with "int __tag1 __tag2 *p", the MDStrs will have
561     // content: [__tag1, __tag2].
562     for (const Metadata *Annotations : Annots->operands()) {
563       const MDNode *MD = cast<MDNode>(Annotations);
564       const MDString *Name = cast<MDString>(MD->getOperand(0));
565       if (!Name->getString().equals("btf_type_tag"))
566         continue;
567       MDStrs.push_back(cast<MDString>(MD->getOperand(1)));
568     }
569   }
570 
571   if (MDStrs.size() == 0)
572     return -1;
573 
574   // With MDStrs [__tag1, __tag2], the output type chain looks like
575   //   PTR -> __tag2 -> __tag1 -> BaseType
576   // In the below, we construct BTF types with the order of __tag1, __tag2
577   // and PTR.
578   unsigned TmpTypeId;
579   std::unique_ptr<BTFTypeTypeTag> TypeEntry;
580   if (BaseTypeId >= 0)
581     TypeEntry =
582         std::make_unique<BTFTypeTypeTag>(BaseTypeId, MDStrs[0]->getString());
583   else
584     TypeEntry = std::make_unique<BTFTypeTypeTag>(DTy, MDStrs[0]->getString());
585   TmpTypeId = addType(std::move(TypeEntry));
586 
587   for (unsigned I = 1; I < MDStrs.size(); I++) {
588     const MDString *Value = MDStrs[I];
589     TypeEntry = std::make_unique<BTFTypeTypeTag>(TmpTypeId, Value->getString());
590     TmpTypeId = addType(std::move(TypeEntry));
591   }
592   return TmpTypeId;
593 }
594 
595 /// Handle structure/union types.
596 void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
597                                uint32_t &TypeId) {
598   const DINodeArray Elements = CTy->getElements();
599   uint32_t VLen = Elements.size();
600   if (VLen > BTF::MAX_VLEN)
601     return;
602 
603   // Check whether we have any bitfield members or not
604   bool HasBitField = false;
605   for (const auto *Element : Elements) {
606     auto E = cast<DIDerivedType>(Element);
607     if (E->isBitField()) {
608       HasBitField = true;
609       break;
610     }
611   }
612 
613   auto TypeEntry =
614       std::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
615   StructTypes.push_back(TypeEntry.get());
616   TypeId = addType(std::move(TypeEntry), CTy);
617 
618   // Check struct/union annotations
619   processDeclAnnotations(CTy->getAnnotations(), TypeId, -1);
620 
621   // Visit all struct members.
622   int FieldNo = 0;
623   for (const auto *Element : Elements) {
624     const auto Elem = cast<DIDerivedType>(Element);
625     visitTypeEntry(Elem);
626     processDeclAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
627     FieldNo++;
628   }
629 }
630 
631 void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
632   // Visit array element type.
633   uint32_t ElemTypeId;
634   const DIType *ElemType = CTy->getBaseType();
635   visitTypeEntry(ElemType, ElemTypeId, false, false);
636 
637   // Visit array dimensions.
638   DINodeArray Elements = CTy->getElements();
639   for (int I = Elements.size() - 1; I >= 0; --I) {
640     if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
641       if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
642         const DISubrange *SR = cast<DISubrange>(Element);
643         auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
644         int64_t Count = CI->getSExtValue();
645 
646         // For struct s { int b; char c[]; }, the c[] will be represented
647         // as an array with Count = -1.
648         auto TypeEntry =
649             std::make_unique<BTFTypeArray>(ElemTypeId,
650                 Count >= 0 ? Count : 0);
651         if (I == 0)
652           ElemTypeId = addType(std::move(TypeEntry), CTy);
653         else
654           ElemTypeId = addType(std::move(TypeEntry));
655       }
656   }
657 
658   // The array TypeId is the type id of the outermost dimension.
659   TypeId = ElemTypeId;
660 
661   // The IR does not have a type for array index while BTF wants one.
662   // So create an array index type if there is none.
663   if (!ArrayIndexTypeId) {
664     auto TypeEntry = std::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
665                                                    0, "__ARRAY_SIZE_TYPE__");
666     ArrayIndexTypeId = addType(std::move(TypeEntry));
667   }
668 }
669 
670 void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
671   DINodeArray Elements = CTy->getElements();
672   uint32_t VLen = Elements.size();
673   if (VLen > BTF::MAX_VLEN)
674     return;
675 
676   auto TypeEntry = std::make_unique<BTFTypeEnum>(CTy, VLen);
677   TypeId = addType(std::move(TypeEntry), CTy);
678   // No need to visit base type as BTF does not encode it.
679 }
680 
681 /// Handle structure/union forward declarations.
682 void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion,
683                                 uint32_t &TypeId) {
684   auto TypeEntry = std::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
685   TypeId = addType(std::move(TypeEntry), CTy);
686 }
687 
688 /// Handle structure, union, array and enumeration types.
689 void BTFDebug::visitCompositeType(const DICompositeType *CTy,
690                                   uint32_t &TypeId) {
691   auto Tag = CTy->getTag();
692   if (Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
693     // Handle forward declaration differently as it does not have members.
694     if (CTy->isForwardDecl())
695       visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
696     else
697       visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
698   } else if (Tag == dwarf::DW_TAG_array_type)
699     visitArrayType(CTy, TypeId);
700   else if (Tag == dwarf::DW_TAG_enumeration_type)
701     visitEnumType(CTy, TypeId);
702 }
703 
704 /// Handle pointer, typedef, const, volatile, restrict and member types.
705 void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
706                                 bool CheckPointer, bool SeenPointer) {
707   unsigned Tag = DTy->getTag();
708 
709   /// Try to avoid chasing pointees, esp. structure pointees which may
710   /// unnecessary bring in a lot of types.
711   if (CheckPointer && !SeenPointer) {
712     SeenPointer = Tag == dwarf::DW_TAG_pointer_type;
713   }
714 
715   if (CheckPointer && SeenPointer) {
716     const DIType *Base = DTy->getBaseType();
717     if (Base) {
718       if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
719         auto CTag = CTy->getTag();
720         if ((CTag == dwarf::DW_TAG_structure_type ||
721              CTag == dwarf::DW_TAG_union_type) &&
722             !CTy->getName().empty() && !CTy->isForwardDecl()) {
723           /// Find a candidate, generate a fixup. Later on the struct/union
724           /// pointee type will be replaced with either a real type or
725           /// a forward declaration.
726           auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, true);
727           auto &Fixup = FixupDerivedTypes[CTy];
728           Fixup.push_back(std::make_pair(DTy, TypeEntry.get()));
729           TypeId = addType(std::move(TypeEntry), DTy);
730           return;
731         }
732       }
733     }
734   }
735 
736   if (Tag == dwarf::DW_TAG_pointer_type) {
737     int TmpTypeId = genBTFTypeTags(DTy, -1);
738     if (TmpTypeId >= 0) {
739       auto TypeDEntry =
740           std::make_unique<BTFTypeDerived>(TmpTypeId, Tag, DTy->getName());
741       TypeId = addType(std::move(TypeDEntry), DTy);
742     } else {
743       auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
744       TypeId = addType(std::move(TypeEntry), DTy);
745     }
746   } else if (Tag == dwarf::DW_TAG_typedef || Tag == dwarf::DW_TAG_const_type ||
747              Tag == dwarf::DW_TAG_volatile_type ||
748              Tag == dwarf::DW_TAG_restrict_type) {
749     auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
750     TypeId = addType(std::move(TypeEntry), DTy);
751     if (Tag == dwarf::DW_TAG_typedef)
752       processDeclAnnotations(DTy->getAnnotations(), TypeId, -1);
753   } else if (Tag != dwarf::DW_TAG_member) {
754     return;
755   }
756 
757   // Visit base type of pointer, typedef, const, volatile, restrict or
758   // struct/union member.
759   uint32_t TempTypeId = 0;
760   if (Tag == dwarf::DW_TAG_member)
761     visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
762   else
763     visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
764 }
765 
766 void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
767                               bool CheckPointer, bool SeenPointer) {
768   if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
769     TypeId = DIToIdMap[Ty];
770 
771     // To handle the case like the following:
772     //    struct t;
773     //    typedef struct t _t;
774     //    struct s1 { _t *c; };
775     //    int test1(struct s1 *arg) { ... }
776     //
777     //    struct t { int a; int b; };
778     //    struct s2 { _t c; }
779     //    int test2(struct s2 *arg) { ... }
780     //
781     // During traversing test1() argument, "_t" is recorded
782     // in DIToIdMap and a forward declaration fixup is created
783     // for "struct t" to avoid pointee type traversal.
784     //
785     // During traversing test2() argument, even if we see "_t" is
786     // already defined, we should keep moving to eventually
787     // bring in types for "struct t". Otherwise, the "struct s2"
788     // definition won't be correct.
789     //
790     // In the above, we have following debuginfo:
791     //  {ptr, struct_member} ->  typedef -> struct
792     // and BTF type for 'typedef' is generated while 'struct' may
793     // be in FixUp. But let us generalize the above to handle
794     //  {different types} -> [various derived types]+ -> another type.
795     // For example,
796     //  {func_param, struct_member} -> const -> ptr -> volatile -> struct
797     // We will traverse const/ptr/volatile which already have corresponding
798     // BTF types and generate type for 'struct' which might be in Fixup
799     // state.
800     if (Ty && (!CheckPointer || !SeenPointer)) {
801       if (const auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
802         while (DTy) {
803           const DIType *BaseTy = DTy->getBaseType();
804           if (!BaseTy)
805             break;
806 
807           if (DIToIdMap.find(BaseTy) != DIToIdMap.end()) {
808             DTy = dyn_cast<DIDerivedType>(BaseTy);
809           } else {
810             uint32_t TmpTypeId;
811             visitTypeEntry(BaseTy, TmpTypeId, CheckPointer, SeenPointer);
812             break;
813           }
814         }
815       }
816     }
817 
818     return;
819   }
820 
821   if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
822     visitBasicType(BTy, TypeId);
823   else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
824     visitSubroutineType(STy, false, std::unordered_map<uint32_t, StringRef>(),
825                         TypeId);
826   else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
827     visitCompositeType(CTy, TypeId);
828   else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
829     visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
830   else
831     llvm_unreachable("Unknown DIType");
832 }
833 
834 void BTFDebug::visitTypeEntry(const DIType *Ty) {
835   uint32_t TypeId;
836   visitTypeEntry(Ty, TypeId, false, false);
837 }
838 
839 void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
840   if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
841     TypeId = DIToIdMap[Ty];
842     return;
843   }
844 
845   // MapDef type may be a struct type or a non-pointer derived type
846   const DIType *OrigTy = Ty;
847   while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
848     auto Tag = DTy->getTag();
849     if (Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type &&
850         Tag != dwarf::DW_TAG_volatile_type &&
851         Tag != dwarf::DW_TAG_restrict_type)
852       break;
853     Ty = DTy->getBaseType();
854   }
855 
856   const auto *CTy = dyn_cast<DICompositeType>(Ty);
857   if (!CTy)
858     return;
859 
860   auto Tag = CTy->getTag();
861   if (Tag != dwarf::DW_TAG_structure_type || CTy->isForwardDecl())
862     return;
863 
864   // Visit all struct members to ensure pointee type is visited
865   const DINodeArray Elements = CTy->getElements();
866   for (const auto *Element : Elements) {
867     const auto *MemberType = cast<DIDerivedType>(Element);
868     visitTypeEntry(MemberType->getBaseType());
869   }
870 
871   // Visit this type, struct or a const/typedef/volatile/restrict type
872   visitTypeEntry(OrigTy, TypeId, false, false);
873 }
874 
875 /// Read file contents from the actual file or from the source
876 std::string BTFDebug::populateFileContent(const DISubprogram *SP) {
877   auto File = SP->getFile();
878   std::string FileName;
879 
880   if (!File->getFilename().startswith("/") && File->getDirectory().size())
881     FileName = File->getDirectory().str() + "/" + File->getFilename().str();
882   else
883     FileName = std::string(File->getFilename());
884 
885   // No need to populate the contends if it has been populated!
886   if (FileContent.find(FileName) != FileContent.end())
887     return FileName;
888 
889   std::vector<std::string> Content;
890   std::string Line;
891   Content.push_back(Line); // Line 0 for empty string
892 
893   std::unique_ptr<MemoryBuffer> Buf;
894   auto Source = File->getSource();
895   if (Source)
896     Buf = MemoryBuffer::getMemBufferCopy(*Source);
897   else if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
898                MemoryBuffer::getFile(FileName))
899     Buf = std::move(*BufOrErr);
900   if (Buf)
901     for (line_iterator I(*Buf, false), E; I != E; ++I)
902       Content.push_back(std::string(*I));
903 
904   FileContent[FileName] = Content;
905   return FileName;
906 }
907 
908 void BTFDebug::constructLineInfo(const DISubprogram *SP, MCSymbol *Label,
909                                  uint32_t Line, uint32_t Column) {
910   std::string FileName = populateFileContent(SP);
911   BTFLineInfo LineInfo;
912 
913   LineInfo.Label = Label;
914   LineInfo.FileNameOff = addString(FileName);
915   // If file content is not available, let LineOff = 0.
916   if (Line < FileContent[FileName].size())
917     LineInfo.LineOff = addString(FileContent[FileName][Line]);
918   else
919     LineInfo.LineOff = 0;
920   LineInfo.LineNum = Line;
921   LineInfo.ColumnNum = Column;
922   LineInfoTable[SecNameOff].push_back(LineInfo);
923 }
924 
925 void BTFDebug::emitCommonHeader() {
926   OS.AddComment("0x" + Twine::utohexstr(BTF::MAGIC));
927   OS.emitIntValue(BTF::MAGIC, 2);
928   OS.emitInt8(BTF::VERSION);
929   OS.emitInt8(0);
930 }
931 
932 void BTFDebug::emitBTFSection() {
933   // Do not emit section if no types and only "" string.
934   if (!TypeEntries.size() && StringTable.getSize() == 1)
935     return;
936 
937   MCContext &Ctx = OS.getContext();
938   MCSectionELF *Sec = Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0);
939   Sec->setAlignment(Align(4));
940   OS.SwitchSection(Sec);
941 
942   // Emit header.
943   emitCommonHeader();
944   OS.emitInt32(BTF::HeaderSize);
945 
946   uint32_t TypeLen = 0, StrLen;
947   for (const auto &TypeEntry : TypeEntries)
948     TypeLen += TypeEntry->getSize();
949   StrLen = StringTable.getSize();
950 
951   OS.emitInt32(0);
952   OS.emitInt32(TypeLen);
953   OS.emitInt32(TypeLen);
954   OS.emitInt32(StrLen);
955 
956   // Emit type table.
957   for (const auto &TypeEntry : TypeEntries)
958     TypeEntry->emitType(OS);
959 
960   // Emit string table.
961   uint32_t StringOffset = 0;
962   for (const auto &S : StringTable.getTable()) {
963     OS.AddComment("string offset=" + std::to_string(StringOffset));
964     OS.emitBytes(S);
965     OS.emitBytes(StringRef("\0", 1));
966     StringOffset += S.size() + 1;
967   }
968 }
969 
970 void BTFDebug::emitBTFExtSection() {
971   // Do not emit section if empty FuncInfoTable and LineInfoTable
972   // and FieldRelocTable.
973   if (!FuncInfoTable.size() && !LineInfoTable.size() &&
974       !FieldRelocTable.size())
975     return;
976 
977   MCContext &Ctx = OS.getContext();
978   MCSectionELF *Sec = Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0);
979   Sec->setAlignment(Align(4));
980   OS.SwitchSection(Sec);
981 
982   // Emit header.
983   emitCommonHeader();
984   OS.emitInt32(BTF::ExtHeaderSize);
985 
986   // Account for FuncInfo/LineInfo record size as well.
987   uint32_t FuncLen = 4, LineLen = 4;
988   // Do not account for optional FieldReloc.
989   uint32_t FieldRelocLen = 0;
990   for (const auto &FuncSec : FuncInfoTable) {
991     FuncLen += BTF::SecFuncInfoSize;
992     FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
993   }
994   for (const auto &LineSec : LineInfoTable) {
995     LineLen += BTF::SecLineInfoSize;
996     LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
997   }
998   for (const auto &FieldRelocSec : FieldRelocTable) {
999     FieldRelocLen += BTF::SecFieldRelocSize;
1000     FieldRelocLen += FieldRelocSec.second.size() * BTF::BPFFieldRelocSize;
1001   }
1002 
1003   if (FieldRelocLen)
1004     FieldRelocLen += 4;
1005 
1006   OS.emitInt32(0);
1007   OS.emitInt32(FuncLen);
1008   OS.emitInt32(FuncLen);
1009   OS.emitInt32(LineLen);
1010   OS.emitInt32(FuncLen + LineLen);
1011   OS.emitInt32(FieldRelocLen);
1012 
1013   // Emit func_info table.
1014   OS.AddComment("FuncInfo");
1015   OS.emitInt32(BTF::BPFFuncInfoSize);
1016   for (const auto &FuncSec : FuncInfoTable) {
1017     OS.AddComment("FuncInfo section string offset=" +
1018                   std::to_string(FuncSec.first));
1019     OS.emitInt32(FuncSec.first);
1020     OS.emitInt32(FuncSec.second.size());
1021     for (const auto &FuncInfo : FuncSec.second) {
1022       Asm->emitLabelReference(FuncInfo.Label, 4);
1023       OS.emitInt32(FuncInfo.TypeId);
1024     }
1025   }
1026 
1027   // Emit line_info table.
1028   OS.AddComment("LineInfo");
1029   OS.emitInt32(BTF::BPFLineInfoSize);
1030   for (const auto &LineSec : LineInfoTable) {
1031     OS.AddComment("LineInfo section string offset=" +
1032                   std::to_string(LineSec.first));
1033     OS.emitInt32(LineSec.first);
1034     OS.emitInt32(LineSec.second.size());
1035     for (const auto &LineInfo : LineSec.second) {
1036       Asm->emitLabelReference(LineInfo.Label, 4);
1037       OS.emitInt32(LineInfo.FileNameOff);
1038       OS.emitInt32(LineInfo.LineOff);
1039       OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
1040                     std::to_string(LineInfo.ColumnNum));
1041       OS.emitInt32(LineInfo.LineNum << 10 | LineInfo.ColumnNum);
1042     }
1043   }
1044 
1045   // Emit field reloc table.
1046   if (FieldRelocLen) {
1047     OS.AddComment("FieldReloc");
1048     OS.emitInt32(BTF::BPFFieldRelocSize);
1049     for (const auto &FieldRelocSec : FieldRelocTable) {
1050       OS.AddComment("Field reloc section string offset=" +
1051                     std::to_string(FieldRelocSec.first));
1052       OS.emitInt32(FieldRelocSec.first);
1053       OS.emitInt32(FieldRelocSec.second.size());
1054       for (const auto &FieldRelocInfo : FieldRelocSec.second) {
1055         Asm->emitLabelReference(FieldRelocInfo.Label, 4);
1056         OS.emitInt32(FieldRelocInfo.TypeID);
1057         OS.emitInt32(FieldRelocInfo.OffsetNameOff);
1058         OS.emitInt32(FieldRelocInfo.RelocKind);
1059       }
1060     }
1061   }
1062 }
1063 
1064 void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
1065   auto *SP = MF->getFunction().getSubprogram();
1066   auto *Unit = SP->getUnit();
1067 
1068   if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
1069     SkipInstruction = true;
1070     return;
1071   }
1072   SkipInstruction = false;
1073 
1074   // Collect MapDef types. Map definition needs to collect
1075   // pointee types. Do it first. Otherwise, for the following
1076   // case:
1077   //    struct m { ...};
1078   //    struct t {
1079   //      struct m *key;
1080   //    };
1081   //    foo(struct t *arg);
1082   //
1083   //    struct mapdef {
1084   //      ...
1085   //      struct m *key;
1086   //      ...
1087   //    } __attribute__((section(".maps"))) hash_map;
1088   //
1089   // If subroutine foo is traversed first, a type chain
1090   // "ptr->struct m(fwd)" will be created and later on
1091   // when traversing mapdef, since "ptr->struct m" exists,
1092   // the traversal of "struct m" will be omitted.
1093   if (MapDefNotCollected) {
1094     processGlobals(true);
1095     MapDefNotCollected = false;
1096   }
1097 
1098   // Collect all types locally referenced in this function.
1099   // Use RetainedNodes so we can collect all argument names
1100   // even if the argument is not used.
1101   std::unordered_map<uint32_t, StringRef> FuncArgNames;
1102   for (const DINode *DN : SP->getRetainedNodes()) {
1103     if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
1104       // Collect function arguments for subprogram func type.
1105       uint32_t Arg = DV->getArg();
1106       if (Arg) {
1107         visitTypeEntry(DV->getType());
1108         FuncArgNames[Arg] = DV->getName();
1109       }
1110     }
1111   }
1112 
1113   // Construct subprogram func proto type.
1114   uint32_t ProtoTypeId;
1115   visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId);
1116 
1117   // Construct subprogram func type
1118   uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
1119   auto FuncTypeEntry =
1120       std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
1121   uint32_t FuncTypeId = addType(std::move(FuncTypeEntry));
1122 
1123   // Process argument annotations.
1124   for (const DINode *DN : SP->getRetainedNodes()) {
1125     if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
1126       uint32_t Arg = DV->getArg();
1127       if (Arg)
1128         processDeclAnnotations(DV->getAnnotations(), FuncTypeId, Arg - 1);
1129     }
1130   }
1131 
1132   processDeclAnnotations(SP->getAnnotations(), FuncTypeId, -1);
1133 
1134   for (const auto &TypeEntry : TypeEntries)
1135     TypeEntry->completeType(*this);
1136 
1137   // Construct funcinfo and the first lineinfo for the function.
1138   MCSymbol *FuncLabel = Asm->getFunctionBegin();
1139   BTFFuncInfo FuncInfo;
1140   FuncInfo.Label = FuncLabel;
1141   FuncInfo.TypeId = FuncTypeId;
1142   if (FuncLabel->isInSection()) {
1143     MCSection &Section = FuncLabel->getSection();
1144     const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section);
1145     assert(SectionELF && "Null section for Function Label");
1146     SecNameOff = addString(SectionELF->getName());
1147   } else {
1148     SecNameOff = addString(".text");
1149   }
1150   FuncInfoTable[SecNameOff].push_back(FuncInfo);
1151 }
1152 
1153 void BTFDebug::endFunctionImpl(const MachineFunction *MF) {
1154   SkipInstruction = false;
1155   LineInfoGenerated = false;
1156   SecNameOff = 0;
1157 }
1158 
1159 /// On-demand populate types as requested from abstract member
1160 /// accessing or preserve debuginfo type.
1161 unsigned BTFDebug::populateType(const DIType *Ty) {
1162   unsigned Id;
1163   visitTypeEntry(Ty, Id, false, false);
1164   for (const auto &TypeEntry : TypeEntries)
1165     TypeEntry->completeType(*this);
1166   return Id;
1167 }
1168 
1169 /// Generate a struct member field relocation.
1170 void BTFDebug::generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
1171                                      const GlobalVariable *GVar, bool IsAma) {
1172   BTFFieldReloc FieldReloc;
1173   FieldReloc.Label = ORSym;
1174   FieldReloc.TypeID = RootId;
1175 
1176   StringRef AccessPattern = GVar->getName();
1177   size_t FirstDollar = AccessPattern.find_first_of('$');
1178   if (IsAma) {
1179     size_t FirstColon = AccessPattern.find_first_of(':');
1180     size_t SecondColon = AccessPattern.find_first_of(':', FirstColon + 1);
1181     StringRef IndexPattern = AccessPattern.substr(FirstDollar + 1);
1182     StringRef RelocKindStr = AccessPattern.substr(FirstColon + 1,
1183         SecondColon - FirstColon);
1184     StringRef PatchImmStr = AccessPattern.substr(SecondColon + 1,
1185         FirstDollar - SecondColon);
1186 
1187     FieldReloc.OffsetNameOff = addString(IndexPattern);
1188     FieldReloc.RelocKind = std::stoull(std::string(RelocKindStr));
1189     PatchImms[GVar] = std::make_pair(std::stoll(std::string(PatchImmStr)),
1190                                      FieldReloc.RelocKind);
1191   } else {
1192     StringRef RelocStr = AccessPattern.substr(FirstDollar + 1);
1193     FieldReloc.OffsetNameOff = addString("0");
1194     FieldReloc.RelocKind = std::stoull(std::string(RelocStr));
1195     PatchImms[GVar] = std::make_pair(RootId, FieldReloc.RelocKind);
1196   }
1197   FieldRelocTable[SecNameOff].push_back(FieldReloc);
1198 }
1199 
1200 void BTFDebug::processGlobalValue(const MachineOperand &MO) {
1201   // check whether this is a candidate or not
1202   if (MO.isGlobal()) {
1203     const GlobalValue *GVal = MO.getGlobal();
1204     auto *GVar = dyn_cast<GlobalVariable>(GVal);
1205     if (!GVar) {
1206       // Not a global variable. Maybe an extern function reference.
1207       processFuncPrototypes(dyn_cast<Function>(GVal));
1208       return;
1209     }
1210 
1211     if (!GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) &&
1212         !GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr))
1213       return;
1214 
1215     MCSymbol *ORSym = OS.getContext().createTempSymbol();
1216     OS.emitLabel(ORSym);
1217 
1218     MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
1219     uint32_t RootId = populateType(dyn_cast<DIType>(MDN));
1220     generatePatchImmReloc(ORSym, RootId, GVar,
1221                           GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr));
1222   }
1223 }
1224 
1225 void BTFDebug::beginInstruction(const MachineInstr *MI) {
1226   DebugHandlerBase::beginInstruction(MI);
1227 
1228   if (SkipInstruction || MI->isMetaInstruction() ||
1229       MI->getFlag(MachineInstr::FrameSetup))
1230     return;
1231 
1232   if (MI->isInlineAsm()) {
1233     // Count the number of register definitions to find the asm string.
1234     unsigned NumDefs = 0;
1235     for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1236          ++NumDefs)
1237       ;
1238 
1239     // Skip this inline asm instruction if the asmstr is empty.
1240     const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1241     if (AsmStr[0] == 0)
1242       return;
1243   }
1244 
1245   if (MI->getOpcode() == BPF::LD_imm64) {
1246     // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
1247     // add this insn into the .BTF.ext FieldReloc subsection.
1248     // Relocation looks like:
1249     //  . SecName:
1250     //    . InstOffset
1251     //    . TypeID
1252     //    . OffSetNameOff
1253     //    . RelocType
1254     // Later, the insn is replaced with "r2 = <offset>"
1255     // where "<offset>" equals to the offset based on current
1256     // type definitions.
1257     //
1258     // If the insn is "r2 = LD_imm64 @<an TypeIdAttr global>",
1259     // The LD_imm64 result will be replaced with a btf type id.
1260     processGlobalValue(MI->getOperand(1));
1261   } else if (MI->getOpcode() == BPF::CORE_MEM ||
1262              MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1263              MI->getOpcode() == BPF::CORE_SHIFT) {
1264     // relocation insn is a load, store or shift insn.
1265     processGlobalValue(MI->getOperand(3));
1266   } else if (MI->getOpcode() == BPF::JAL) {
1267     // check extern function references
1268     const MachineOperand &MO = MI->getOperand(0);
1269     if (MO.isGlobal()) {
1270       processFuncPrototypes(dyn_cast<Function>(MO.getGlobal()));
1271     }
1272   }
1273 
1274   if (!CurMI) // no debug info
1275     return;
1276 
1277   // Skip this instruction if no DebugLoc or the DebugLoc
1278   // is the same as the previous instruction.
1279   const DebugLoc &DL = MI->getDebugLoc();
1280   if (!DL || PrevInstLoc == DL) {
1281     // This instruction will be skipped, no LineInfo has
1282     // been generated, construct one based on function signature.
1283     if (LineInfoGenerated == false) {
1284       auto *S = MI->getMF()->getFunction().getSubprogram();
1285       MCSymbol *FuncLabel = Asm->getFunctionBegin();
1286       constructLineInfo(S, FuncLabel, S->getLine(), 0);
1287       LineInfoGenerated = true;
1288     }
1289 
1290     return;
1291   }
1292 
1293   // Create a temporary label to remember the insn for lineinfo.
1294   MCSymbol *LineSym = OS.getContext().createTempSymbol();
1295   OS.emitLabel(LineSym);
1296 
1297   // Construct the lineinfo.
1298   auto SP = DL.get()->getScope()->getSubprogram();
1299   constructLineInfo(SP, LineSym, DL.getLine(), DL.getCol());
1300 
1301   LineInfoGenerated = true;
1302   PrevInstLoc = DL;
1303 }
1304 
1305 void BTFDebug::processGlobals(bool ProcessingMapDef) {
1306   // Collect all types referenced by globals.
1307   const Module *M = MMI->getModule();
1308   for (const GlobalVariable &Global : M->globals()) {
1309     // Decide the section name.
1310     StringRef SecName;
1311     if (Global.hasSection()) {
1312       SecName = Global.getSection();
1313     } else if (Global.hasInitializer()) {
1314       // data, bss, or readonly sections
1315       if (Global.isConstant())
1316         SecName = ".rodata";
1317       else
1318         SecName = Global.getInitializer()->isZeroValue() ? ".bss" : ".data";
1319     }
1320 
1321     if (ProcessingMapDef != SecName.startswith(".maps"))
1322       continue;
1323 
1324     // Create a .rodata datasec if the global variable is an initialized
1325     // constant with private linkage and if it won't be in .rodata.str<#>
1326     // and .rodata.cst<#> sections.
1327     if (SecName == ".rodata" && Global.hasPrivateLinkage() &&
1328         DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1329       SectionKind GVKind =
1330           TargetLoweringObjectFile::getKindForGlobal(&Global, Asm->TM);
1331       // skip .rodata.str<#> and .rodata.cst<#> sections
1332       if (!GVKind.isMergeableCString() && !GVKind.isMergeableConst()) {
1333         DataSecEntries[std::string(SecName)] =
1334             std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1335       }
1336     }
1337 
1338     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1339     Global.getDebugInfo(GVs);
1340 
1341     // No type information, mostly internal, skip it.
1342     if (GVs.size() == 0)
1343       continue;
1344 
1345     uint32_t GVTypeId = 0;
1346     DIGlobalVariable *DIGlobal = nullptr;
1347     for (auto *GVE : GVs) {
1348       DIGlobal = GVE->getVariable();
1349       if (SecName.startswith(".maps"))
1350         visitMapDefType(DIGlobal->getType(), GVTypeId);
1351       else
1352         visitTypeEntry(DIGlobal->getType(), GVTypeId, false, false);
1353       break;
1354     }
1355 
1356     // Only support the following globals:
1357     //  . static variables
1358     //  . non-static weak or non-weak global variables
1359     //  . weak or non-weak extern global variables
1360     // Whether DataSec is readonly or not can be found from corresponding ELF
1361     // section flags. Whether a BTF_KIND_VAR is a weak symbol or not
1362     // can be found from the corresponding ELF symbol table.
1363     auto Linkage = Global.getLinkage();
1364     if (Linkage != GlobalValue::InternalLinkage &&
1365         Linkage != GlobalValue::ExternalLinkage &&
1366         Linkage != GlobalValue::WeakAnyLinkage &&
1367         Linkage != GlobalValue::WeakODRLinkage &&
1368         Linkage != GlobalValue::ExternalWeakLinkage)
1369       continue;
1370 
1371     uint32_t GVarInfo;
1372     if (Linkage == GlobalValue::InternalLinkage) {
1373       GVarInfo = BTF::VAR_STATIC;
1374     } else if (Global.hasInitializer()) {
1375       GVarInfo = BTF::VAR_GLOBAL_ALLOCATED;
1376     } else {
1377       GVarInfo = BTF::VAR_GLOBAL_EXTERNAL;
1378     }
1379 
1380     auto VarEntry =
1381         std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
1382     uint32_t VarId = addType(std::move(VarEntry));
1383 
1384     processDeclAnnotations(DIGlobal->getAnnotations(), VarId, -1);
1385 
1386     // An empty SecName means an extern variable without section attribute.
1387     if (SecName.empty())
1388       continue;
1389 
1390     // Find or create a DataSec
1391     if (DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1392       DataSecEntries[std::string(SecName)] =
1393           std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1394     }
1395 
1396     // Calculate symbol size
1397     const DataLayout &DL = Global.getParent()->getDataLayout();
1398     uint32_t Size = DL.getTypeAllocSize(Global.getValueType());
1399 
1400     DataSecEntries[std::string(SecName)]->addDataSecEntry(VarId,
1401         Asm->getSymbol(&Global), Size);
1402   }
1403 }
1404 
1405 /// Emit proper patchable instructions.
1406 bool BTFDebug::InstLower(const MachineInstr *MI, MCInst &OutMI) {
1407   if (MI->getOpcode() == BPF::LD_imm64) {
1408     const MachineOperand &MO = MI->getOperand(1);
1409     if (MO.isGlobal()) {
1410       const GlobalValue *GVal = MO.getGlobal();
1411       auto *GVar = dyn_cast<GlobalVariable>(GVal);
1412       if (GVar) {
1413         // Emit "mov ri, <imm>"
1414         int64_t Imm;
1415         uint32_t Reloc;
1416         if (GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) ||
1417             GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr)) {
1418           Imm = PatchImms[GVar].first;
1419           Reloc = PatchImms[GVar].second;
1420         } else {
1421           return false;
1422         }
1423 
1424         if (Reloc == BPFCoreSharedInfo::ENUM_VALUE_EXISTENCE ||
1425             Reloc == BPFCoreSharedInfo::ENUM_VALUE ||
1426             Reloc == BPFCoreSharedInfo::BTF_TYPE_ID_LOCAL ||
1427             Reloc == BPFCoreSharedInfo::BTF_TYPE_ID_REMOTE)
1428           OutMI.setOpcode(BPF::LD_imm64);
1429         else
1430           OutMI.setOpcode(BPF::MOV_ri);
1431         OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1432         OutMI.addOperand(MCOperand::createImm(Imm));
1433         return true;
1434       }
1435     }
1436   } else if (MI->getOpcode() == BPF::CORE_MEM ||
1437              MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1438              MI->getOpcode() == BPF::CORE_SHIFT) {
1439     const MachineOperand &MO = MI->getOperand(3);
1440     if (MO.isGlobal()) {
1441       const GlobalValue *GVal = MO.getGlobal();
1442       auto *GVar = dyn_cast<GlobalVariable>(GVal);
1443       if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
1444         uint32_t Imm = PatchImms[GVar].first;
1445         OutMI.setOpcode(MI->getOperand(1).getImm());
1446         if (MI->getOperand(0).isImm())
1447           OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
1448         else
1449           OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1450         OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
1451         OutMI.addOperand(MCOperand::createImm(Imm));
1452         return true;
1453       }
1454     }
1455   }
1456   return false;
1457 }
1458 
1459 void BTFDebug::processFuncPrototypes(const Function *F) {
1460   if (!F)
1461     return;
1462 
1463   const DISubprogram *SP = F->getSubprogram();
1464   if (!SP || SP->isDefinition())
1465     return;
1466 
1467   // Do not emit again if already emitted.
1468   if (ProtoFunctions.find(F) != ProtoFunctions.end())
1469     return;
1470   ProtoFunctions.insert(F);
1471 
1472   uint32_t ProtoTypeId;
1473   const std::unordered_map<uint32_t, StringRef> FuncArgNames;
1474   visitSubroutineType(SP->getType(), false, FuncArgNames, ProtoTypeId);
1475 
1476   uint8_t Scope = BTF::FUNC_EXTERN;
1477   auto FuncTypeEntry =
1478       std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
1479   uint32_t FuncId = addType(std::move(FuncTypeEntry));
1480 
1481   processDeclAnnotations(SP->getAnnotations(), FuncId, -1);
1482 
1483   if (F->hasSection()) {
1484     StringRef SecName = F->getSection();
1485 
1486     if (DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1487       DataSecEntries[std::string(SecName)] =
1488           std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1489     }
1490 
1491     // We really don't know func size, set it to 0.
1492     DataSecEntries[std::string(SecName)]->addDataSecEntry(FuncId,
1493         Asm->getSymbol(F), 0);
1494   }
1495 }
1496 
1497 void BTFDebug::endModule() {
1498   // Collect MapDef globals if not collected yet.
1499   if (MapDefNotCollected) {
1500     processGlobals(true);
1501     MapDefNotCollected = false;
1502   }
1503 
1504   // Collect global types/variables except MapDef globals.
1505   processGlobals(false);
1506 
1507   for (auto &DataSec : DataSecEntries)
1508     addType(std::move(DataSec.second));
1509 
1510   // Fixups
1511   for (auto &Fixup : FixupDerivedTypes) {
1512     const DICompositeType *CTy = Fixup.first;
1513     StringRef TypeName = CTy->getName();
1514     bool IsUnion = CTy->getTag() == dwarf::DW_TAG_union_type;
1515 
1516     // Search through struct types
1517     uint32_t StructTypeId = 0;
1518     for (const auto &StructType : StructTypes) {
1519       if (StructType->getName() == TypeName) {
1520         StructTypeId = StructType->getId();
1521         break;
1522       }
1523     }
1524 
1525     if (StructTypeId == 0) {
1526       auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
1527       StructTypeId = addType(std::move(FwdTypeEntry));
1528     }
1529 
1530     for (auto &TypeInfo : Fixup.second) {
1531       const DIDerivedType *DTy = TypeInfo.first;
1532       BTFTypeDerived *BDType = TypeInfo.second;
1533 
1534       int TmpTypeId = genBTFTypeTags(DTy, StructTypeId);
1535       if (TmpTypeId >= 0)
1536         BDType->setPointeeType(TmpTypeId);
1537       else
1538         BDType->setPointeeType(StructTypeId);
1539     }
1540   }
1541 
1542   // Complete BTF type cross refereences.
1543   for (const auto &TypeEntry : TypeEntries)
1544     TypeEntry->completeType(*this);
1545 
1546   // Emit BTF sections.
1547   emitBTFSection();
1548   emitBTFExtSection();
1549 }
1550