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::processAnnotations(DINodeArray Annotations, uint32_t BaseTypeId,
501                                   int ComponentIdx) {
502   if (!Annotations)
503      return;
504 
505   for (const Metadata *Annotation : Annotations->operands()) {
506     const MDNode *MD = cast<MDNode>(Annotation);
507     const MDString *Name = cast<MDString>(MD->getOperand(0));
508     if (!Name->getString().equals("btf_decl_tag"))
509       continue;
510 
511     const MDString *Value = cast<MDString>(MD->getOperand(1));
512     auto TypeEntry = std::make_unique<BTFTypeDeclTag>(BaseTypeId, ComponentIdx,
513                                                       Value->getString());
514     addType(std::move(TypeEntry));
515   }
516 }
517 
518 /// Handle structure/union types.
519 void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
520                                uint32_t &TypeId) {
521   const DINodeArray Elements = CTy->getElements();
522   uint32_t VLen = Elements.size();
523   if (VLen > BTF::MAX_VLEN)
524     return;
525 
526   // Check whether we have any bitfield members or not
527   bool HasBitField = false;
528   for (const auto *Element : Elements) {
529     auto E = cast<DIDerivedType>(Element);
530     if (E->isBitField()) {
531       HasBitField = true;
532       break;
533     }
534   }
535 
536   auto TypeEntry =
537       std::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
538   StructTypes.push_back(TypeEntry.get());
539   TypeId = addType(std::move(TypeEntry), CTy);
540 
541   // Check struct/union annotations
542   processAnnotations(CTy->getAnnotations(), TypeId, -1);
543 
544   // Visit all struct members.
545   int FieldNo = 0;
546   for (const auto *Element : Elements) {
547     const auto Elem = cast<DIDerivedType>(Element);
548     visitTypeEntry(Elem);
549     processAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
550     FieldNo++;
551   }
552 }
553 
554 void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
555   // Visit array element type.
556   uint32_t ElemTypeId;
557   const DIType *ElemType = CTy->getBaseType();
558   visitTypeEntry(ElemType, ElemTypeId, false, false);
559 
560   // Visit array dimensions.
561   DINodeArray Elements = CTy->getElements();
562   for (int I = Elements.size() - 1; I >= 0; --I) {
563     if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
564       if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
565         const DISubrange *SR = cast<DISubrange>(Element);
566         auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
567         int64_t Count = CI->getSExtValue();
568 
569         // For struct s { int b; char c[]; }, the c[] will be represented
570         // as an array with Count = -1.
571         auto TypeEntry =
572             std::make_unique<BTFTypeArray>(ElemTypeId,
573                 Count >= 0 ? Count : 0);
574         if (I == 0)
575           ElemTypeId = addType(std::move(TypeEntry), CTy);
576         else
577           ElemTypeId = addType(std::move(TypeEntry));
578       }
579   }
580 
581   // The array TypeId is the type id of the outermost dimension.
582   TypeId = ElemTypeId;
583 
584   // The IR does not have a type for array index while BTF wants one.
585   // So create an array index type if there is none.
586   if (!ArrayIndexTypeId) {
587     auto TypeEntry = std::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
588                                                    0, "__ARRAY_SIZE_TYPE__");
589     ArrayIndexTypeId = addType(std::move(TypeEntry));
590   }
591 }
592 
593 void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
594   DINodeArray Elements = CTy->getElements();
595   uint32_t VLen = Elements.size();
596   if (VLen > BTF::MAX_VLEN)
597     return;
598 
599   auto TypeEntry = std::make_unique<BTFTypeEnum>(CTy, VLen);
600   TypeId = addType(std::move(TypeEntry), CTy);
601   // No need to visit base type as BTF does not encode it.
602 }
603 
604 /// Handle structure/union forward declarations.
605 void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion,
606                                 uint32_t &TypeId) {
607   auto TypeEntry = std::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
608   TypeId = addType(std::move(TypeEntry), CTy);
609 }
610 
611 /// Handle structure, union, array and enumeration types.
612 void BTFDebug::visitCompositeType(const DICompositeType *CTy,
613                                   uint32_t &TypeId) {
614   auto Tag = CTy->getTag();
615   if (Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
616     // Handle forward declaration differently as it does not have members.
617     if (CTy->isForwardDecl())
618       visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
619     else
620       visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
621   } else if (Tag == dwarf::DW_TAG_array_type)
622     visitArrayType(CTy, TypeId);
623   else if (Tag == dwarf::DW_TAG_enumeration_type)
624     visitEnumType(CTy, TypeId);
625 }
626 
627 /// Handle pointer, typedef, const, volatile, restrict and member types.
628 void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
629                                 bool CheckPointer, bool SeenPointer) {
630   unsigned Tag = DTy->getTag();
631 
632   /// Try to avoid chasing pointees, esp. structure pointees which may
633   /// unnecessary bring in a lot of types.
634   if (CheckPointer && !SeenPointer) {
635     SeenPointer = Tag == dwarf::DW_TAG_pointer_type;
636   }
637 
638   if (CheckPointer && SeenPointer) {
639     const DIType *Base = DTy->getBaseType();
640     if (Base) {
641       if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
642         auto CTag = CTy->getTag();
643         if ((CTag == dwarf::DW_TAG_structure_type ||
644              CTag == dwarf::DW_TAG_union_type) &&
645             !CTy->getName().empty() && !CTy->isForwardDecl()) {
646           /// Find a candidate, generate a fixup. Later on the struct/union
647           /// pointee type will be replaced with either a real type or
648           /// a forward declaration.
649           auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, true);
650           auto &Fixup = FixupDerivedTypes[CTy->getName()];
651           Fixup.first = CTag == dwarf::DW_TAG_union_type;
652           Fixup.second.push_back(TypeEntry.get());
653           TypeId = addType(std::move(TypeEntry), DTy);
654           return;
655         }
656       }
657     }
658   }
659 
660   if (Tag == dwarf::DW_TAG_pointer_type || Tag == dwarf::DW_TAG_typedef ||
661       Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
662       Tag == dwarf::DW_TAG_restrict_type) {
663     auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
664     TypeId = addType(std::move(TypeEntry), DTy);
665   } else if (Tag != dwarf::DW_TAG_member) {
666     return;
667   }
668 
669   // Visit base type of pointer, typedef, const, volatile, restrict or
670   // struct/union member.
671   uint32_t TempTypeId = 0;
672   if (Tag == dwarf::DW_TAG_member)
673     visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
674   else
675     visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
676 }
677 
678 void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
679                               bool CheckPointer, bool SeenPointer) {
680   if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
681     TypeId = DIToIdMap[Ty];
682 
683     // To handle the case like the following:
684     //    struct t;
685     //    typedef struct t _t;
686     //    struct s1 { _t *c; };
687     //    int test1(struct s1 *arg) { ... }
688     //
689     //    struct t { int a; int b; };
690     //    struct s2 { _t c; }
691     //    int test2(struct s2 *arg) { ... }
692     //
693     // During traversing test1() argument, "_t" is recorded
694     // in DIToIdMap and a forward declaration fixup is created
695     // for "struct t" to avoid pointee type traversal.
696     //
697     // During traversing test2() argument, even if we see "_t" is
698     // already defined, we should keep moving to eventually
699     // bring in types for "struct t". Otherwise, the "struct s2"
700     // definition won't be correct.
701     if (Ty && (!CheckPointer || !SeenPointer)) {
702       if (const auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
703         unsigned Tag = DTy->getTag();
704         if (Tag == dwarf::DW_TAG_typedef || Tag == dwarf::DW_TAG_const_type ||
705             Tag == dwarf::DW_TAG_volatile_type ||
706             Tag == dwarf::DW_TAG_restrict_type) {
707           uint32_t TmpTypeId;
708           visitTypeEntry(DTy->getBaseType(), TmpTypeId, CheckPointer,
709                          SeenPointer);
710         }
711       }
712     }
713 
714     return;
715   }
716 
717   if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
718     visitBasicType(BTy, TypeId);
719   else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
720     visitSubroutineType(STy, false, std::unordered_map<uint32_t, StringRef>(),
721                         TypeId);
722   else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
723     visitCompositeType(CTy, TypeId);
724   else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
725     visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
726   else
727     llvm_unreachable("Unknown DIType");
728 }
729 
730 void BTFDebug::visitTypeEntry(const DIType *Ty) {
731   uint32_t TypeId;
732   visitTypeEntry(Ty, TypeId, false, false);
733 }
734 
735 void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
736   if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
737     TypeId = DIToIdMap[Ty];
738     return;
739   }
740 
741   // MapDef type may be a struct type or a non-pointer derived type
742   const DIType *OrigTy = Ty;
743   while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
744     auto Tag = DTy->getTag();
745     if (Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type &&
746         Tag != dwarf::DW_TAG_volatile_type &&
747         Tag != dwarf::DW_TAG_restrict_type)
748       break;
749     Ty = DTy->getBaseType();
750   }
751 
752   const auto *CTy = dyn_cast<DICompositeType>(Ty);
753   if (!CTy)
754     return;
755 
756   auto Tag = CTy->getTag();
757   if (Tag != dwarf::DW_TAG_structure_type || CTy->isForwardDecl())
758     return;
759 
760   // Visit all struct members to ensure pointee type is visited
761   const DINodeArray Elements = CTy->getElements();
762   for (const auto *Element : Elements) {
763     const auto *MemberType = cast<DIDerivedType>(Element);
764     visitTypeEntry(MemberType->getBaseType());
765   }
766 
767   // Visit this type, struct or a const/typedef/volatile/restrict type
768   visitTypeEntry(OrigTy, TypeId, false, false);
769 }
770 
771 /// Read file contents from the actual file or from the source
772 std::string BTFDebug::populateFileContent(const DISubprogram *SP) {
773   auto File = SP->getFile();
774   std::string FileName;
775 
776   if (!File->getFilename().startswith("/") && File->getDirectory().size())
777     FileName = File->getDirectory().str() + "/" + File->getFilename().str();
778   else
779     FileName = std::string(File->getFilename());
780 
781   // No need to populate the contends if it has been populated!
782   if (FileContent.find(FileName) != FileContent.end())
783     return FileName;
784 
785   std::vector<std::string> Content;
786   std::string Line;
787   Content.push_back(Line); // Line 0 for empty string
788 
789   std::unique_ptr<MemoryBuffer> Buf;
790   auto Source = File->getSource();
791   if (Source)
792     Buf = MemoryBuffer::getMemBufferCopy(*Source);
793   else if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
794                MemoryBuffer::getFile(FileName))
795     Buf = std::move(*BufOrErr);
796   if (Buf)
797     for (line_iterator I(*Buf, false), E; I != E; ++I)
798       Content.push_back(std::string(*I));
799 
800   FileContent[FileName] = Content;
801   return FileName;
802 }
803 
804 void BTFDebug::constructLineInfo(const DISubprogram *SP, MCSymbol *Label,
805                                  uint32_t Line, uint32_t Column) {
806   std::string FileName = populateFileContent(SP);
807   BTFLineInfo LineInfo;
808 
809   LineInfo.Label = Label;
810   LineInfo.FileNameOff = addString(FileName);
811   // If file content is not available, let LineOff = 0.
812   if (Line < FileContent[FileName].size())
813     LineInfo.LineOff = addString(FileContent[FileName][Line]);
814   else
815     LineInfo.LineOff = 0;
816   LineInfo.LineNum = Line;
817   LineInfo.ColumnNum = Column;
818   LineInfoTable[SecNameOff].push_back(LineInfo);
819 }
820 
821 void BTFDebug::emitCommonHeader() {
822   OS.AddComment("0x" + Twine::utohexstr(BTF::MAGIC));
823   OS.emitIntValue(BTF::MAGIC, 2);
824   OS.emitInt8(BTF::VERSION);
825   OS.emitInt8(0);
826 }
827 
828 void BTFDebug::emitBTFSection() {
829   // Do not emit section if no types and only "" string.
830   if (!TypeEntries.size() && StringTable.getSize() == 1)
831     return;
832 
833   MCContext &Ctx = OS.getContext();
834   OS.SwitchSection(Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0));
835 
836   // Emit header.
837   emitCommonHeader();
838   OS.emitInt32(BTF::HeaderSize);
839 
840   uint32_t TypeLen = 0, StrLen;
841   for (const auto &TypeEntry : TypeEntries)
842     TypeLen += TypeEntry->getSize();
843   StrLen = StringTable.getSize();
844 
845   OS.emitInt32(0);
846   OS.emitInt32(TypeLen);
847   OS.emitInt32(TypeLen);
848   OS.emitInt32(StrLen);
849 
850   // Emit type table.
851   for (const auto &TypeEntry : TypeEntries)
852     TypeEntry->emitType(OS);
853 
854   // Emit string table.
855   uint32_t StringOffset = 0;
856   for (const auto &S : StringTable.getTable()) {
857     OS.AddComment("string offset=" + std::to_string(StringOffset));
858     OS.emitBytes(S);
859     OS.emitBytes(StringRef("\0", 1));
860     StringOffset += S.size() + 1;
861   }
862 }
863 
864 void BTFDebug::emitBTFExtSection() {
865   // Do not emit section if empty FuncInfoTable and LineInfoTable
866   // and FieldRelocTable.
867   if (!FuncInfoTable.size() && !LineInfoTable.size() &&
868       !FieldRelocTable.size())
869     return;
870 
871   MCContext &Ctx = OS.getContext();
872   OS.SwitchSection(Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0));
873 
874   // Emit header.
875   emitCommonHeader();
876   OS.emitInt32(BTF::ExtHeaderSize);
877 
878   // Account for FuncInfo/LineInfo record size as well.
879   uint32_t FuncLen = 4, LineLen = 4;
880   // Do not account for optional FieldReloc.
881   uint32_t FieldRelocLen = 0;
882   for (const auto &FuncSec : FuncInfoTable) {
883     FuncLen += BTF::SecFuncInfoSize;
884     FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
885   }
886   for (const auto &LineSec : LineInfoTable) {
887     LineLen += BTF::SecLineInfoSize;
888     LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
889   }
890   for (const auto &FieldRelocSec : FieldRelocTable) {
891     FieldRelocLen += BTF::SecFieldRelocSize;
892     FieldRelocLen += FieldRelocSec.second.size() * BTF::BPFFieldRelocSize;
893   }
894 
895   if (FieldRelocLen)
896     FieldRelocLen += 4;
897 
898   OS.emitInt32(0);
899   OS.emitInt32(FuncLen);
900   OS.emitInt32(FuncLen);
901   OS.emitInt32(LineLen);
902   OS.emitInt32(FuncLen + LineLen);
903   OS.emitInt32(FieldRelocLen);
904 
905   // Emit func_info table.
906   OS.AddComment("FuncInfo");
907   OS.emitInt32(BTF::BPFFuncInfoSize);
908   for (const auto &FuncSec : FuncInfoTable) {
909     OS.AddComment("FuncInfo section string offset=" +
910                   std::to_string(FuncSec.first));
911     OS.emitInt32(FuncSec.first);
912     OS.emitInt32(FuncSec.second.size());
913     for (const auto &FuncInfo : FuncSec.second) {
914       Asm->emitLabelReference(FuncInfo.Label, 4);
915       OS.emitInt32(FuncInfo.TypeId);
916     }
917   }
918 
919   // Emit line_info table.
920   OS.AddComment("LineInfo");
921   OS.emitInt32(BTF::BPFLineInfoSize);
922   for (const auto &LineSec : LineInfoTable) {
923     OS.AddComment("LineInfo section string offset=" +
924                   std::to_string(LineSec.first));
925     OS.emitInt32(LineSec.first);
926     OS.emitInt32(LineSec.second.size());
927     for (const auto &LineInfo : LineSec.second) {
928       Asm->emitLabelReference(LineInfo.Label, 4);
929       OS.emitInt32(LineInfo.FileNameOff);
930       OS.emitInt32(LineInfo.LineOff);
931       OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
932                     std::to_string(LineInfo.ColumnNum));
933       OS.emitInt32(LineInfo.LineNum << 10 | LineInfo.ColumnNum);
934     }
935   }
936 
937   // Emit field reloc table.
938   if (FieldRelocLen) {
939     OS.AddComment("FieldReloc");
940     OS.emitInt32(BTF::BPFFieldRelocSize);
941     for (const auto &FieldRelocSec : FieldRelocTable) {
942       OS.AddComment("Field reloc section string offset=" +
943                     std::to_string(FieldRelocSec.first));
944       OS.emitInt32(FieldRelocSec.first);
945       OS.emitInt32(FieldRelocSec.second.size());
946       for (const auto &FieldRelocInfo : FieldRelocSec.second) {
947         Asm->emitLabelReference(FieldRelocInfo.Label, 4);
948         OS.emitInt32(FieldRelocInfo.TypeID);
949         OS.emitInt32(FieldRelocInfo.OffsetNameOff);
950         OS.emitInt32(FieldRelocInfo.RelocKind);
951       }
952     }
953   }
954 }
955 
956 void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
957   auto *SP = MF->getFunction().getSubprogram();
958   auto *Unit = SP->getUnit();
959 
960   if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
961     SkipInstruction = true;
962     return;
963   }
964   SkipInstruction = false;
965 
966   // Collect MapDef types. Map definition needs to collect
967   // pointee types. Do it first. Otherwise, for the following
968   // case:
969   //    struct m { ...};
970   //    struct t {
971   //      struct m *key;
972   //    };
973   //    foo(struct t *arg);
974   //
975   //    struct mapdef {
976   //      ...
977   //      struct m *key;
978   //      ...
979   //    } __attribute__((section(".maps"))) hash_map;
980   //
981   // If subroutine foo is traversed first, a type chain
982   // "ptr->struct m(fwd)" will be created and later on
983   // when traversing mapdef, since "ptr->struct m" exists,
984   // the traversal of "struct m" will be omitted.
985   if (MapDefNotCollected) {
986     processGlobals(true);
987     MapDefNotCollected = false;
988   }
989 
990   // Collect all types locally referenced in this function.
991   // Use RetainedNodes so we can collect all argument names
992   // even if the argument is not used.
993   std::unordered_map<uint32_t, StringRef> FuncArgNames;
994   for (const DINode *DN : SP->getRetainedNodes()) {
995     if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
996       // Collect function arguments for subprogram func type.
997       uint32_t Arg = DV->getArg();
998       if (Arg) {
999         visitTypeEntry(DV->getType());
1000         FuncArgNames[Arg] = DV->getName();
1001       }
1002     }
1003   }
1004 
1005   // Construct subprogram func proto type.
1006   uint32_t ProtoTypeId;
1007   visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId);
1008 
1009   // Construct subprogram func type
1010   uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
1011   auto FuncTypeEntry =
1012       std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
1013   uint32_t FuncTypeId = addType(std::move(FuncTypeEntry));
1014 
1015   // Process argument annotations.
1016   for (const DINode *DN : SP->getRetainedNodes()) {
1017     if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
1018       uint32_t Arg = DV->getArg();
1019       if (Arg)
1020         processAnnotations(DV->getAnnotations(), FuncTypeId, Arg - 1);
1021     }
1022   }
1023 
1024   processAnnotations(SP->getAnnotations(), FuncTypeId, -1);
1025 
1026   for (const auto &TypeEntry : TypeEntries)
1027     TypeEntry->completeType(*this);
1028 
1029   // Construct funcinfo and the first lineinfo for the function.
1030   MCSymbol *FuncLabel = Asm->getFunctionBegin();
1031   BTFFuncInfo FuncInfo;
1032   FuncInfo.Label = FuncLabel;
1033   FuncInfo.TypeId = FuncTypeId;
1034   if (FuncLabel->isInSection()) {
1035     MCSection &Section = FuncLabel->getSection();
1036     const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section);
1037     assert(SectionELF && "Null section for Function Label");
1038     SecNameOff = addString(SectionELF->getName());
1039   } else {
1040     SecNameOff = addString(".text");
1041   }
1042   FuncInfoTable[SecNameOff].push_back(FuncInfo);
1043 }
1044 
1045 void BTFDebug::endFunctionImpl(const MachineFunction *MF) {
1046   SkipInstruction = false;
1047   LineInfoGenerated = false;
1048   SecNameOff = 0;
1049 }
1050 
1051 /// On-demand populate types as requested from abstract member
1052 /// accessing or preserve debuginfo type.
1053 unsigned BTFDebug::populateType(const DIType *Ty) {
1054   unsigned Id;
1055   visitTypeEntry(Ty, Id, false, false);
1056   for (const auto &TypeEntry : TypeEntries)
1057     TypeEntry->completeType(*this);
1058   return Id;
1059 }
1060 
1061 /// Generate a struct member field relocation.
1062 void BTFDebug::generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
1063                                      const GlobalVariable *GVar, bool IsAma) {
1064   BTFFieldReloc FieldReloc;
1065   FieldReloc.Label = ORSym;
1066   FieldReloc.TypeID = RootId;
1067 
1068   StringRef AccessPattern = GVar->getName();
1069   size_t FirstDollar = AccessPattern.find_first_of('$');
1070   if (IsAma) {
1071     size_t FirstColon = AccessPattern.find_first_of(':');
1072     size_t SecondColon = AccessPattern.find_first_of(':', FirstColon + 1);
1073     StringRef IndexPattern = AccessPattern.substr(FirstDollar + 1);
1074     StringRef RelocKindStr = AccessPattern.substr(FirstColon + 1,
1075         SecondColon - FirstColon);
1076     StringRef PatchImmStr = AccessPattern.substr(SecondColon + 1,
1077         FirstDollar - SecondColon);
1078 
1079     FieldReloc.OffsetNameOff = addString(IndexPattern);
1080     FieldReloc.RelocKind = std::stoull(std::string(RelocKindStr));
1081     PatchImms[GVar] = std::make_pair(std::stoll(std::string(PatchImmStr)),
1082                                      FieldReloc.RelocKind);
1083   } else {
1084     StringRef RelocStr = AccessPattern.substr(FirstDollar + 1);
1085     FieldReloc.OffsetNameOff = addString("0");
1086     FieldReloc.RelocKind = std::stoull(std::string(RelocStr));
1087     PatchImms[GVar] = std::make_pair(RootId, FieldReloc.RelocKind);
1088   }
1089   FieldRelocTable[SecNameOff].push_back(FieldReloc);
1090 }
1091 
1092 void BTFDebug::processGlobalValue(const MachineOperand &MO) {
1093   // check whether this is a candidate or not
1094   if (MO.isGlobal()) {
1095     const GlobalValue *GVal = MO.getGlobal();
1096     auto *GVar = dyn_cast<GlobalVariable>(GVal);
1097     if (!GVar) {
1098       // Not a global variable. Maybe an extern function reference.
1099       processFuncPrototypes(dyn_cast<Function>(GVal));
1100       return;
1101     }
1102 
1103     if (!GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) &&
1104         !GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr))
1105       return;
1106 
1107     MCSymbol *ORSym = OS.getContext().createTempSymbol();
1108     OS.emitLabel(ORSym);
1109 
1110     MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
1111     uint32_t RootId = populateType(dyn_cast<DIType>(MDN));
1112     generatePatchImmReloc(ORSym, RootId, GVar,
1113                           GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr));
1114   }
1115 }
1116 
1117 void BTFDebug::beginInstruction(const MachineInstr *MI) {
1118   DebugHandlerBase::beginInstruction(MI);
1119 
1120   if (SkipInstruction || MI->isMetaInstruction() ||
1121       MI->getFlag(MachineInstr::FrameSetup))
1122     return;
1123 
1124   if (MI->isInlineAsm()) {
1125     // Count the number of register definitions to find the asm string.
1126     unsigned NumDefs = 0;
1127     for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1128          ++NumDefs)
1129       ;
1130 
1131     // Skip this inline asm instruction if the asmstr is empty.
1132     const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1133     if (AsmStr[0] == 0)
1134       return;
1135   }
1136 
1137   if (MI->getOpcode() == BPF::LD_imm64) {
1138     // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
1139     // add this insn into the .BTF.ext FieldReloc subsection.
1140     // Relocation looks like:
1141     //  . SecName:
1142     //    . InstOffset
1143     //    . TypeID
1144     //    . OffSetNameOff
1145     //    . RelocType
1146     // Later, the insn is replaced with "r2 = <offset>"
1147     // where "<offset>" equals to the offset based on current
1148     // type definitions.
1149     //
1150     // If the insn is "r2 = LD_imm64 @<an TypeIdAttr global>",
1151     // The LD_imm64 result will be replaced with a btf type id.
1152     processGlobalValue(MI->getOperand(1));
1153   } else if (MI->getOpcode() == BPF::CORE_MEM ||
1154              MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1155              MI->getOpcode() == BPF::CORE_SHIFT) {
1156     // relocation insn is a load, store or shift insn.
1157     processGlobalValue(MI->getOperand(3));
1158   } else if (MI->getOpcode() == BPF::JAL) {
1159     // check extern function references
1160     const MachineOperand &MO = MI->getOperand(0);
1161     if (MO.isGlobal()) {
1162       processFuncPrototypes(dyn_cast<Function>(MO.getGlobal()));
1163     }
1164   }
1165 
1166   if (!CurMI) // no debug info
1167     return;
1168 
1169   // Skip this instruction if no DebugLoc or the DebugLoc
1170   // is the same as the previous instruction.
1171   const DebugLoc &DL = MI->getDebugLoc();
1172   if (!DL || PrevInstLoc == DL) {
1173     // This instruction will be skipped, no LineInfo has
1174     // been generated, construct one based on function signature.
1175     if (LineInfoGenerated == false) {
1176       auto *S = MI->getMF()->getFunction().getSubprogram();
1177       MCSymbol *FuncLabel = Asm->getFunctionBegin();
1178       constructLineInfo(S, FuncLabel, S->getLine(), 0);
1179       LineInfoGenerated = true;
1180     }
1181 
1182     return;
1183   }
1184 
1185   // Create a temporary label to remember the insn for lineinfo.
1186   MCSymbol *LineSym = OS.getContext().createTempSymbol();
1187   OS.emitLabel(LineSym);
1188 
1189   // Construct the lineinfo.
1190   auto SP = DL.get()->getScope()->getSubprogram();
1191   constructLineInfo(SP, LineSym, DL.getLine(), DL.getCol());
1192 
1193   LineInfoGenerated = true;
1194   PrevInstLoc = DL;
1195 }
1196 
1197 void BTFDebug::processGlobals(bool ProcessingMapDef) {
1198   // Collect all types referenced by globals.
1199   const Module *M = MMI->getModule();
1200   for (const GlobalVariable &Global : M->globals()) {
1201     // Decide the section name.
1202     StringRef SecName;
1203     if (Global.hasSection()) {
1204       SecName = Global.getSection();
1205     } else if (Global.hasInitializer()) {
1206       // data, bss, or readonly sections
1207       if (Global.isConstant())
1208         SecName = ".rodata";
1209       else
1210         SecName = Global.getInitializer()->isZeroValue() ? ".bss" : ".data";
1211     }
1212 
1213     if (ProcessingMapDef != SecName.startswith(".maps"))
1214       continue;
1215 
1216     // Create a .rodata datasec if the global variable is an initialized
1217     // constant with private linkage and if it won't be in .rodata.str<#>
1218     // and .rodata.cst<#> sections.
1219     if (SecName == ".rodata" && Global.hasPrivateLinkage() &&
1220         DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1221       SectionKind GVKind =
1222           TargetLoweringObjectFile::getKindForGlobal(&Global, Asm->TM);
1223       // skip .rodata.str<#> and .rodata.cst<#> sections
1224       if (!GVKind.isMergeableCString() && !GVKind.isMergeableConst()) {
1225         DataSecEntries[std::string(SecName)] =
1226             std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1227       }
1228     }
1229 
1230     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1231     Global.getDebugInfo(GVs);
1232 
1233     // No type information, mostly internal, skip it.
1234     if (GVs.size() == 0)
1235       continue;
1236 
1237     uint32_t GVTypeId = 0;
1238     DIGlobalVariable *DIGlobal = nullptr;
1239     for (auto *GVE : GVs) {
1240       DIGlobal = GVE->getVariable();
1241       if (SecName.startswith(".maps"))
1242         visitMapDefType(DIGlobal->getType(), GVTypeId);
1243       else
1244         visitTypeEntry(DIGlobal->getType(), GVTypeId, false, false);
1245       break;
1246     }
1247 
1248     // Only support the following globals:
1249     //  . static variables
1250     //  . non-static weak or non-weak global variables
1251     //  . weak or non-weak extern global variables
1252     // Whether DataSec is readonly or not can be found from corresponding ELF
1253     // section flags. Whether a BTF_KIND_VAR is a weak symbol or not
1254     // can be found from the corresponding ELF symbol table.
1255     auto Linkage = Global.getLinkage();
1256     if (Linkage != GlobalValue::InternalLinkage &&
1257         Linkage != GlobalValue::ExternalLinkage &&
1258         Linkage != GlobalValue::WeakAnyLinkage &&
1259         Linkage != GlobalValue::WeakODRLinkage &&
1260         Linkage != GlobalValue::ExternalWeakLinkage)
1261       continue;
1262 
1263     uint32_t GVarInfo;
1264     if (Linkage == GlobalValue::InternalLinkage) {
1265       GVarInfo = BTF::VAR_STATIC;
1266     } else if (Global.hasInitializer()) {
1267       GVarInfo = BTF::VAR_GLOBAL_ALLOCATED;
1268     } else {
1269       GVarInfo = BTF::VAR_GLOBAL_EXTERNAL;
1270     }
1271 
1272     auto VarEntry =
1273         std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
1274     uint32_t VarId = addType(std::move(VarEntry));
1275 
1276     processAnnotations(DIGlobal->getAnnotations(), VarId, -1);
1277 
1278     // An empty SecName means an extern variable without section attribute.
1279     if (SecName.empty())
1280       continue;
1281 
1282     // Find or create a DataSec
1283     if (DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1284       DataSecEntries[std::string(SecName)] =
1285           std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1286     }
1287 
1288     // Calculate symbol size
1289     const DataLayout &DL = Global.getParent()->getDataLayout();
1290     uint32_t Size = DL.getTypeAllocSize(Global.getType()->getElementType());
1291 
1292     DataSecEntries[std::string(SecName)]->addDataSecEntry(VarId,
1293         Asm->getSymbol(&Global), Size);
1294   }
1295 }
1296 
1297 /// Emit proper patchable instructions.
1298 bool BTFDebug::InstLower(const MachineInstr *MI, MCInst &OutMI) {
1299   if (MI->getOpcode() == BPF::LD_imm64) {
1300     const MachineOperand &MO = MI->getOperand(1);
1301     if (MO.isGlobal()) {
1302       const GlobalValue *GVal = MO.getGlobal();
1303       auto *GVar = dyn_cast<GlobalVariable>(GVal);
1304       if (GVar) {
1305         // Emit "mov ri, <imm>"
1306         int64_t Imm;
1307         uint32_t Reloc;
1308         if (GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) ||
1309             GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr)) {
1310           Imm = PatchImms[GVar].first;
1311           Reloc = PatchImms[GVar].second;
1312         } else {
1313           return false;
1314         }
1315 
1316         if (Reloc == BPFCoreSharedInfo::ENUM_VALUE_EXISTENCE ||
1317             Reloc == BPFCoreSharedInfo::ENUM_VALUE ||
1318             Reloc == BPFCoreSharedInfo::BTF_TYPE_ID_LOCAL ||
1319             Reloc == BPFCoreSharedInfo::BTF_TYPE_ID_REMOTE)
1320           OutMI.setOpcode(BPF::LD_imm64);
1321         else
1322           OutMI.setOpcode(BPF::MOV_ri);
1323         OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1324         OutMI.addOperand(MCOperand::createImm(Imm));
1325         return true;
1326       }
1327     }
1328   } else if (MI->getOpcode() == BPF::CORE_MEM ||
1329              MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1330              MI->getOpcode() == BPF::CORE_SHIFT) {
1331     const MachineOperand &MO = MI->getOperand(3);
1332     if (MO.isGlobal()) {
1333       const GlobalValue *GVal = MO.getGlobal();
1334       auto *GVar = dyn_cast<GlobalVariable>(GVal);
1335       if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
1336         uint32_t Imm = PatchImms[GVar].first;
1337         OutMI.setOpcode(MI->getOperand(1).getImm());
1338         if (MI->getOperand(0).isImm())
1339           OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
1340         else
1341           OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1342         OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
1343         OutMI.addOperand(MCOperand::createImm(Imm));
1344         return true;
1345       }
1346     }
1347   }
1348   return false;
1349 }
1350 
1351 void BTFDebug::processFuncPrototypes(const Function *F) {
1352   if (!F)
1353     return;
1354 
1355   const DISubprogram *SP = F->getSubprogram();
1356   if (!SP || SP->isDefinition())
1357     return;
1358 
1359   // Do not emit again if already emitted.
1360   if (ProtoFunctions.find(F) != ProtoFunctions.end())
1361     return;
1362   ProtoFunctions.insert(F);
1363 
1364   uint32_t ProtoTypeId;
1365   const std::unordered_map<uint32_t, StringRef> FuncArgNames;
1366   visitSubroutineType(SP->getType(), false, FuncArgNames, ProtoTypeId);
1367 
1368   uint8_t Scope = BTF::FUNC_EXTERN;
1369   auto FuncTypeEntry =
1370       std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
1371   uint32_t FuncId = addType(std::move(FuncTypeEntry));
1372 
1373   processAnnotations(SP->getAnnotations(), FuncId, -1);
1374 
1375   if (F->hasSection()) {
1376     StringRef SecName = F->getSection();
1377 
1378     if (DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1379       DataSecEntries[std::string(SecName)] =
1380           std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1381     }
1382 
1383     // We really don't know func size, set it to 0.
1384     DataSecEntries[std::string(SecName)]->addDataSecEntry(FuncId,
1385         Asm->getSymbol(F), 0);
1386   }
1387 }
1388 
1389 void BTFDebug::endModule() {
1390   // Collect MapDef globals if not collected yet.
1391   if (MapDefNotCollected) {
1392     processGlobals(true);
1393     MapDefNotCollected = false;
1394   }
1395 
1396   // Collect global types/variables except MapDef globals.
1397   processGlobals(false);
1398 
1399   for (auto &DataSec : DataSecEntries)
1400     addType(std::move(DataSec.second));
1401 
1402   // Fixups
1403   for (auto &Fixup : FixupDerivedTypes) {
1404     StringRef TypeName = Fixup.first;
1405     bool IsUnion = Fixup.second.first;
1406 
1407     // Search through struct types
1408     uint32_t StructTypeId = 0;
1409     for (const auto &StructType : StructTypes) {
1410       if (StructType->getName() == TypeName) {
1411         StructTypeId = StructType->getId();
1412         break;
1413       }
1414     }
1415 
1416     if (StructTypeId == 0) {
1417       auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
1418       StructTypeId = addType(std::move(FwdTypeEntry));
1419     }
1420 
1421     for (auto &DType : Fixup.second.second) {
1422       DType->setPointeeType(StructTypeId);
1423     }
1424   }
1425 
1426   // Complete BTF type cross refereences.
1427   for (const auto &TypeEntry : TypeEntries)
1428     TypeEntry->completeType(*this);
1429 
1430   // Emit BTF sections.
1431   emitBTFSection();
1432   emitBTFExtSection();
1433 }
1434