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