BTFDebug.cpp 51 KB

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