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