LLVM 23.0.0git
BTFDebug.cpp
Go to the documentation of this file.
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"
25#include "llvm/IR/Module.h"
26#include "llvm/MC/MCContext.h"
29#include "llvm/MC/MCStreamer.h"
30#include "llvm/Support/Debug.h"
36#include <optional>
37
38using namespace llvm;
39
40#define DEBUG_TYPE "btf-debug"
41
42#define GET_CC_REGISTER_LISTS
43#include "BPFGenCallingConv.inc"
44
45static const char *BTFKindStr[] = {
46#define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
47#include "llvm/DebugInfo/BTF/BTF.def"
48};
49
50static const DIType *tryRemoveAtomicType(const DIType *Ty) {
51 if (!Ty)
52 return Ty;
53 auto DerivedTy = dyn_cast<DIDerivedType>(Ty);
54 if (DerivedTy && DerivedTy->getTag() == dwarf::DW_TAG_atomic_type)
55 return DerivedTy->getBaseType();
56 return Ty;
57}
58
59static const DIType *stripDITypeAttributes(const DIType *Ty) {
60 while (const auto *DTy = dyn_cast_or_null<DIDerivedType>(Ty)) {
61 switch (DTy->getTag()) {
62 case dwarf::DW_TAG_atomic_type:
63 case dwarf::DW_TAG_const_type:
64 case dwarf::DW_TAG_restrict_type:
65 case dwarf::DW_TAG_typedef:
66 case dwarf::DW_TAG_volatile_type:
67 Ty = DTy->getBaseType();
68 break;
69 default:
70 return Ty;
71 }
72 }
73 return Ty;
74}
75
76static bool sourceArgMatchesIRType(const DIType *SourceTy, Type *IRTy) {
77 SourceTy = stripDITypeAttributes(SourceTy);
78
79 // All pointers are opaque in LLVM IR, so any source-level pointer matches any
80 // IR pointer regardless of pointee type.
81 if (const auto *DTy = dyn_cast<DIDerivedType>(SourceTy))
82 return DTy->getTag() == dwarf::DW_TAG_pointer_type && IRTy->isPointerTy();
83
84 if (const auto *BTy = dyn_cast<DIBasicType>(SourceTy)) {
85 uint64_t SizeInBits = BTy->getSizeInBits();
86 if (BTy->getEncoding() == dwarf::DW_ATE_float)
87 return IRTy->isFloatingPointTy() &&
88 IRTy->getPrimitiveSizeInBits() == SizeInBits;
89 // _Bool is 8 bits in DWARF/source but lowered to i1 in LLVM IR.
90 if (BTy->getEncoding() == dwarf::DW_ATE_boolean && IRTy->isIntegerTy(1))
91 return true;
92 return IRTy->isIntegerTy(SizeInBits);
93 }
94
95 const auto *CTy = dyn_cast<DICompositeType>(SourceTy);
96 if (!CTy)
97 return false;
98
99 switch (CTy->getTag()) {
100 case dwarf::DW_TAG_enumeration_type:
101 return IRTy->isIntegerTy(CTy->getSizeInBits());
102 default:
103 return false;
104 }
105}
106
107/// Collect the physical register each source argument lives in by scanning
108/// DBG_VALUE instructions in the entry block. A DBG_VALUE is only recorded
109/// when its register either (a) has not been redefined by any preceding
110/// non-debug instruction (i.e. it still holds the caller-passed value), or
111/// (b) was most recently loaded from the stack via $r11 (a stack-passed
112/// argument beyond the first five register args).
113///
114/// There is another case where DBG_VALUE is not emitted due to
115/// AssignmentTrackingAnalysis which determines that a variable is
116/// always stack-homed, and describes the variable via MachineFunction's
117/// VariableDbgInfo (setVariableDbgInfo with a frame index). To recover the
118/// register for those arguments, we also track stores of un-redefined physical
119/// registers to stack frame objects during the entry-block walk (using
120/// MachineMemOperands to identify the target frame index), then match them
121/// against VariableDbgInfo entries after the scan.
125 const DISubprogram *SP = MF.getFunction().getSubprogram();
126 SmallDenseSet<Register> DefinedRegs, StackLoadRegs;
127
128 // Build a reverse map from IR alloca to frame index so we can
129 // identify which frame object a store targets via its MachineMemOperand.
130 const MachineFrameInfo &MFI = MF.getFrameInfo();
132 for (int I = 0, N = MFI.getObjectIndexEnd(); I < N; ++I)
133 if (const AllocaInst *AI = MFI.getObjectAllocation(I))
134 AllocaToFI[AI] = I;
135
136 // Maps frame index → first physical register stored there before
137 // that register is redefined.
138 SmallDenseMap<int, Register> FrameIndexToReg;
139
140 for (const MachineInstr &MI : MF.front()) {
141 if (MI.isDebugValue()) {
142 // Skip indirect DBG_VALUEs — the register is a base address for a
143 // memory location, not the argument value itself.
144 if (MI.isIndirectDebugValue())
145 continue;
146
147 const DILocalVariable *DV = MI.getDebugVariable();
148 if (!DV || !DV->getArg() || DV->getScope()->getSubprogram() != SP)
149 continue;
150
151 uint32_t Arg = DV->getArg();
152 const MachineOperand &MO = MI.getDebugOperand(0);
153 if (!MO.isReg() || !MO.getReg().isPhysical())
154 continue;
155
156 if (!DefinedRegs.contains(MO.getReg()) ||
157 StackLoadRegs.contains(MO.getReg()))
158 EntryRegMap[Arg] = MO.getReg();
159 continue;
160 }
161
162 // Track stores of unredefined physical registers to stack frame
163 // objects. Use MachineMemOperands to identify the target frame
164 // index rather than assuming a particular addressing mode.
165 if (MI.mayStore() && !MI.isCall() && MI.getOperand(0).isReg()) {
166 Register SrcReg = MI.getOperand(0).getReg();
167 if (SrcReg.isPhysical() && !DefinedRegs.contains(SrcReg)) {
168 for (const MachineMemOperand *MMO : MI.memoperands()) {
169 const Value *V = MMO->getValue();
170 if (!V)
171 continue;
172 auto It = AllocaToFI.find(V);
173 if (It != AllocaToFI.end())
174 FrameIndexToReg.try_emplace(It->second, SrcReg);
175 }
176 }
177 }
178
179 for (const MachineOperand &MO : MI.operands())
180 if (MO.isReg() && MO.isDef() && MO.getReg().isPhysical()) {
181 DefinedRegs.insert(MO.getReg());
182 StackLoadRegs.erase(MO.getReg());
183 }
184
185 // Detect stack argument loads: $rX = LDD $r11, offset.
186 if (MI.getOpcode() == BPF::LDD && MI.getOperand(1).getReg() == BPF::R11)
187 StackLoadRegs.insert(MI.getOperand(0).getReg());
188 }
189
190 // Check VariableDbgInfo for args that AssignmentTrackingAnalysis described
191 // via setVariableDbgInfo (single-loc stack-homed variables) rather than
192 // DBG_VALUE instructions.
193 for (const auto &VI : MF.getVariableDbgInfo()) {
194 if (!VI.Var || !VI.Var->getArg() || !VI.inStackSlot())
195 continue;
196 if (VI.Var->getScope()->getSubprogram() != SP)
197 continue;
198 uint32_t Arg = VI.Var->getArg();
199 if (EntryRegMap.count(Arg))
200 continue;
201 auto It = FrameIndexToReg.find(VI.getStackSlot());
202 if (It != FrameIndexToReg.end())
203 EntryRegMap[Arg] = It->second;
204 }
205
206 SmallVector<std::pair<uint32_t, Register>, 8> AliveArgs(EntryRegMap.begin(),
207 EntryRegMap.end());
208 llvm::sort(AliveArgs, llvm::less_first());
209 return AliveArgs;
210}
211
212/// Check whether the optimized IR signature matches the surviving source
213/// arguments precisely enough to emit a filtered BTF prototype.
214/// Requires exact IR/source arg count match, matching types, and correct
215/// BPF register order (R1..R5) for register args.
217 const MachineFunction &MF, DITypeArray Elements,
218 ArrayRef<std::pair<uint32_t, Register>> AliveArgs,
219 const TargetRegisterInfo &TRI) {
220 if (MF.getFunction().arg_size() != AliveArgs.size()) {
221 LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName() << ": IR arg count ("
222 << MF.getFunction().arg_size() << ") != alive arg count ("
223 << AliveArgs.size() << ")\n");
224 return false;
225 }
226
227 auto ArgIt = MF.getFunction().arg_begin();
228 for (unsigned I = 0, N = AliveArgs.size(); I < N; ++I, ++ArgIt) {
229 auto [ArgNo, Reg] = AliveArgs[I];
230 if (!sourceArgMatchesIRType(Elements[ArgNo], ArgIt->getType())) {
231 LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName()
232 << ": type mismatch for source arg " << ArgNo
233 << " at IR position " << I << "\n");
234 return false;
235 }
236
237 if (I >= std::size(CC_BPF64_ArgRegs))
238 continue;
239
240 int DwarfReg = TRI.getDwarfRegNum(Reg, false);
241 if (DwarfReg != static_cast<int>(I + 1)) {
242 LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName() << ": arg " << ArgNo
243 << " in DWARF reg " << DwarfReg << ", expected "
244 << (I + 1) << "\n");
245 return false;
246 }
247 }
248
249 return true;
250}
251
252/// Emit a BTF common type.
254 OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
255 ")");
256 OS.emitInt32(BTFType.NameOff);
257 OS.AddComment("0x" + Twine::utohexstr(BTFType.Info));
258 OS.emitInt32(BTFType.Info);
259 OS.emitInt32(BTFType.Size);
260}
261
263 bool NeedsFixup)
264 : DTy(DTy), NeedsFixup(NeedsFixup), Name(DTy->getName()) {
265 switch (Tag) {
266 case dwarf::DW_TAG_pointer_type:
267 Kind = BTF::BTF_KIND_PTR;
268 break;
269 case dwarf::DW_TAG_const_type:
270 Kind = BTF::BTF_KIND_CONST;
271 break;
272 case dwarf::DW_TAG_volatile_type:
273 Kind = BTF::BTF_KIND_VOLATILE;
274 break;
275 case dwarf::DW_TAG_typedef:
276 Kind = BTF::BTF_KIND_TYPEDEF;
277 break;
278 case dwarf::DW_TAG_restrict_type:
279 Kind = BTF::BTF_KIND_RESTRICT;
280 break;
281 default:
282 llvm_unreachable("Unknown DIDerivedType Tag");
283 }
284 BTFType.Info = Kind << 24;
285}
286
287/// Used by DW_TAG_pointer_type only.
288BTFTypeDerived::BTFTypeDerived(unsigned NextTypeId, unsigned Tag,
289 StringRef Name)
290 : DTy(nullptr), NeedsFixup(false), Name(Name) {
291 Kind = BTF::BTF_KIND_PTR;
292 BTFType.Info = Kind << 24;
293 BTFType.Type = NextTypeId;
294}
295
297 if (IsCompleted)
298 return;
299 IsCompleted = true;
300
301 switch (Kind) {
302 case BTF::BTF_KIND_PTR:
303 case BTF::BTF_KIND_CONST:
304 case BTF::BTF_KIND_VOLATILE:
305 case BTF::BTF_KIND_RESTRICT:
306 // Debug info might contain names for these types, but given that we want
307 // to keep BTF minimal and naming reference types doesn't bring any value
308 // (what matters is the completeness of the base type), we don't emit them.
309 //
310 // Furthermore, the Linux kernel refuses to load BPF programs that contain
311 // BTF with these types named:
312 // https://elixir.bootlin.com/linux/v6.17.1/source/kernel/bpf/btf.c#L2586
313 BTFType.NameOff = 0;
314 break;
315 default:
316 BTFType.NameOff = BDebug.addString(Name);
317 break;
318 }
319
320 if (NeedsFixup || !DTy)
321 return;
322
323 // The base type for PTR/CONST/VOLATILE could be void.
324 const DIType *ResolvedType = tryRemoveAtomicType(DTy->getBaseType());
325 if (!ResolvedType) {
326 assert((Kind == BTF::BTF_KIND_PTR || Kind == BTF::BTF_KIND_CONST ||
327 Kind == BTF::BTF_KIND_VOLATILE) &&
328 "Invalid null basetype");
329 BTFType.Type = 0;
330 } else {
331 BTFType.Type = BDebug.getTypeId(ResolvedType);
332 }
333}
334
336
338 BTFType.Type = PointeeType;
339}
340
341/// Represent a struct/union forward declaration.
342BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion) : Name(Name) {
343 Kind = BTF::BTF_KIND_FWD;
344 BTFType.Info = IsUnion << 31 | Kind << 24;
345 BTFType.Type = 0;
346}
347
349 if (IsCompleted)
350 return;
351 IsCompleted = true;
352
353 BTFType.NameOff = BDebug.addString(Name);
354}
355
357
359 uint32_t OffsetInBits, StringRef TypeName)
360 : Name(TypeName) {
361 // Translate IR int encoding to BTF int encoding.
362 uint8_t BTFEncoding;
363 switch (Encoding) {
364 case dwarf::DW_ATE_boolean:
365 BTFEncoding = BTF::INT_BOOL;
366 break;
367 case dwarf::DW_ATE_signed:
368 case dwarf::DW_ATE_signed_char:
369 BTFEncoding = BTF::INT_SIGNED;
370 break;
371 case dwarf::DW_ATE_unsigned:
372 case dwarf::DW_ATE_unsigned_char:
373 case dwarf::DW_ATE_UTF:
374 BTFEncoding = 0;
375 break;
376 default:
377 llvm_unreachable("Unknown BTFTypeInt Encoding");
378 }
379
380 Kind = BTF::BTF_KIND_INT;
381 BTFType.Info = Kind << 24;
382 BTFType.Size = roundupToBytes(SizeInBits);
383 IntVal = (BTFEncoding << 24) | OffsetInBits << 16 | SizeInBits;
384}
385
387 if (IsCompleted)
388 return;
389 IsCompleted = true;
390
391 BTFType.NameOff = BDebug.addString(Name);
392}
393
396 OS.AddComment("0x" + Twine::utohexstr(IntVal));
397 OS.emitInt32(IntVal);
398}
399
401 bool IsSigned) : ETy(ETy) {
402 Kind = BTF::BTF_KIND_ENUM;
403 BTFType.Info = IsSigned << 31 | Kind << 24 | VLen;
404 BTFType.Size = roundupToBytes(ETy->getSizeInBits());
405}
406
408 if (IsCompleted)
409 return;
410 IsCompleted = true;
411
412 BTFType.NameOff = BDebug.addString(ETy->getName());
413
414 DINodeArray Elements = ETy->getElements();
415 for (const auto Element : Elements) {
416 const auto *Enum = cast<DIEnumerator>(Element);
417
418 struct BTF::BTFEnum BTFEnum;
419 BTFEnum.NameOff = BDebug.addString(Enum->getName());
420 // BTF enum value is 32bit, enforce it.
422 if (Enum->isUnsigned())
423 Value = static_cast<uint32_t>(Enum->getValue().getZExtValue());
424 else
425 Value = static_cast<uint32_t>(Enum->getValue().getSExtValue());
426 BTFEnum.Val = Value;
427 EnumValues.push_back(BTFEnum);
428 }
429}
430
433 for (const auto &Enum : EnumValues) {
434 OS.emitInt32(Enum.NameOff);
435 OS.emitInt32(Enum.Val);
436 }
437}
438
440 bool IsSigned) : ETy(ETy) {
441 Kind = BTF::BTF_KIND_ENUM64;
442 BTFType.Info = IsSigned << 31 | Kind << 24 | VLen;
443 BTFType.Size = roundupToBytes(ETy->getSizeInBits());
444}
445
447 if (IsCompleted)
448 return;
449 IsCompleted = true;
450
451 BTFType.NameOff = BDebug.addString(ETy->getName());
452
453 DINodeArray Elements = ETy->getElements();
454 for (const auto Element : Elements) {
455 const auto *Enum = cast<DIEnumerator>(Element);
456
457 struct BTF::BTFEnum64 BTFEnum;
458 BTFEnum.NameOff = BDebug.addString(Enum->getName());
460 if (Enum->isUnsigned())
461 Value = Enum->getValue().getZExtValue();
462 else
463 Value = static_cast<uint64_t>(Enum->getValue().getSExtValue());
464 BTFEnum.Val_Lo32 = Value;
465 BTFEnum.Val_Hi32 = Value >> 32;
466 EnumValues.push_back(BTFEnum);
467 }
468}
469
472 for (const auto &Enum : EnumValues) {
473 OS.emitInt32(Enum.NameOff);
474 OS.AddComment("0x" + Twine::utohexstr(Enum.Val_Lo32));
475 OS.emitInt32(Enum.Val_Lo32);
476 OS.AddComment("0x" + Twine::utohexstr(Enum.Val_Hi32));
477 OS.emitInt32(Enum.Val_Hi32);
478 }
479}
480
482 Kind = BTF::BTF_KIND_ARRAY;
483 BTFType.NameOff = 0;
484 BTFType.Info = Kind << 24;
485 BTFType.Size = 0;
486
487 ArrayInfo.ElemType = ElemTypeId;
488 ArrayInfo.Nelems = NumElems;
489}
490
491/// Represent a BTF array.
493 if (IsCompleted)
494 return;
495 IsCompleted = true;
496
497 // The IR does not really have a type for the index.
498 // A special type for array index should have been
499 // created during initial type traversal. Just
500 // retrieve that type id.
501 ArrayInfo.IndexType = BDebug.getArrayIndexTypeId();
502}
503
506 OS.emitInt32(ArrayInfo.ElemType);
507 OS.emitInt32(ArrayInfo.IndexType);
508 OS.emitInt32(ArrayInfo.Nelems);
509}
510
511/// Represent either a struct or a union.
513 bool HasBitField, uint32_t Vlen)
514 : STy(STy), HasBitField(HasBitField) {
515 Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION;
516 BTFType.Size = roundupToBytes(STy->getSizeInBits());
517 BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen;
518}
519
521 if (IsCompleted)
522 return;
523 IsCompleted = true;
524
525 BTFType.NameOff = BDebug.addString(STy->getName());
526
527 if (STy->getTag() == dwarf::DW_TAG_variant_part) {
528 // Variant parts might have a discriminator, which has its own memory
529 // location, and variants, which share the memory location afterwards. LLVM
530 // DI doesn't consider discriminator as an element and instead keeps
531 // it as a separate reference.
532 // To keep BTF simple, let's represent the structure as an union with
533 // discriminator as the first element.
534 // The offsets inside variant types are already handled correctly in the
535 // DI.
536 const auto *DTy = STy->getDiscriminator();
537 if (DTy) {
538 struct BTF::BTFMember Discriminator;
539
540 Discriminator.NameOff = BDebug.addString(DTy->getName());
541 Discriminator.Offset = DTy->getOffsetInBits();
542 const auto *BaseTy = DTy->getBaseType();
543 Discriminator.Type = BDebug.getTypeId(BaseTy);
544
545 Members.push_back(Discriminator);
546 }
547 }
548
549 // Add struct/union members.
550 const DINodeArray Elements = STy->getElements();
551 for (const auto *Element : Elements) {
552 struct BTF::BTFMember BTFMember;
553
554 switch (Element->getTag()) {
555 case dwarf::DW_TAG_member: {
556 const auto *DDTy = cast<DIDerivedType>(Element);
557
558 BTFMember.NameOff = BDebug.addString(DDTy->getName());
559 if (HasBitField) {
560 uint8_t BitFieldSize = DDTy->isBitField() ? DDTy->getSizeInBits() : 0;
561 BTFMember.Offset = BitFieldSize << 24 | DDTy->getOffsetInBits();
562 } else {
563 BTFMember.Offset = DDTy->getOffsetInBits();
564 }
565 const auto *BaseTy = tryRemoveAtomicType(DDTy->getBaseType());
566 BTFMember.Type = BDebug.getTypeId(BaseTy);
567 break;
568 }
569 case dwarf::DW_TAG_variant_part: {
570 const auto *DCTy = dyn_cast<DICompositeType>(Element);
571
572 BTFMember.NameOff = BDebug.addString(DCTy->getName());
573 BTFMember.Offset = DCTy->getOffsetInBits();
574 BTFMember.Type = BDebug.getTypeId(DCTy);
575 break;
576 }
577 default:
578 llvm_unreachable("Unexpected DI tag of a struct/union element");
579 }
580 Members.push_back(BTFMember);
581 }
582}
583
586 for (const auto &Member : Members) {
587 OS.emitInt32(Member.NameOff);
588 OS.emitInt32(Member.Type);
589 OS.AddComment("0x" + Twine::utohexstr(Member.Offset));
590 OS.emitInt32(Member.Offset);
591 }
592}
593
594std::string BTFTypeStruct::getName() { return std::string(STy->getName()); }
595
596/// The Func kind represents both subprogram and pointee of function
597/// pointers. If the FuncName is empty, it represents a pointee of function
598/// pointer. Otherwise, it represents a subprogram. The func arg names
599/// are empty for pointee of function pointer case, and are valid names
600/// for subprogram.
602 const DISubroutineType *STy, uint32_t VLen,
603 const SmallDenseMap<uint32_t, StringRef> &FuncArgNames,
604 bool UseFilteredParams, ArrayRef<uint32_t> AliveParamIndices,
605 bool VoidReturn)
606 : STy(STy), FuncArgNames(FuncArgNames),
607 AliveParamIndices(AliveParamIndices),
608 UseFilteredParams(UseFilteredParams), VoidReturn(VoidReturn) {
609 Kind = BTF::BTF_KIND_FUNC_PROTO;
610 BTFType.Info = (Kind << 24) | VLen;
611}
612
614 if (IsCompleted)
615 return;
616 IsCompleted = true;
617
618 DITypeArray Elements = STy->getTypeArray();
619 if (VoidReturn) {
620 BTFType.Type = 0;
621 } else {
622 auto RetType = tryRemoveAtomicType(Elements[0]);
623 BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
624 }
625 BTFType.NameOff = 0;
626
627 auto EmitParam = [&](uint32_t I) {
628 struct BTF::BTFParam Param;
629 auto Element = tryRemoveAtomicType(Elements[I]);
630 if (Element) {
631 auto It = FuncArgNames.find(I);
632 Param.NameOff =
633 It != FuncArgNames.end() ? BDebug.addString(It->second) : 0;
634 Param.Type = BDebug.getTypeId(Element);
635 } else {
636 Param.NameOff = 0;
637 Param.Type = 0;
638 }
639 Parameters.push_back(Param);
640 };
641
642 if (UseFilteredParams) {
643 for (uint32_t I : AliveParamIndices)
644 EmitParam(I);
645 return;
646 }
647
648 for (unsigned I = 1, N = Elements.size(); I < N; ++I)
649 EmitParam(I);
650}
651
654 for (const auto &Param : Parameters) {
655 OS.emitInt32(Param.NameOff);
656 OS.emitInt32(Param.Type);
657 }
658}
659
661 uint32_t Scope)
662 : Name(FuncName) {
663 Kind = BTF::BTF_KIND_FUNC;
664 BTFType.Info = (Kind << 24) | Scope;
665 BTFType.Type = ProtoTypeId;
666}
667
669 if (IsCompleted)
670 return;
671 IsCompleted = true;
672
673 BTFType.NameOff = BDebug.addString(Name);
674}
675
677
679 : Name(VarName) {
680 Kind = BTF::BTF_KIND_VAR;
681 BTFType.Info = Kind << 24;
682 BTFType.Type = TypeId;
683 Info = VarInfo;
684}
685
687 BTFType.NameOff = BDebug.addString(Name);
688}
689
692 OS.emitInt32(Info);
693}
694
695BTFKindDataSec::BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
696 : Asm(AsmPrt), Name(SecName) {
697 Kind = BTF::BTF_KIND_DATASEC;
698 BTFType.Info = Kind << 24;
699 BTFType.Size = 0;
700}
701
703 BTFType.NameOff = BDebug.addString(Name);
704 BTFType.Info |= Vars.size();
705}
706
709
710 for (const auto &V : Vars) {
711 OS.emitInt32(std::get<0>(V));
712 Asm->emitLabelReference(std::get<1>(V), 4);
713 OS.emitInt32(std::get<2>(V));
714 }
715}
716
718 : Name(TypeName) {
719 Kind = BTF::BTF_KIND_FLOAT;
720 BTFType.Info = Kind << 24;
721 BTFType.Size = roundupToBytes(SizeInBits);
722}
723
725 if (IsCompleted)
726 return;
727 IsCompleted = true;
728
729 BTFType.NameOff = BDebug.addString(Name);
730}
731
732BTFTypeDeclTag::BTFTypeDeclTag(uint32_t BaseTypeId, int ComponentIdx,
733 StringRef Tag)
734 : Tag(Tag) {
735 Kind = BTF::BTF_KIND_DECL_TAG;
736 BTFType.Info = Kind << 24;
737 BTFType.Type = BaseTypeId;
738 Info = ComponentIdx;
739}
740
742 if (IsCompleted)
743 return;
744 IsCompleted = true;
745
746 BTFType.NameOff = BDebug.addString(Tag);
747}
748
753
755 : DTy(nullptr), Tag(Tag) {
756 Kind = BTF::BTF_KIND_TYPE_TAG;
757 BTFType.Info = Kind << 24;
758 BTFType.Type = NextTypeId;
759}
760
762 : DTy(DTy), Tag(Tag) {
763 Kind = BTF::BTF_KIND_TYPE_TAG;
764 BTFType.Info = Kind << 24;
765}
766
768 if (IsCompleted)
769 return;
770 IsCompleted = true;
771 BTFType.NameOff = BDebug.addString(Tag);
772 if (DTy) {
773 const DIType *ResolvedType = tryRemoveAtomicType(DTy->getBaseType());
774 if (!ResolvedType)
775 BTFType.Type = 0;
776 else
777 BTFType.Type = BDebug.getTypeId(ResolvedType);
778 }
779}
780
782 // Check whether the string already exists.
783 for (auto &OffsetM : OffsetToIdMap) {
784 if (Table[OffsetM.second] == S)
785 return OffsetM.first;
786 }
787 // Not find, add to the string table.
788 uint32_t Offset = Size;
789 OffsetToIdMap[Offset] = Table.size();
790 Table.push_back(std::string(S));
791 Size += S.size() + 1;
792 return Offset;
793}
794
796 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
797 LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
798 MapDefNotCollected(true) {
799 addString("\0");
800}
801
802uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry,
803 const DIType *Ty) {
804 TypeEntry->setId(TypeEntries.size() + 1);
805 uint32_t Id = TypeEntry->getId();
806 DIToIdMap[Ty] = Id;
807 TypeEntries.push_back(std::move(TypeEntry));
808 return Id;
809}
810
811uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
812 TypeEntry->setId(TypeEntries.size() + 1);
813 uint32_t Id = TypeEntry->getId();
814 TypeEntries.push_back(std::move(TypeEntry));
815 return Id;
816}
817
818void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
819 // Only int and binary floating point types are supported in BTF.
820 uint32_t Encoding = BTy->getEncoding();
821 std::unique_ptr<BTFTypeBase> TypeEntry;
822 switch (Encoding) {
823 case dwarf::DW_ATE_boolean:
824 case dwarf::DW_ATE_signed:
825 case dwarf::DW_ATE_signed_char:
826 case dwarf::DW_ATE_unsigned:
827 case dwarf::DW_ATE_unsigned_char:
828 case dwarf::DW_ATE_UTF:
829 // Create a BTF type instance for this DIBasicType and put it into
830 // DIToIdMap for cross-type reference check.
831 TypeEntry = std::make_unique<BTFTypeInt>(
832 Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
833 break;
834 case dwarf::DW_ATE_float:
835 TypeEntry =
836 std::make_unique<BTFTypeFloat>(BTy->getSizeInBits(), BTy->getName());
837 break;
838 default:
839 return;
840 }
841
842 TypeId = addType(std::move(TypeEntry), BTy);
843}
844
845/// Handle subprogram or subroutine types.
846void BTFDebug::visitSubroutineType(
847 const DISubroutineType *STy, bool ForSubprog,
848 const SmallDenseMap<uint32_t, StringRef> &FuncArgNames, uint32_t &TypeId,
849 bool VoidReturn) {
850 DITypeArray Elements = STy->getTypeArray();
851 uint32_t VLen = Elements.size() - 1;
852 if (VLen > BTF::MAX_VLEN)
853 return;
854
855 // Subprogram has a valid non-zero-length name, and the pointee of
856 // a function pointer has an empty name. The subprogram type will
857 // not be added to DIToIdMap as it should not be referenced by
858 // any other types.
859 auto TypeEntry = std::make_unique<BTFTypeFuncProto>(
860 STy, VLen, FuncArgNames, false, ArrayRef<uint32_t>(), VoidReturn);
861 if (ForSubprog)
862 TypeId = addType(std::move(TypeEntry)); // For subprogram
863 else
864 TypeId = addType(std::move(TypeEntry), STy); // For func ptr
865
866 // Visit return type and func arg types.
867 if (!VoidReturn) {
868 for (const auto Element : Elements)
869 visitTypeEntry(Element);
870 } else {
871 for (unsigned I = 1, N = Elements.size(); I < N; ++I)
872 visitTypeEntry(Elements[I]);
873 }
874}
875
876void BTFDebug::processDeclAnnotations(DINodeArray Annotations,
877 uint32_t BaseTypeId,
878 int ComponentIdx) {
879 if (!Annotations)
880 return;
881
882 for (const Metadata *Annotation : Annotations->operands()) {
883 const MDNode *MD = cast<MDNode>(Annotation);
884 const MDString *Name = cast<MDString>(MD->getOperand(0));
885 if (Name->getString() != "btf_decl_tag")
886 continue;
887
888 const MDString *Value = cast<MDString>(MD->getOperand(1));
889 auto TypeEntry = std::make_unique<BTFTypeDeclTag>(BaseTypeId, ComponentIdx,
890 Value->getString());
891 addType(std::move(TypeEntry));
892 }
893}
894
895uint32_t BTFDebug::processDISubprogram(
896 const DISubprogram *SP, uint32_t ProtoTypeId, uint8_t Scope,
897 const SmallDenseMap<uint32_t, uint32_t> *ArgIndexMap) {
898 auto FuncTypeEntry =
899 std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
900 uint32_t FuncId = addType(std::move(FuncTypeEntry));
901
902 // Process argument annotations.
903 for (const DINode *DN : SP->getRetainedNodes()) {
904 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
905 uint32_t Arg = DV->getArg();
906 if (Arg) {
907 if (ArgIndexMap) {
908 auto It = ArgIndexMap->find(Arg);
909 if (It != ArgIndexMap->end())
910 processDeclAnnotations(DV->getAnnotations(), FuncId, It->second);
911 } else {
912 processDeclAnnotations(DV->getAnnotations(), FuncId, Arg - 1);
913 }
914 }
915 }
916 }
917 processDeclAnnotations(SP->getAnnotations(), FuncId, -1);
918
919 return FuncId;
920}
921
922/// Generate btf_type_tag chains.
923int BTFDebug::genBTFTypeTags(const DIDerivedType *DTy, int BaseTypeId) {
925 DINodeArray Annots = DTy->getAnnotations();
926 if (Annots) {
927 // For type with "int __tag1 __tag2 *p", the MDStrs will have
928 // content: [__tag1, __tag2].
929 for (const Metadata *Annotations : Annots->operands()) {
930 const MDNode *MD = cast<MDNode>(Annotations);
931 const MDString *Name = cast<MDString>(MD->getOperand(0));
932 if (Name->getString() != "btf_type_tag")
933 continue;
934 MDStrs.push_back(cast<MDString>(MD->getOperand(1)));
935 }
936 }
937
938 if (MDStrs.size() == 0)
939 return -1;
940
941 // With MDStrs [__tag1, __tag2], the output type chain looks like
942 // PTR -> __tag2 -> __tag1 -> BaseType
943 // In the below, we construct BTF types with the order of __tag1, __tag2
944 // and PTR.
945 unsigned TmpTypeId;
946 std::unique_ptr<BTFTypeTypeTag> TypeEntry;
947 if (BaseTypeId >= 0)
948 TypeEntry =
949 std::make_unique<BTFTypeTypeTag>(BaseTypeId, MDStrs[0]->getString());
950 else
951 TypeEntry = std::make_unique<BTFTypeTypeTag>(DTy, MDStrs[0]->getString());
952 TmpTypeId = addType(std::move(TypeEntry));
953
954 for (unsigned I = 1; I < MDStrs.size(); I++) {
955 const MDString *Value = MDStrs[I];
956 TypeEntry = std::make_unique<BTFTypeTypeTag>(TmpTypeId, Value->getString());
957 TmpTypeId = addType(std::move(TypeEntry));
958 }
959 return TmpTypeId;
960}
961
962/// Handle structure/union types.
963void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
964 uint32_t &TypeId) {
965 const DINodeArray Elements = CTy->getElements();
966 uint32_t VLen = Elements.size();
967 // Variant parts might have a discriminator. LLVM DI doesn't consider it as
968 // an element and instead keeps it as a separate reference. But we represent
969 // it as an element in BTF.
970 if (CTy->getTag() == dwarf::DW_TAG_variant_part) {
971 const auto *DTy = CTy->getDiscriminator();
972 if (DTy) {
973 visitTypeEntry(DTy);
974 VLen++;
975 }
976 }
977 if (VLen > BTF::MAX_VLEN)
978 return;
979
980 // Check whether we have any bitfield members or not
981 bool HasBitField = false;
982 for (const auto *Element : Elements) {
983 if (Element->getTag() == dwarf::DW_TAG_member) {
984 auto E = cast<DIDerivedType>(Element);
985 if (E->isBitField()) {
986 HasBitField = true;
987 break;
988 }
989 }
990 }
991
992 auto TypeEntry =
993 std::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
994 StructTypes.push_back(TypeEntry.get());
995 TypeId = addType(std::move(TypeEntry), CTy);
996
997 // Check struct/union annotations
998 processDeclAnnotations(CTy->getAnnotations(), TypeId, -1);
999
1000 // Visit all struct members.
1001 int FieldNo = 0;
1002 for (const auto *Element : Elements) {
1003 switch (Element->getTag()) {
1004 case dwarf::DW_TAG_member: {
1005 const auto Elem = cast<DIDerivedType>(Element);
1006 visitTypeEntry(Elem);
1007 processDeclAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
1008 break;
1009 }
1010 case dwarf::DW_TAG_variant_part: {
1011 const auto Elem = cast<DICompositeType>(Element);
1012 visitTypeEntry(Elem);
1013 processDeclAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
1014 break;
1015 }
1016 default:
1017 llvm_unreachable("Unexpected DI tag of a struct/union element");
1018 }
1019 FieldNo++;
1020 }
1021}
1022
1023void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
1024 // Visit array element type.
1025 uint32_t ElemTypeId;
1026 const DIType *ElemType = CTy->getBaseType();
1027 visitTypeEntry(ElemType, ElemTypeId, false, false);
1028
1029 // Visit array dimensions.
1030 DINodeArray Elements = CTy->getElements();
1031 if (Elements.size() == 0) {
1032 // Rust and other languages may emit array types with no dimensions.
1033 // Treat as a zero-length array so the type is still registered.
1034 auto TypeEntry = std::make_unique<BTFTypeArray>(ElemTypeId, 0);
1035 ElemTypeId = addType(std::move(TypeEntry), CTy);
1036 }
1037 for (int I = Elements.size() - 1; I >= 0; --I) {
1038 if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
1039 if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
1040 const DISubrange *SR = cast<DISubrange>(Element);
1041 auto *CI = dyn_cast<ConstantInt *>(SR->getCount());
1042 int64_t Count = CI->getSExtValue();
1043
1044 // For struct s { int b; char c[]; }, the c[] will be represented
1045 // as an array with Count = -1.
1046 auto TypeEntry =
1047 std::make_unique<BTFTypeArray>(ElemTypeId,
1048 Count >= 0 ? Count : 0);
1049 if (I == 0)
1050 ElemTypeId = addType(std::move(TypeEntry), CTy);
1051 else
1052 ElemTypeId = addType(std::move(TypeEntry));
1053 }
1054 }
1055
1056 // The array TypeId is the type id of the outermost dimension.
1057 TypeId = ElemTypeId;
1058
1059 // The IR does not have a type for array index while BTF wants one.
1060 // So create an array index type if there is none.
1061 if (!ArrayIndexTypeId) {
1062 auto TypeEntry = std::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
1063 0, "__ARRAY_SIZE_TYPE__");
1064 ArrayIndexTypeId = addType(std::move(TypeEntry));
1065 }
1066}
1067
1068void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
1069 DINodeArray Elements = CTy->getElements();
1070 uint32_t VLen = Elements.size();
1071 if (VLen > BTF::MAX_VLEN)
1072 return;
1073
1074 bool IsSigned = false;
1075 unsigned NumBits = 32;
1076 // No BaseType implies forward declaration in which case a
1077 // BTFTypeEnum with Vlen = 0 is emitted.
1078 if (CTy->getBaseType() != nullptr) {
1079 const auto *BTy = cast<DIBasicType>(CTy->getBaseType());
1080 IsSigned = BTy->getEncoding() == dwarf::DW_ATE_signed ||
1081 BTy->getEncoding() == dwarf::DW_ATE_signed_char;
1082 NumBits = BTy->getSizeInBits();
1083 }
1084
1085 if (NumBits <= 32) {
1086 auto TypeEntry = std::make_unique<BTFTypeEnum>(CTy, VLen, IsSigned);
1087 TypeId = addType(std::move(TypeEntry), CTy);
1088 } else {
1089 assert(NumBits == 64);
1090 auto TypeEntry = std::make_unique<BTFTypeEnum64>(CTy, VLen, IsSigned);
1091 TypeId = addType(std::move(TypeEntry), CTy);
1092 }
1093 // No need to visit base type as BTF does not encode it.
1094}
1095
1096/// Handle structure/union forward declarations.
1097void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion,
1098 uint32_t &TypeId) {
1099 auto TypeEntry = std::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
1100 TypeId = addType(std::move(TypeEntry), CTy);
1101}
1102
1103/// Handle structure, union, array and enumeration types.
1104void BTFDebug::visitCompositeType(const DICompositeType *CTy,
1105 uint32_t &TypeId) {
1106 auto Tag = CTy->getTag();
1107 switch (Tag) {
1108 case dwarf::DW_TAG_structure_type:
1109 case dwarf::DW_TAG_union_type:
1110 case dwarf::DW_TAG_variant_part:
1111 // Handle forward declaration differently as it does not have members.
1112 if (CTy->isForwardDecl())
1113 visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
1114 else
1115 visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
1116 break;
1117 case dwarf::DW_TAG_array_type:
1118 visitArrayType(CTy, TypeId);
1119 break;
1120 case dwarf::DW_TAG_enumeration_type:
1121 visitEnumType(CTy, TypeId);
1122 break;
1123 default:
1124 llvm_unreachable("Unexpected DI tag of a composite type");
1125 }
1126}
1127
1128bool BTFDebug::IsForwardDeclCandidate(const DIType *Base) {
1129 if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
1130 auto CTag = CTy->getTag();
1131 if ((CTag == dwarf::DW_TAG_structure_type ||
1132 CTag == dwarf::DW_TAG_union_type) &&
1133 !CTy->getName().empty() && !CTy->isForwardDecl())
1134 return true;
1135 }
1136 return false;
1137}
1138
1139/// Handle pointer, typedef, const, volatile, restrict and member types.
1140void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
1141 bool CheckPointer, bool SeenPointer) {
1142 unsigned Tag = DTy->getTag();
1143
1144 if (Tag == dwarf::DW_TAG_atomic_type)
1145 return visitTypeEntry(DTy->getBaseType(), TypeId, CheckPointer,
1146 SeenPointer);
1147
1148 /// Try to avoid chasing pointees, esp. structure pointees which may
1149 /// unnecessary bring in a lot of types.
1150 if (CheckPointer && !SeenPointer) {
1151 SeenPointer = Tag == dwarf::DW_TAG_pointer_type && !DTy->getAnnotations();
1152 }
1153
1154 if (CheckPointer && SeenPointer) {
1155 const DIType *Base = DTy->getBaseType();
1156 if (Base) {
1157 if (IsForwardDeclCandidate(Base)) {
1158 /// Find a candidate, generate a fixup. Later on the struct/union
1159 /// pointee type will be replaced with either a real type or
1160 /// a forward declaration.
1161 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, true);
1162 auto &Fixup = FixupDerivedTypes[cast<DICompositeType>(Base)];
1163 Fixup.push_back(std::make_pair(DTy, TypeEntry.get()));
1164 TypeId = addType(std::move(TypeEntry), DTy);
1165 return;
1166 }
1167 }
1168 }
1169
1170 if (Tag == dwarf::DW_TAG_pointer_type) {
1171 int TmpTypeId = genBTFTypeTags(DTy, -1);
1172 if (TmpTypeId >= 0) {
1173 auto TypeDEntry =
1174 std::make_unique<BTFTypeDerived>(TmpTypeId, Tag, DTy->getName());
1175 TypeId = addType(std::move(TypeDEntry), DTy);
1176 } else {
1177 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
1178 TypeId = addType(std::move(TypeEntry), DTy);
1179 }
1180 } else if (Tag == dwarf::DW_TAG_typedef || Tag == dwarf::DW_TAG_const_type ||
1181 Tag == dwarf::DW_TAG_volatile_type ||
1182 Tag == dwarf::DW_TAG_restrict_type) {
1183 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
1184 TypeId = addType(std::move(TypeEntry), DTy);
1185 if (Tag == dwarf::DW_TAG_typedef)
1186 processDeclAnnotations(DTy->getAnnotations(), TypeId, -1);
1187 } else if (Tag != dwarf::DW_TAG_member) {
1188 return;
1189 }
1190
1191 // Visit base type of pointer, typedef, const, volatile, restrict or
1192 // struct/union member.
1193 uint32_t TempTypeId = 0;
1194 if (Tag == dwarf::DW_TAG_member)
1195 visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
1196 else
1197 visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
1198}
1199
1200/// Visit a type entry. CheckPointer is true if the type has
1201/// one of its predecessors as one struct/union member. SeenPointer
1202/// is true if CheckPointer is true and one of its predecessors
1203/// is a pointer. The goal of CheckPointer and SeenPointer is to
1204/// do pruning for struct/union types so some of these types
1205/// will not be emitted in BTF and rather forward declarations
1206/// will be generated.
1207void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
1208 bool CheckPointer, bool SeenPointer) {
1209 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
1210 TypeId = DIToIdMap[Ty];
1211
1212 // To handle the case like the following:
1213 // struct t;
1214 // typedef struct t _t;
1215 // struct s1 { _t *c; };
1216 // int test1(struct s1 *arg) { ... }
1217 //
1218 // struct t { int a; int b; };
1219 // struct s2 { _t c; }
1220 // int test2(struct s2 *arg) { ... }
1221 //
1222 // During traversing test1() argument, "_t" is recorded
1223 // in DIToIdMap and a forward declaration fixup is created
1224 // for "struct t" to avoid pointee type traversal.
1225 //
1226 // During traversing test2() argument, even if we see "_t" is
1227 // already defined, we should keep moving to eventually
1228 // bring in types for "struct t". Otherwise, the "struct s2"
1229 // definition won't be correct.
1230 //
1231 // In the above, we have following debuginfo:
1232 // {ptr, struct_member} -> typedef -> struct
1233 // and BTF type for 'typedef' is generated while 'struct' may
1234 // be in FixUp. But let us generalize the above to handle
1235 // {different types} -> [various derived types]+ -> another type.
1236 // For example,
1237 // {func_param, struct_member} -> const -> ptr -> volatile -> struct
1238 // We will traverse const/ptr/volatile which already have corresponding
1239 // BTF types and generate type for 'struct' which might be in Fixup
1240 // state.
1241 if (Ty && (!CheckPointer || !SeenPointer)) {
1242 if (const auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
1243 while (DTy) {
1244 const DIType *BaseTy = DTy->getBaseType();
1245 if (!BaseTy)
1246 break;
1247
1248 if (DIToIdMap.find(BaseTy) != DIToIdMap.end()) {
1249 DTy = dyn_cast<DIDerivedType>(BaseTy);
1250 } else {
1251 if (CheckPointer && DTy->getTag() == dwarf::DW_TAG_pointer_type &&
1252 !DTy->getAnnotations()) {
1253 SeenPointer = true;
1254 if (IsForwardDeclCandidate(BaseTy))
1255 break;
1256 }
1257 uint32_t TmpTypeId;
1258 visitTypeEntry(BaseTy, TmpTypeId, CheckPointer, SeenPointer);
1259 break;
1260 }
1261 }
1262 }
1263 }
1264
1265 return;
1266 }
1267
1268 if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
1269 visitBasicType(BTy, TypeId);
1270 else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
1271 visitSubroutineType(STy, false, SmallDenseMap<uint32_t, StringRef>(),
1272 TypeId);
1273 else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
1274 visitCompositeType(CTy, TypeId);
1275 else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
1276 visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
1277 else
1278 llvm_unreachable("Unknown DIType");
1279}
1280
1281void BTFDebug::visitTypeEntry(const DIType *Ty) {
1282 uint32_t TypeId;
1283 visitTypeEntry(Ty, TypeId, false, false);
1284}
1285
1286void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
1287 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
1288 TypeId = DIToIdMap[Ty];
1289 return;
1290 }
1291
1292 uint32_t TmpId;
1293 switch (Ty->getTag()) {
1294 case dwarf::DW_TAG_typedef:
1295 case dwarf::DW_TAG_const_type:
1296 case dwarf::DW_TAG_volatile_type:
1297 case dwarf::DW_TAG_restrict_type:
1298 case dwarf::DW_TAG_pointer_type:
1299 visitMapDefType(dyn_cast<DIDerivedType>(Ty)->getBaseType(), TmpId);
1300 break;
1301 case dwarf::DW_TAG_array_type:
1302 // Visit nested map array and jump to the element type
1303 visitMapDefType(dyn_cast<DICompositeType>(Ty)->getBaseType(), TmpId);
1304 break;
1305 case dwarf::DW_TAG_structure_type: {
1306 // Visit all struct members to ensure their types are visited.
1307 const auto *CTy = cast<DICompositeType>(Ty);
1308 const DINodeArray Elements = CTy->getElements();
1309 for (const auto *Element : Elements) {
1310 const auto *MemberType = cast<DIDerivedType>(Element);
1311 const DIType *MemberBaseType = MemberType->getBaseType();
1312 // If the member is a composite type, that may indicate the currently
1313 // visited composite type is a wrapper, and the member represents the
1314 // actual map definition.
1315 // In that case, visit the member with `visitMapDefType` instead of
1316 // `visitTypeEntry`, treating it specifically as a map definition rather
1317 // than as a regular composite type.
1318 const auto *MemberCTy = dyn_cast<DICompositeType>(MemberBaseType);
1319 if (MemberCTy) {
1320 visitMapDefType(MemberBaseType, TmpId);
1321 } else {
1322 visitTypeEntry(MemberBaseType);
1323 }
1324 }
1325 break;
1326 }
1327 default:
1328 break;
1329 }
1330
1331 // Visit this type, struct or a const/typedef/volatile/restrict type
1332 visitTypeEntry(Ty, TypeId, false, false);
1333}
1334
1335/// Read file contents from the actual file or from the source
1336std::string BTFDebug::populateFileContent(const DIFile *File) {
1337 std::string FileName;
1338
1339 if (!File->getFilename().starts_with("/") && File->getDirectory().size())
1340 FileName = File->getDirectory().str() + "/" + File->getFilename().str();
1341 else
1342 FileName = std::string(File->getFilename());
1343
1344 // No need to populate the contends if it has been populated!
1345 if (FileContent.contains(FileName))
1346 return FileName;
1347
1348 std::vector<std::string> Content;
1349 std::string Line;
1350 Content.push_back(Line); // Line 0 for empty string
1351
1352 auto LoadFile = [](StringRef FileName) {
1353 // FIXME(sandboxing): Propagating vfs::FileSystem here is lots of work.
1354 auto BypassSandbox = sys::sandbox::scopedDisable();
1355 return MemoryBuffer::getFile(FileName);
1356 };
1357
1358 std::unique_ptr<MemoryBuffer> Buf;
1359 auto Source = File->getSource();
1360 if (Source)
1361 Buf = MemoryBuffer::getMemBufferCopy(*Source);
1362 else if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = LoadFile(FileName))
1363 Buf = std::move(*BufOrErr);
1364 if (Buf)
1365 for (line_iterator I(*Buf, false), E; I != E; ++I)
1366 Content.push_back(std::string(*I));
1367
1368 FileContent[FileName] = std::move(Content);
1369 return FileName;
1370}
1371
1372void BTFDebug::constructLineInfo(MCSymbol *Label, const DIFile *File,
1373 uint32_t Line, uint32_t Column) {
1374 std::string FileName = populateFileContent(File);
1375 BTFLineInfo LineInfo;
1376
1377 LineInfo.Label = Label;
1378 LineInfo.FileNameOff = addString(FileName);
1379 // If file content is not available, let LineOff = 0.
1380 const auto &Content = FileContent[FileName];
1381 if (Line < Content.size())
1382 LineInfo.LineOff = addString(Content[Line]);
1383 else
1384 LineInfo.LineOff = 0;
1385 LineInfo.LineNum = Line;
1386 LineInfo.ColumnNum = Column;
1387 LineInfoTable[SecNameOff].push_back(LineInfo);
1388}
1389
1390void BTFDebug::emitCommonHeader() {
1391 OS.AddComment("0x" + Twine::utohexstr(BTF::MAGIC));
1392 OS.emitIntValue(BTF::MAGIC, 2);
1393 OS.emitInt8(BTF::VERSION);
1394 OS.emitInt8(0);
1395}
1396
1397void BTFDebug::emitBTFSection() {
1398 // Do not emit section if no types and only "" string.
1399 if (!TypeEntries.size() && StringTable.getSize() == 1)
1400 return;
1401
1402 MCContext &Ctx = OS.getContext();
1403 MCSectionELF *Sec = Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0);
1404 Sec->setAlignment(Align(4));
1405 OS.switchSection(Sec);
1406
1407 // Emit header.
1408 emitCommonHeader();
1409 OS.emitInt32(BTF::HeaderSize);
1410
1411 uint32_t TypeLen = 0, StrLen;
1412 for (const auto &TypeEntry : TypeEntries)
1413 TypeLen += TypeEntry->getSize();
1414 StrLen = StringTable.getSize();
1415
1416 OS.emitInt32(0);
1417 OS.emitInt32(TypeLen);
1418 OS.emitInt32(TypeLen);
1419 OS.emitInt32(StrLen);
1420
1421 // Emit type table.
1422 for (const auto &TypeEntry : TypeEntries)
1423 TypeEntry->emitType(OS);
1424
1425 // Emit string table.
1426 uint32_t StringOffset = 0;
1427 for (const auto &S : StringTable.getTable()) {
1428 OS.AddComment("string offset=" + std::to_string(StringOffset));
1429 OS.emitBytes(S);
1430 OS.emitBytes(StringRef("\0", 1));
1431 StringOffset += S.size() + 1;
1432 }
1433}
1434
1435void BTFDebug::emitBTFExtSection() {
1436 // Do not emit section if empty FuncInfoTable and LineInfoTable
1437 // and FieldRelocTable.
1438 if (!FuncInfoTable.size() && !LineInfoTable.size() &&
1439 !FieldRelocTable.size())
1440 return;
1441
1442 MCContext &Ctx = OS.getContext();
1443 MCSectionELF *Sec = Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0);
1444 Sec->setAlignment(Align(4));
1445 OS.switchSection(Sec);
1446
1447 // Emit header.
1448 emitCommonHeader();
1449 OS.emitInt32(BTF::ExtHeaderSize);
1450
1451 // Account for FuncInfo/LineInfo record size as well.
1452 uint32_t FuncLen = 4, LineLen = 4;
1453 // Do not account for optional FieldReloc.
1454 uint32_t FieldRelocLen = 0;
1455 for (const auto &FuncSec : FuncInfoTable) {
1456 FuncLen += BTF::SecFuncInfoSize;
1457 FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
1458 }
1459 for (const auto &LineSec : LineInfoTable) {
1460 LineLen += BTF::SecLineInfoSize;
1461 LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
1462 }
1463 for (const auto &FieldRelocSec : FieldRelocTable) {
1464 FieldRelocLen += BTF::SecFieldRelocSize;
1465 FieldRelocLen += FieldRelocSec.second.size() * BTF::BPFFieldRelocSize;
1466 }
1467
1468 if (FieldRelocLen)
1469 FieldRelocLen += 4;
1470
1471 OS.emitInt32(0);
1472 OS.emitInt32(FuncLen);
1473 OS.emitInt32(FuncLen);
1474 OS.emitInt32(LineLen);
1475 OS.emitInt32(FuncLen + LineLen);
1476 OS.emitInt32(FieldRelocLen);
1477
1478 // Emit func_info table.
1479 OS.AddComment("FuncInfo");
1480 OS.emitInt32(BTF::BPFFuncInfoSize);
1481 for (const auto &FuncSec : FuncInfoTable) {
1482 OS.AddComment("FuncInfo section string offset=" +
1483 std::to_string(FuncSec.first));
1484 OS.emitInt32(FuncSec.first);
1485 OS.emitInt32(FuncSec.second.size());
1486 for (const auto &FuncInfo : FuncSec.second) {
1487 Asm->emitLabelReference(FuncInfo.Label, 4);
1488 OS.emitInt32(FuncInfo.TypeId);
1489 }
1490 }
1491
1492 // Emit line_info table.
1493 OS.AddComment("LineInfo");
1494 OS.emitInt32(BTF::BPFLineInfoSize);
1495 for (const auto &LineSec : LineInfoTable) {
1496 OS.AddComment("LineInfo section string offset=" +
1497 std::to_string(LineSec.first));
1498 OS.emitInt32(LineSec.first);
1499 OS.emitInt32(LineSec.second.size());
1500 for (const auto &LineInfo : LineSec.second) {
1501 Asm->emitLabelReference(LineInfo.Label, 4);
1502 OS.emitInt32(LineInfo.FileNameOff);
1503 OS.emitInt32(LineInfo.LineOff);
1504 OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
1505 std::to_string(LineInfo.ColumnNum));
1506 OS.emitInt32(LineInfo.LineNum << 10 | LineInfo.ColumnNum);
1507 }
1508 }
1509
1510 // Emit field reloc table.
1511 if (FieldRelocLen) {
1512 OS.AddComment("FieldReloc");
1513 OS.emitInt32(BTF::BPFFieldRelocSize);
1514 for (const auto &FieldRelocSec : FieldRelocTable) {
1515 OS.AddComment("Field reloc section string offset=" +
1516 std::to_string(FieldRelocSec.first));
1517 OS.emitInt32(FieldRelocSec.first);
1518 OS.emitInt32(FieldRelocSec.second.size());
1519 for (const auto &FieldRelocInfo : FieldRelocSec.second) {
1520 Asm->emitLabelReference(FieldRelocInfo.Label, 4);
1521 OS.emitInt32(FieldRelocInfo.TypeID);
1522 OS.emitInt32(FieldRelocInfo.OffsetNameOff);
1523 OS.emitInt32(FieldRelocInfo.RelocKind);
1524 }
1525 }
1526 }
1527}
1528
1530 auto *SP = MF->getFunction().getSubprogram();
1531 auto *Unit = SP->getUnit();
1532
1533 if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
1534 SkipInstruction = true;
1535 return;
1536 }
1537 SkipInstruction = false;
1538
1539 // Collect MapDef types. Map definition needs to collect
1540 // pointee types. Do it first. Otherwise, for the following
1541 // case:
1542 // struct m { ...};
1543 // struct t {
1544 // struct m *key;
1545 // };
1546 // foo(struct t *arg);
1547 //
1548 // struct mapdef {
1549 // ...
1550 // struct m *key;
1551 // ...
1552 // } __attribute__((section(".maps"))) hash_map;
1553 //
1554 // If subroutine foo is traversed first, a type chain
1555 // "ptr->struct m(fwd)" will be created and later on
1556 // when traversing mapdef, since "ptr->struct m" exists,
1557 // the traversal of "struct m" will be omitted.
1558 if (MapDefNotCollected) {
1559 processGlobals(true);
1560 MapDefNotCollected = false;
1561 }
1562
1563 // Collect all types locally referenced in this function.
1564 // Use RetainedNodes so we can collect all argument names
1565 // even if the argument is not used.
1567 for (const DINode *DN : SP->getRetainedNodes()) {
1568 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
1569 // Collect function arguments for subprogram func type.
1570 uint32_t Arg = DV->getArg();
1571 if (Arg) {
1572 visitTypeEntry(DV->getType());
1573 FuncArgNames[Arg] = DV->getName();
1574 }
1575 }
1576 }
1577
1578 // Construct subprogram func proto type.
1579 uint32_t ProtoTypeId, FuncTypeId;
1580 uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
1581 bool IsNocall = SP->getType()->getCC() == dwarf::DW_CC_nocall;
1582 bool UseFilteredParams = false;
1583 bool VoidReturn = MF->getFunction().getReturnType()->isVoidTy();
1584
1585 if (IsNocall) {
1586 // For DW_CC_nocall functions, try to build a FUNC_PROTO reflecting
1587 // the true ABI: only parameters that survived optimization and whose
1588 // first 5 arguments map to the correct BPF registers (R1-R5).
1590 DITypeArray Elements = SP->getType()->getTypeArray();
1591
1594
1595 UseFilteredParams =
1596 canUseNocallOptimizedSignature(*MF, Elements, AliveArgs, *TRI);
1597
1598 if (UseFilteredParams) {
1599 SmallVector<uint32_t, 8> AliveParamIndices;
1601 for (auto [I, ArgReg] : llvm::enumerate(AliveArgs)) {
1602 AliveParamIndices.push_back(ArgReg.first);
1603 ArgIndexMap[ArgReg.first] = I;
1604 }
1605
1606 if (!VoidReturn)
1607 visitTypeEntry(Elements[0]);
1608 for (uint32_t ArgNo : AliveParamIndices)
1609 visitTypeEntry(Elements[ArgNo]);
1610
1611 auto TypeEntry = std::make_unique<BTFTypeFuncProto>(
1612 SP->getType(), AliveParamIndices.size(), FuncArgNames, true,
1613 AliveParamIndices, VoidReturn);
1614 ProtoTypeId = addType(std::move(TypeEntry));
1615 FuncTypeId = processDISubprogram(SP, ProtoTypeId, Scope, &ArgIndexMap);
1616 }
1617 }
1618
1619 if (!UseFilteredParams) {
1620 // Fall back to the full source prototype, still voiding the return
1621 // type if compiler removed it.
1622 visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId,
1623 VoidReturn);
1624 FuncTypeId = processDISubprogram(SP, ProtoTypeId, Scope);
1625 }
1626
1627 for (const auto &TypeEntry : TypeEntries)
1628 TypeEntry->completeType(*this);
1629
1630 // Construct funcinfo and the first lineinfo for the function.
1631 MCSymbol *FuncLabel = Asm->getFunctionBegin();
1632 BTFFuncInfo FuncInfo;
1633 FuncInfo.Label = FuncLabel;
1634 FuncInfo.TypeId = FuncTypeId;
1635 if (FuncLabel->isInSection()) {
1636 auto &Sec = static_cast<const MCSectionELF &>(FuncLabel->getSection());
1637 SecNameOff = addString(Sec.getName());
1638 } else {
1639 SecNameOff = addString(".text");
1640 }
1641 FuncInfoTable[SecNameOff].push_back(FuncInfo);
1642}
1643
1645 SkipInstruction = false;
1646 LineInfoGenerated = false;
1647 SecNameOff = 0;
1648}
1649
1650/// On-demand populate types as requested from abstract member
1651/// accessing or preserve debuginfo type.
1652unsigned BTFDebug::populateType(const DIType *Ty) {
1653 unsigned Id;
1654 visitTypeEntry(Ty, Id, false, false);
1655 for (const auto &TypeEntry : TypeEntries)
1656 TypeEntry->completeType(*this);
1657 return Id;
1658}
1659
1660/// Generate a struct member field relocation.
1661void BTFDebug::generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
1662 const GlobalVariable *GVar, bool IsAma) {
1663 BTFFieldReloc FieldReloc;
1664 FieldReloc.Label = ORSym;
1665 FieldReloc.TypeID = RootId;
1666
1667 StringRef AccessPattern = GVar->getName();
1668 size_t FirstDollar = AccessPattern.find_first_of('$');
1669 if (IsAma) {
1670 size_t FirstColon = AccessPattern.find_first_of(':');
1671 size_t SecondColon = AccessPattern.find_first_of(':', FirstColon + 1);
1672 StringRef IndexPattern = AccessPattern.substr(FirstDollar + 1);
1673 StringRef RelocKindStr = AccessPattern.substr(FirstColon + 1,
1674 SecondColon - FirstColon);
1675 StringRef PatchImmStr = AccessPattern.substr(SecondColon + 1,
1676 FirstDollar - SecondColon);
1677
1678 FieldReloc.OffsetNameOff = addString(IndexPattern);
1679 FieldReloc.RelocKind = std::stoull(std::string(RelocKindStr));
1680 PatchImms[GVar] = std::make_pair(std::stoll(std::string(PatchImmStr)),
1681 FieldReloc.RelocKind);
1682 } else {
1683 StringRef RelocStr = AccessPattern.substr(FirstDollar + 1);
1684 FieldReloc.OffsetNameOff = addString("0");
1685 FieldReloc.RelocKind = std::stoull(std::string(RelocStr));
1686 PatchImms[GVar] = std::make_pair(RootId, FieldReloc.RelocKind);
1687 }
1688 FieldRelocTable[SecNameOff].push_back(FieldReloc);
1689}
1690
1691void BTFDebug::processGlobalValue(const MachineOperand &MO) {
1692 // check whether this is a candidate or not
1693 if (MO.isGlobal()) {
1694 const GlobalValue *GVal = MO.getGlobal();
1695 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1696 if (!GVar) {
1697 // Not a global variable. Maybe an extern function reference.
1698 processFuncPrototypes(dyn_cast<Function>(GVal));
1699 return;
1700 }
1701
1704 return;
1705
1706 MCSymbol *ORSym = OS.getContext().createTempSymbol();
1707 OS.emitLabel(ORSym);
1708
1709 MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
1710 uint32_t RootId = populateType(dyn_cast<DIType>(MDN));
1711 generatePatchImmReloc(ORSym, RootId, GVar,
1713 }
1714}
1715
1718
1719 if (SkipInstruction || MI->isMetaInstruction() ||
1720 MI->getFlag(MachineInstr::FrameSetup))
1721 return;
1722
1723 if (MI->isInlineAsm()) {
1724 // Count the number of register definitions to find the asm string.
1725 unsigned NumDefs = 0;
1726 while (true) {
1727 const MachineOperand &MO = MI->getOperand(NumDefs);
1728 if (MO.isReg() && MO.isDef()) {
1729 ++NumDefs;
1730 continue;
1731 }
1732 // Skip this inline asm instruction if the asmstr is empty.
1733 const char *AsmStr = MO.getSymbolName();
1734 if (AsmStr[0] == 0)
1735 return;
1736 break;
1737 }
1738 }
1739
1740 if (MI->getOpcode() == BPF::LD_imm64) {
1741 // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
1742 // add this insn into the .BTF.ext FieldReloc subsection.
1743 // Relocation looks like:
1744 // . SecName:
1745 // . InstOffset
1746 // . TypeID
1747 // . OffSetNameOff
1748 // . RelocType
1749 // Later, the insn is replaced with "r2 = <offset>"
1750 // where "<offset>" equals to the offset based on current
1751 // type definitions.
1752 //
1753 // If the insn is "r2 = LD_imm64 @<an TypeIdAttr global>",
1754 // The LD_imm64 result will be replaced with a btf type id.
1755 processGlobalValue(MI->getOperand(1));
1756 } else if (MI->getOpcode() == BPF::CORE_LD64 ||
1757 MI->getOpcode() == BPF::CORE_LD32 ||
1758 MI->getOpcode() == BPF::CORE_ST ||
1759 MI->getOpcode() == BPF::CORE_SHIFT) {
1760 // relocation insn is a load, store or shift insn.
1761 processGlobalValue(MI->getOperand(3));
1762 } else if (MI->getOpcode() == BPF::JAL) {
1763 // check extern function references
1764 const MachineOperand &MO = MI->getOperand(0);
1765 if (MO.isGlobal()) {
1766 processFuncPrototypes(dyn_cast<Function>(MO.getGlobal()));
1767 }
1768 }
1769
1770 if (!CurMI) // no debug info
1771 return;
1772
1773 // Skip this instruction if no DebugLoc, the DebugLoc
1774 // is the same as the previous instruction or Line is 0.
1775 const DebugLoc &DL = MI->getDebugLoc();
1776 if (!DL || PrevInstLoc == DL || DL.getLine() == 0) {
1777 // This instruction will be skipped, no LineInfo has
1778 // been generated, construct one based on function signature.
1779 if (LineInfoGenerated == false) {
1780 auto *S = MI->getMF()->getFunction().getSubprogram();
1781 if (!S)
1782 return;
1783 MCSymbol *FuncLabel = Asm->getFunctionBegin();
1784 constructLineInfo(FuncLabel, S->getFile(), S->getLine(), 0);
1785 LineInfoGenerated = true;
1786 }
1787
1788 return;
1789 }
1790
1791 // Create a temporary label to remember the insn for lineinfo.
1792 MCSymbol *LineSym = OS.getContext().createTempSymbol();
1793 OS.emitLabel(LineSym);
1794
1795 // Construct the lineinfo.
1796 constructLineInfo(LineSym, DL->getFile(), DL.getLine(), DL.getCol());
1797
1798 LineInfoGenerated = true;
1799 PrevInstLoc = DL;
1800}
1801
1802void BTFDebug::processGlobals(bool ProcessingMapDef) {
1803 // Collect all types referenced by globals.
1804 const Module *M = MMI->getModule();
1805 for (const GlobalVariable &Global : M->globals()) {
1806 // Decide the section name.
1807 StringRef SecName;
1808 std::optional<SectionKind> GVKind;
1809
1810 if (!Global.isDeclarationForLinker())
1812
1813 if (Global.isDeclarationForLinker())
1814 SecName = Global.hasSection() ? Global.getSection() : "";
1815 else if (GVKind->isCommon())
1816 SecName = ".bss";
1817 else {
1819 MCSection *Sec = TLOF->SectionForGlobal(&Global, Asm->TM);
1820 SecName = Sec->getName();
1821 }
1822
1823 if (ProcessingMapDef != SecName.starts_with(".maps"))
1824 continue;
1825
1826 // Create a .rodata datasec if the global variable is an initialized
1827 // constant with private linkage and if it won't be in .rodata.str<#>
1828 // and .rodata.cst<#> sections.
1829 if (SecName == ".rodata" && Global.hasPrivateLinkage() &&
1830 DataSecEntries.find(SecName) == DataSecEntries.end()) {
1831 // skip .rodata.str<#> and .rodata.cst<#> sections
1832 if (!GVKind->isMergeableCString() && !GVKind->isMergeableConst()) {
1833 DataSecEntries[std::string(SecName)] =
1834 std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1835 }
1836 }
1837
1839 Global.getDebugInfo(GVs);
1840
1841 // No type information, mostly internal, skip it.
1842 if (GVs.size() == 0)
1843 continue;
1844
1845 uint32_t GVTypeId = 0;
1846 DIGlobalVariable *DIGlobal = nullptr;
1847 for (auto *GVE : GVs) {
1848 DIGlobal = GVE->getVariable();
1849 if (SecName.starts_with(".maps"))
1850 visitMapDefType(DIGlobal->getType(), GVTypeId);
1851 else {
1852 const DIType *Ty = tryRemoveAtomicType(DIGlobal->getType());
1853 visitTypeEntry(Ty, GVTypeId, false, false);
1854 }
1855 break;
1856 }
1857
1858 // Only support the following globals:
1859 // . static variables
1860 // . non-static weak or non-weak global variables
1861 // . weak or non-weak extern global variables
1862 // Whether DataSec is readonly or not can be found from corresponding ELF
1863 // section flags. Whether a BTF_KIND_VAR is a weak symbol or not
1864 // can be found from the corresponding ELF symbol table.
1865 auto Linkage = Global.getLinkage();
1871 continue;
1872
1873 uint32_t GVarInfo;
1875 GVarInfo = BTF::VAR_STATIC;
1876 } else if (Global.hasInitializer()) {
1877 GVarInfo = BTF::VAR_GLOBAL_ALLOCATED;
1878 } else {
1879 GVarInfo = BTF::VAR_GLOBAL_EXTERNAL;
1880 }
1881
1882 auto VarEntry =
1883 std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
1884 uint32_t VarId = addType(std::move(VarEntry));
1885
1886 processDeclAnnotations(DIGlobal->getAnnotations(), VarId, -1);
1887
1888 // An empty SecName means an extern variable without section attribute.
1889 if (SecName.empty())
1890 continue;
1891
1892 // Find or create a DataSec
1893 auto [It, Inserted] = DataSecEntries.try_emplace(std::string(SecName));
1894 if (Inserted)
1895 It->second = std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1896
1897 // Calculate symbol size
1898 const DataLayout &DL = Global.getDataLayout();
1899 uint32_t Size = Global.getGlobalSize(DL);
1900
1901 It->second->addDataSecEntry(VarId, Asm->getSymbol(&Global), Size);
1902
1903 if (Global.hasInitializer())
1904 processGlobalInitializer(Global.getInitializer());
1905 }
1906}
1907
1908/// Process global variable initializer in pursuit for function
1909/// pointers. Add discovered (extern) functions to BTF. Some (extern)
1910/// functions might have been missed otherwise. Every symbol needs BTF
1911/// info when linking with bpftool. Primary use case: "static"
1912/// initialization of BPF maps.
1913///
1914/// struct {
1915/// __uint(type, BPF_MAP_TYPE_PROG_ARRAY);
1916/// ...
1917/// } prog_map SEC(".maps") = { .values = { extern_func } };
1918///
1919void BTFDebug::processGlobalInitializer(const Constant *C) {
1920 if (auto *Fn = dyn_cast<Function>(C))
1921 processFuncPrototypes(Fn);
1922 if (auto *CA = dyn_cast<ConstantAggregate>(C)) {
1923 for (unsigned I = 0, N = CA->getNumOperands(); I < N; ++I)
1924 processGlobalInitializer(CA->getOperand(I));
1925 }
1926}
1927
1928/// Emit proper patchable instructions.
1930 if (MI->getOpcode() == BPF::LD_imm64) {
1931 const MachineOperand &MO = MI->getOperand(1);
1932 if (MO.isGlobal()) {
1933 const GlobalValue *GVal = MO.getGlobal();
1934 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1935 if (GVar) {
1938 return false;
1939
1940 // Emit "mov ri, <imm>"
1941 auto [Imm, Reloc] = PatchImms[GVar];
1944 OutMI.setOpcode(BPF::LD_imm64);
1945 else
1946 OutMI.setOpcode(BPF::MOV_ri);
1947 OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1948 OutMI.addOperand(MCOperand::createImm(Imm));
1949 return true;
1950 }
1951 }
1952 } else if (MI->getOpcode() == BPF::CORE_LD64 ||
1953 MI->getOpcode() == BPF::CORE_LD32 ||
1954 MI->getOpcode() == BPF::CORE_ST ||
1955 MI->getOpcode() == BPF::CORE_SHIFT) {
1956 const MachineOperand &MO = MI->getOperand(3);
1957 if (MO.isGlobal()) {
1958 const GlobalValue *GVal = MO.getGlobal();
1959 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1960 if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
1961 uint32_t Imm = PatchImms[GVar].first;
1962 OutMI.setOpcode(MI->getOperand(1).getImm());
1963 if (MI->getOperand(0).isImm())
1964 OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
1965 else
1966 OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1967 OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
1968 OutMI.addOperand(MCOperand::createImm(Imm));
1969 return true;
1970 }
1971 }
1972 }
1973 return false;
1974}
1975
1976void BTFDebug::processFuncPrototypes(const Function *F) {
1977 if (!F)
1978 return;
1979
1980 const DISubprogram *SP = F->getSubprogram();
1981 if (!SP || SP->isDefinition())
1982 return;
1983
1984 // Do not emit again if already emitted.
1985 if (!ProtoFunctions.insert(F).second)
1986 return;
1987
1988 uint32_t ProtoTypeId;
1989 const SmallDenseMap<uint32_t, StringRef> FuncArgNames;
1990 visitSubroutineType(SP->getType(), false, FuncArgNames, ProtoTypeId);
1991 uint32_t FuncId = processDISubprogram(SP, ProtoTypeId, BTF::FUNC_EXTERN);
1992
1993 if (F->hasSection()) {
1994 StringRef SecName = F->getSection();
1995
1996 auto [It, Inserted] = DataSecEntries.try_emplace(std::string(SecName));
1997 if (Inserted)
1998 It->second = std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1999
2000 // We really don't know func size, set it to 0.
2001 It->second->addDataSecEntry(FuncId, Asm->getSymbol(F), 0);
2002 }
2003}
2004
2006 // Collect MapDef globals if not collected yet.
2007 if (MapDefNotCollected) {
2008 processGlobals(true);
2009 MapDefNotCollected = false;
2010 }
2011
2012 // Collect global types/variables except MapDef globals.
2013 processGlobals(false);
2014
2015 // In case that BPF_TRAP usage is removed during machine-level optimization,
2016 // generate btf for BPF_TRAP function here.
2017 for (const Function &F : *MMI->getModule()) {
2018 if (F.getName() == BPF_TRAP)
2019 processFuncPrototypes(&F);
2020 }
2021
2022 for (auto &DataSec : DataSecEntries)
2023 addType(std::move(DataSec.second));
2024
2025 // Fixups
2026 for (auto &Fixup : FixupDerivedTypes) {
2027 const DICompositeType *CTy = Fixup.first;
2028 StringRef TypeName = CTy->getName();
2029 bool IsUnion = CTy->getTag() == dwarf::DW_TAG_union_type;
2030
2031 // Search through struct types
2032 uint32_t StructTypeId = 0;
2033 for (const auto &StructType : StructTypes) {
2034 if (StructType->getName() == TypeName) {
2035 StructTypeId = StructType->getId();
2036 break;
2037 }
2038 }
2039
2040 if (StructTypeId == 0) {
2041 auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
2042 StructTypeId = addType(std::move(FwdTypeEntry));
2043 }
2044
2045 for (auto &TypeInfo : Fixup.second) {
2046 const DIDerivedType *DTy = TypeInfo.first;
2047 BTFTypeDerived *BDType = TypeInfo.second;
2048
2049 int TmpTypeId = genBTFTypeTags(DTy, StructTypeId);
2050 if (TmpTypeId >= 0)
2051 BDType->setPointeeType(TmpTypeId);
2052 else
2053 BDType->setPointeeType(StructTypeId);
2054 }
2055 }
2056
2057 // Complete BTF type cross refereences.
2058 for (const auto &TypeEntry : TypeEntries)
2059 TypeEntry->completeType(*this);
2060
2061 // Emit BTF sections.
2062 emitBTFSection();
2063 emitBTFExtSection();
2064}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define BPF_TRAP
Definition BPF.h:25
static SmallVector< std::pair< uint32_t, Register >, 8 > collectNocallEntryArgRegs(const MachineFunction &MF)
Collect the physical register each source argument lives in by scanning DBG_VALUE instructions in the...
Definition BTFDebug.cpp:123
static bool sourceArgMatchesIRType(const DIType *SourceTy, Type *IRTy)
Definition BTFDebug.cpp:76
static const char * BTFKindStr[]
Definition BTFDebug.cpp:45
static const DIType * stripDITypeAttributes(const DIType *Ty)
Definition BTFDebug.cpp:59
static bool canUseNocallOptimizedSignature(const MachineFunction &MF, DITypeArray Elements, ArrayRef< std::pair< uint32_t, Register > > AliveArgs, const TargetRegisterInfo &TRI)
Check whether the optimized IR signature matches the surviving source arguments precisely enough to e...
Definition BTFDebug.cpp:216
static const DIType * tryRemoveAtomicType(const DIType *Ty)
Definition BTFDebug.cpp:50
This file contains support for writing BTF debug info.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file contains constants used for implementing Dwarf debug support.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
PowerPC TLS Dynamic Call Fixup
static StringRef getName(Value *V)
static enum BaseType getBaseType(const Value *Val)
Return the baseType for Val which states whether Val is exclusively derived from constant/null,...
#define LLVM_DEBUG(...)
Definition Debug.h:119
an instruction to allocate memory on the stack
Annotations lets you mark points and ranges inside source code, for tests:
Definition Annotations.h:67
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
MCSymbol * getSymbol(const GlobalValue *GV) const
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:94
static constexpr StringRef TypeIdAttr
The attribute attached to globals representing a type id.
Definition BPFCORE.h:48
static constexpr StringRef AmaAttr
The attribute attached to globals representing a field access.
Definition BPFCORE.h:46
Collect and emit BTF information.
Definition BTFDebug.h:295
void endFunctionImpl(const MachineFunction *MF) override
Post process after all instructions in this function are processed.
BTFDebug(AsmPrinter *AP)
Definition BTFDebug.cpp:795
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
bool InstLower(const MachineInstr *MI, MCInst &OutMI)
Emit proper patchable instructions.
size_t addString(StringRef S)
Add string to the string table.
Definition BTFDebug.h:425
uint32_t getArrayIndexTypeId()
Get the special array index type id.
Definition BTFDebug.h:419
uint32_t getTypeId(const DIType *Ty)
Get the type id for a particular DIType.
Definition BTFDebug.h:428
void endModule() override
Complete all the types and emit the BTF sections.
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:707
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:702
BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
Definition BTFDebug.cpp:695
BTFKindVar(StringRef VarName, uint32_t TypeId, uint32_t VarInfo)
Definition BTFDebug.cpp:678
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:690
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:686
uint32_t addString(StringRef S)
Add a string to the string table and returns its offset in the table.
Definition BTFDebug.cpp:781
BTFTypeArray(uint32_t ElemTypeId, uint32_t NumElems)
Definition BTFDebug.cpp:481
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:504
void completeType(BTFDebug &BDebug) override
Represent a BTF array.
Definition BTFDebug.cpp:492
struct BTF::CommonType BTFType
Definition BTFDebug.h:44
virtual void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition BTFDebug.cpp:253
uint32_t roundupToBytes(uint32_t NumBits)
Definition BTFDebug.h:51
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:741
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:749
BTFTypeDeclTag(uint32_t BaseTypeId, int ComponentId, StringRef Tag)
Definition BTFDebug.cpp:732
Handle several derived types include pointer, const, volatile, typedef and restrict.
Definition BTFDebug.h:64
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:296
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:335
void setPointeeType(uint32_t PointeeType)
Definition BTFDebug.cpp:337
BTFTypeDerived(const DIDerivedType *Ty, unsigned Tag, bool NeedsFixup)
Definition BTFDebug.cpp:262
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:446
BTFTypeEnum64(const DICompositeType *ETy, uint32_t NumValues, bool IsSigned)
Definition BTFDebug.cpp:439
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:470
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:407
BTFTypeEnum(const DICompositeType *ETy, uint32_t NumValues, bool IsSigned)
Definition BTFDebug.cpp:400
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:431
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:724
BTFTypeFloat(uint32_t SizeInBits, StringRef TypeName)
Definition BTFDebug.cpp:717
BTFTypeFuncProto(const DISubroutineType *STy, uint32_t NumParams, const SmallDenseMap< uint32_t, StringRef > &FuncArgNames, bool UseFilteredParams=false, ArrayRef< uint32_t > AliveParamIndices={}, bool VoidReturn=false)
The Func kind represents both subprogram and pointee of function pointers.
Definition BTFDebug.cpp:601
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:613
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:652
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:676
BTFTypeFunc(StringRef FuncName, uint32_t ProtoTypeId, uint32_t Scope)
Definition BTFDebug.cpp:660
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:668
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:356
BTFTypeFwd(StringRef Name, bool IsUnion)
Represent a struct/union forward declaration.
Definition BTFDebug.cpp:342
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:348
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:394
BTFTypeInt(uint32_t Encoding, uint32_t SizeInBits, uint32_t OffsetInBits, StringRef TypeName)
Definition BTFDebug.cpp:358
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:386
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:584
BTFTypeStruct(const DICompositeType *STy, bool IsStruct, bool HasBitField, uint32_t NumMembers)
Represent either a struct or a union.
Definition BTFDebug.cpp:512
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:520
std::string getName()
Definition BTFDebug.cpp:594
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:767
BTFTypeTypeTag(uint32_t NextTypeId, StringRef Tag)
Definition BTFDebug.cpp:754
This is an important base class in LLVM.
Definition Constant.h:43
Basic type, like 'int' or 'float'.
unsigned getEncoding() const
DIDerivedType * getDiscriminator() const
DINodeArray getElements() const
DINodeArray getAnnotations() const
DIType * getBaseType() const
DINodeArray getAnnotations() const
Get annotations associated with this derived type.
DINodeArray getAnnotations() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Tagged DWARF-like metadata node.
LLVM_ABI dwarf::Tag getTag() const
Subprogram description. Uses SubclassData1.
LLVM_ABI BoundType getCount() const
Type array for a subprogram.
DITypeArray getTypeArray() const
Base class for types.
uint64_t getOffsetInBits() const
StringRef getName() const
bool isForwardDecl() const
uint64_t getSizeInBits() const
DIType * getType() const
const MachineInstr * CurMI
If nonnull, stores the current machine instruction we're processing.
AsmPrinter * Asm
Target of debug info emission.
MachineModuleInfo * MMI
Collected machine module information.
DebugLoc PrevInstLoc
Previous instruction's location information.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
A debug info location.
Definition DebugLoc.h:124
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:225
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:301
iterator begin()
Definition DenseMap.h:139
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:221
iterator end()
Definition DenseMap.h:143
DISubprogram * getSubprogram() const
Get the attached subprogram.
arg_iterator arg_begin()
Definition Function.h:868
size_t arg_size() const
Definition Function.h:901
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists.
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition MCContext.h:550
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
void addOperand(const MCOperand Op)
Definition MCInst.h:215
void setOpcode(unsigned Op)
Definition MCInst.h:201
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:138
static MCOperand createImm(int64_t Val)
Definition MCInst.h:145
This represents a section on linux, lots of unix variants and some bare metal systems.
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:573
void setAlignment(Align Value)
Definition MCSection.h:658
StringRef getName() const
Definition MCSection.h:643
Streaming machine code generation interface.
Definition MCStreamer.h:222
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition MCStreamer.h:397
void emitInt32(uint64_t Value)
Definition MCStreamer.h:760
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition MCSymbol.h:237
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition MCSymbol.h:251
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1433
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
VariableDbgInfoMapTy & getVariableDbgInfo()
const MachineBasicBlock & front() const
Representation of each machine instruction.
A description of a memory reference used in the backend.
const Module * getModule() const
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:301
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:591
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition StringRef.h:396
Class to represent struct types.
LLVM_ABI StringRef getName() const
Return the name for this struct type if it has an identity.
Definition Type.cpp:762
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
virtual TargetLoweringObjectFile * getObjFileLowering() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:185
bool erase(const ValueT &V)
Definition DenseSet.h:100
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ INT_SIGNED
Definition BTF.h:146
@ INT_BOOL
Definition BTF.h:148
@ VAR_GLOBAL_ALLOCATED
Linkage: ExternalLinkage.
Definition BTF.h:209
@ VAR_STATIC
Linkage: InternalLinkage.
Definition BTF.h:208
@ VAR_GLOBAL_EXTERNAL
Linkage: ExternalLinkage.
Definition BTF.h:210
@ VERSION
Definition BTF.h:57
@ MAGIC
Definition BTF.h:57
@ BPFFuncInfoSize
Definition BTF.h:73
@ HeaderSize
Definition BTF.h:61
@ ExtHeaderSize
Definition BTF.h:62
@ SecLineInfoSize
Definition BTF.h:71
@ SecFieldRelocSize
Definition BTF.h:72
@ BPFLineInfoSize
Definition BTF.h:74
@ SecFuncInfoSize
Definition BTF.h:70
@ BPFFieldRelocSize
Definition BTF.h:75
@ MAX_VLEN
Max # of struct/union/enum members or func args.
Definition BTF.h:93
@ ENUM_VALUE
Definition BTF.h:293
@ ENUM_VALUE_EXISTENCE
Definition BTF.h:292
@ BTF_TYPE_ID_REMOTE
Definition BTF.h:289
@ BTF_TYPE_ID_LOCAL
Definition BTF.h:288
@ FUNC_STATIC
Definition BTF.h:201
@ FUNC_EXTERN
Definition BTF.h:203
@ FUNC_GLOBAL
Definition BTF.h:202
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ SHT_PROGBITS
Definition ELF.h:1150
StringMapEntry< std::atomic< TypeEntryBody * > > TypeEntry
Definition TypePool.h:28
ScopedSetting scopedDisable()
Definition IOSandbox.h:36
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2553
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Global
Append to llvm.global_dtors.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
#define N
Represent one field relocation.
Definition BTFDebug.h:287
uint32_t RelocKind
What to patch the instruction.
Definition BTFDebug.h:291
const MCSymbol * Label
MCSymbol identifying insn for the reloc.
Definition BTFDebug.h:288
uint32_t TypeID
Type ID.
Definition BTFDebug.h:289
uint32_t OffsetNameOff
The string to traverse types.
Definition BTFDebug.h:290
Represent one func and its type id.
Definition BTFDebug.h:272
uint32_t TypeId
Type id referring to .BTF type section.
Definition BTFDebug.h:274
const MCSymbol * Label
Func MCSymbol.
Definition BTFDebug.h:273
uint32_t LineOff
line offset in the .BTF string table
Definition BTFDebug.h:281
MCSymbol * Label
MCSymbol identifying insn for the lineinfo.
Definition BTFDebug.h:279
uint32_t ColumnNum
the column number
Definition BTFDebug.h:283
uint32_t FileNameOff
file name offset in the .BTF string table
Definition BTFDebug.h:280
uint32_t LineNum
the line number
Definition BTFDebug.h:282
BTF_KIND_ENUM64 is followed by multiple "struct BTFEnum64".
Definition BTF.h:162
uint32_t NameOff
Enum name offset in the string table.
Definition BTF.h:163
uint32_t Val_Hi32
Enum member hi32 value.
Definition BTF.h:165
uint32_t Val_Lo32
Enum member lo32 value.
Definition BTF.h:164
BTF_KIND_ENUM is followed by multiple "struct BTFEnum".
Definition BTF.h:154
int32_t Val
Enum member value.
Definition BTF.h:156
uint32_t NameOff
Enum name offset in the string table.
Definition BTF.h:155
BTF_KIND_STRUCT and BTF_KIND_UNION are followed by multiple "struct BTFMember".
Definition BTF.h:185
uint32_t NameOff
Member name offset in the string table.
Definition BTF.h:186
uint32_t Offset
BitOffset or BitFieldSize+BitOffset.
Definition BTF.h:188
uint32_t Type
Member type.
Definition BTF.h:187
BTF_KIND_FUNC_PROTO are followed by multiple "struct BTFParam".
Definition BTF.h:194
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1438