LLVM 24.0.0git
BPFAbstractMemberAccess.cpp
Go to the documentation of this file.
1//===------ BPFAbstractMemberAccess.cpp - Abstracting Member Accesses -----===//
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 pass abstracted struct/union member accesses in order to support
10// compile-once run-everywhere (CO-RE). The CO-RE intends to compile the program
11// which can run on different kernels. In particular, if bpf program tries to
12// access a particular kernel data structure member, the details of the
13// intermediate member access will be remembered so bpf loader can do
14// necessary adjustment right before program loading.
15//
16// For example,
17//
18// struct s {
19// int a;
20// int b;
21// };
22// struct t {
23// struct s c;
24// int d;
25// };
26// struct t e;
27//
28// For the member access e.c.b, the compiler will generate code
29// &e + 4
30//
31// The compile-once run-everywhere instead generates the following code
32// r = 4
33// &e + r
34// The "4" in "r = 4" can be changed based on a particular kernel version.
35// For example, on a particular kernel version, if struct s is changed to
36//
37// struct s {
38// int new_field;
39// int a;
40// int b;
41// }
42//
43// By repeating the member access on the host, the bpf loader can
44// adjust "r = 4" as "r = 8".
45//
46// This feature relies on the following three intrinsic calls:
47// addr = preserve_array_access_index(base, dimension, index)
48// addr = preserve_union_access_index(base, di_index)
49// !llvm.preserve.access.index <union_ditype>
50// addr = preserve_struct_access_index(base, gep_index, di_index)
51// !llvm.preserve.access.index <struct_ditype>
52//
53// Bitfield member access needs special attention. User cannot take the
54// address of a bitfield acceess. To facilitate kernel verifier
55// for easy bitfield code optimization, a new clang intrinsic is introduced:
56// uint32_t __builtin_preserve_field_info(member_access, info_kind)
57// In IR, a chain with two (or more) intrinsic calls will be generated:
58// ...
59// addr = preserve_struct_access_index(base, 1, 1) !struct s
60// uint32_t result = bpf_preserve_field_info(addr, info_kind)
61//
62// Suppose the info_kind is FIELD_SIGNEDNESS,
63// The above two IR intrinsics will be replaced with
64// a relocatable insn:
65// signness = /* signness of member_access */
66// and signness can be changed by bpf loader based on the
67// types on the host.
68//
69// User can also test whether a field exists or not with
70// uint32_t result = bpf_preserve_field_info(member_access, FIELD_EXISTENCE)
71// The field will be always available (result = 1) during initial
72// compilation, but bpf loader can patch with the correct value
73// on the target host where the member_access may or may not be available
74//
75//===----------------------------------------------------------------------===//
76
77#include "BPF.h"
78#include "BPFCORE.h"
79#include "BPFTargetMachine.h"
80#include "llvm/ADT/ArrayRef.h"
81#include "llvm/ADT/MapVector.h"
82#include "llvm/ADT/STLExtras.h"
84#include "llvm/ADT/Twine.h"
89#include "llvm/IR/Instruction.h"
91#include "llvm/IR/IntrinsicsBPF.h"
92#include "llvm/IR/Module.h"
93#include "llvm/IR/PassManager.h"
94#include "llvm/IR/Type.h"
95#include "llvm/IR/User.h"
96#include "llvm/IR/Value.h"
97#include "llvm/IR/ValueHandle.h"
98#include "llvm/Pass.h"
100#include <optional>
101
102#define DEBUG_TYPE "bpf-abstract-member-access"
103
104namespace llvm {
106
109 // Type names may contain ':' and '$'. Only the suffix has a fixed format.
110 auto [Prefix, AccessString] = Name.rsplit('$');
111 auto [NameAndKind, PatchString] = Prefix.rsplit(':');
112 StringRef KindString = NameAndKind.rsplit(':').second;
114 int64_t PatchImm;
115 if (AccessString.empty() || KindString.getAsInteger(10, Kind) ||
116 PatchString.getAsInteger(10, PatchImm))
117 reportFatalInternalError(Twine("Invalid BPF CO-RE relocation global ") +
118 Name);
119 return {static_cast<BTF::PatchableRelocKind>(Kind), PatchImm, AccessString};
120}
121
124 Instruction *Before) {
126 M, Intrinsic::bpf_passthrough, {Input->getType(), Input->getType()});
127 Constant *SeqNumVal = ConstantInt::get(Type::getInt32Ty(BB->getContext()),
129
130 auto *NewInst = CallInst::Create(Fn, {SeqNumVal, Input});
131 NewInst->insertBefore(Before->getIterator());
132 return NewInst;
133}
134} // namespace llvm
135
136using namespace llvm;
137
138namespace {
139class BPFAbstractMemberAccess final {
140public:
141 BPFAbstractMemberAccess(BPFTargetMachine *TM) : TM(TM) {}
142
143 bool run(Function &F);
144
145 struct CallInfo {
146 uint32_t Kind;
147 uint32_t AccessIndex;
148 MaybeAlign RecordAlignment;
149 MDNode *Metadata;
150 WeakTrackingVH Base;
151 };
152
153private:
154 enum : uint32_t {
155 BPFPreserveArrayAI = 1,
156 BPFPreserveUnionAI = 2,
157 BPFPreserveStructAI = 3,
158 BPFPreserveFieldInfoAI = 4,
159 };
160
161 TargetMachine *TM;
162 const DataLayout *DL = nullptr;
163 Module *M = nullptr;
164
165 // A map to link preserve_*_access_index intrinsic calls.
166 std::map<CallInst *, std::pair<CallInst *, CallInfo>> AIChain;
167 // A map to hold all the base preserve_*_access_index intrinsic calls.
168 // The base call is not an input of any other preserve_*
169 // intrinsics.
170 // Iterated below, so the order can't come from the addresses.
171 SmallMapVector<CallInst *, CallInfo, 4> BaseAICalls;
172 // A map to hold <AnonRecord, TypeDef> relationships
173 std::map<DICompositeType *, DIDerivedType *> AnonRecords;
174
175 void CheckAnonRecordType(DIDerivedType *ParentTy, DIType *Ty);
176 void CheckCompositeType(DIDerivedType *ParentTy, DICompositeType *CTy);
177 void CheckDerivedType(DIDerivedType *ParentTy, DIDerivedType *DTy);
178 void ResetMetadata(struct CallInfo &CInfo);
179
180 bool doTransformation(Function &F);
181
182 void traceAICall(CallInst *Call, CallInfo &ParentInfo);
183 void traceBitCast(BitCastInst *BitCast, CallInst *Parent,
184 CallInfo &ParentInfo);
185 void traceGEP(GetElementPtrInst *GEP, CallInst *Parent,
186 CallInfo &ParentInfo);
187 void collectAICallChains(Function &F);
188
189 bool IsPreserveDIAccessIndexCall(const CallInst *Call, CallInfo &Cinfo);
190 bool IsValidAIChain(const MDNode *ParentMeta, uint32_t ParentAI,
191 const MDNode *ChildMeta);
192 bool removePreserveAccessIndexIntrinsic(Function &F);
193 void GetStorageBitRange(DIDerivedType *MemberTy, Align RecordAlignment,
194 uint32_t &StartBitOffset, uint32_t &EndBitOffset);
195 uint32_t GetFieldInfo(uint32_t InfoKind, DICompositeType *CTy,
196 uint32_t AccessIndex, uint32_t PatchImm,
197 MaybeAlign RecordAlignment);
198
199 struct AccessRoot {
200 DIType *Type;
201 uint32_t Index;
202 };
203 static std::optional<AccessRoot>
204 consumeAccessRoot(SmallVectorImpl<CallInfo> &CallStack);
205 Value *computeFieldAccess(CallInst *Call, const CallInfo &Terminal,
206 std::string &RelocSuffix, DIType *&RootType);
207 struct EnumAccess {
208 size_t Index;
209 StringRef Value;
210 };
211 static EnumAccess computeEnumAccess(const CallInst *Call, const DIType *Ty);
212 DIType *computeTypeAccess(CallInst *Call, const CallInfo &CInfo,
213 std::string &RelocSuffix);
214 bool transformGEPChain(CallInst *Call, const CallInfo &CInfo);
215};
216
217} // End anonymous namespace
218
219bool BPFAbstractMemberAccess::run(Function &F) {
220 LLVM_DEBUG(dbgs() << "********** Abstract Member Accesses **********\n");
221
222 M = F.getParent();
223 if (!M)
224 return false;
225
226 // Bail out if no debug info.
227 if (M->debug_compile_units().empty())
228 return false;
229
230 // For each argument/return/local_variable type, trace the type
231 // pattern like '[derived_type]* [composite_type]' to check
232 // and remember (anon record -> typedef) relations where the
233 // anon record is defined as
234 // typedef [const/volatile/restrict]* [anon record]
235 DISubprogram *SP = F.getSubprogram();
236 if (SP && SP->isDefinition()) {
237 for (DIType *Ty: SP->getType()->getTypeArray())
238 CheckAnonRecordType(nullptr, Ty);
239 for (const MDNode *DN : SP->getRetainedNodes()) {
240 if (const auto *DV = dyn_cast<DILocalVariable>(DN))
241 CheckAnonRecordType(nullptr, DV->getType());
242 }
243 }
244
245 DL = &M->getDataLayout();
246 return doTransformation(F);
247}
248
249void BPFAbstractMemberAccess::ResetMetadata(struct CallInfo &CInfo) {
250 if (auto Ty = dyn_cast<DICompositeType>(CInfo.Metadata)) {
251 auto It = AnonRecords.find(Ty);
252 if (It != AnonRecords.end() && It->second != nullptr)
253 CInfo.Metadata = It->second;
254 }
255}
256
257void BPFAbstractMemberAccess::CheckCompositeType(DIDerivedType *ParentTy,
258 DICompositeType *CTy) {
259 if (!CTy->getName().empty() || !ParentTy ||
260 ParentTy->getTag() != dwarf::DW_TAG_typedef)
261 return;
262
263 auto [It, Inserted] = AnonRecords.try_emplace(CTy, ParentTy);
264 // Two or more typedef's may point to the same anon record.
265 // If this is the case, set the typedef DIType to be nullptr
266 // to indicate the duplication case.
267 if (!Inserted && It->second != ParentTy)
268 It->second = nullptr;
269}
270
271void BPFAbstractMemberAccess::CheckDerivedType(DIDerivedType *ParentTy,
272 DIDerivedType *DTy) {
273 DIType *BaseType = DTy->getBaseType();
274 if (!BaseType)
275 return;
276
277 unsigned Tag = DTy->getTag();
278 if (Tag == dwarf::DW_TAG_pointer_type)
279 CheckAnonRecordType(nullptr, BaseType);
280 else if (Tag == dwarf::DW_TAG_typedef)
281 CheckAnonRecordType(DTy, BaseType);
282 else
283 CheckAnonRecordType(ParentTy, BaseType);
284}
285
286void BPFAbstractMemberAccess::CheckAnonRecordType(DIDerivedType *ParentTy,
287 DIType *Ty) {
288 if (!Ty)
289 return;
290
291 if (auto *CTy = dyn_cast<DICompositeType>(Ty))
292 return CheckCompositeType(ParentTy, CTy);
293 else if (auto *DTy = dyn_cast<DIDerivedType>(Ty))
294 return CheckDerivedType(ParentTy, DTy);
295}
296
297static bool SkipDIDerivedTag(unsigned Tag, bool skipTypedef) {
298 if (Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type &&
299 Tag != dwarf::DW_TAG_volatile_type &&
300 Tag != dwarf::DW_TAG_restrict_type &&
301 Tag != dwarf::DW_TAG_member)
302 return false;
303 if (Tag == dwarf::DW_TAG_typedef && !skipTypedef)
304 return false;
305 return true;
306}
307
308static DIType * stripQualifiers(DIType *Ty, bool skipTypedef = true) {
309 while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
310 if (!SkipDIDerivedTag(DTy->getTag(), skipTypedef))
311 break;
312 Ty = DTy->getBaseType();
313 }
314 return Ty;
315}
316
317static const DIType * stripQualifiers(const DIType *Ty) {
318 while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
319 if (!SkipDIDerivedTag(DTy->getTag(), true))
320 break;
321 Ty = DTy->getBaseType();
322 }
323 return Ty;
324}
325
326static uint32_t calcArraySize(const DICompositeType *CTy, uint32_t StartDim) {
327 DINodeArray Elements = CTy->getElements();
328 uint32_t DimSize = 1;
329 for (uint32_t I = StartDim; I < Elements.size(); ++I) {
330 if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
331 if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
332 const DISubrange *SR = cast<DISubrange>(Element);
333 auto *CI = dyn_cast<ConstantInt *>(SR->getCount());
334 DimSize *= CI->getSExtValue();
335 }
336 }
337
338 return DimSize;
339}
340
341/// Return the number of innermost elements in \p Ty, looking through array
342/// element types such as Row in typedef struct S Row[3]. \p Ty is updated to
343/// the innermost element type.
345 uint32_t Count = 1;
346 for (;;) {
348 if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
349 return Count;
350 Count *= calcArraySize(Array, 0);
351 Ty = Array->getBaseType();
352 }
353}
354
356 // Element type is stored in an elementtype() attribute on the first param.
357 return Call->getParamElementType(0);
358}
359
360static uint64_t getConstant(const Value *IndexValue) {
361 const ConstantInt *CV = dyn_cast<ConstantInt>(IndexValue);
362 assert(CV);
363 return CV->getValue().getZExtValue();
364}
365
366/// Check whether a call is a preserve_*_access_index intrinsic call or not.
367bool BPFAbstractMemberAccess::IsPreserveDIAccessIndexCall(const CallInst *Call,
368 CallInfo &CInfo) {
369 if (!Call)
370 return false;
371
372 const auto *GV = dyn_cast<GlobalValue>(Call->getCalledOperand());
373 if (!GV)
374 return false;
375 if (GV->getName().starts_with("llvm.preserve.array.access.index")) {
376 CInfo.Kind = BPFPreserveArrayAI;
377 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
378 if (!CInfo.Metadata)
379 report_fatal_error("Missing metadata for llvm.preserve.array.access.index intrinsic");
380 CInfo.AccessIndex = getConstant(Call->getArgOperand(2));
381 CInfo.Base = Call->getArgOperand(0);
382 CInfo.RecordAlignment = DL->getABITypeAlign(getBaseElementType(Call));
383 return true;
384 }
385 if (GV->getName().starts_with("llvm.preserve.union.access.index")) {
386 CInfo.Kind = BPFPreserveUnionAI;
387 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
388 if (!CInfo.Metadata)
389 report_fatal_error("Missing metadata for llvm.preserve.union.access.index intrinsic");
390 ResetMetadata(CInfo);
391 CInfo.AccessIndex = getConstant(Call->getArgOperand(1));
392 CInfo.Base = Call->getArgOperand(0);
393 return true;
394 }
395 if (GV->getName().starts_with("llvm.preserve.struct.access.index")) {
396 CInfo.Kind = BPFPreserveStructAI;
397 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
398 if (!CInfo.Metadata)
399 report_fatal_error("Missing metadata for llvm.preserve.struct.access.index intrinsic");
400 ResetMetadata(CInfo);
401 CInfo.AccessIndex = getConstant(Call->getArgOperand(2));
402 CInfo.Base = Call->getArgOperand(0);
403 CInfo.RecordAlignment = DL->getABITypeAlign(getBaseElementType(Call));
404 return true;
405 }
406 if (GV->getName().starts_with("llvm.bpf.preserve.field.info")) {
407 CInfo.Kind = BPFPreserveFieldInfoAI;
408 CInfo.Metadata = nullptr;
409 // Check validity of info_kind as clang did not check this.
411 if (InfoKind >= BTF::MAX_FIELD_RELOC_KIND)
412 report_fatal_error("Incorrect info_kind for llvm.bpf.preserve.field.info intrinsic");
413 CInfo.AccessIndex = InfoKind;
414 return true;
415 }
416 if (GV->getName().starts_with("llvm.bpf.preserve.type.info")) {
417 CInfo.Kind = BPFPreserveFieldInfoAI;
418 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
419 if (!CInfo.Metadata)
420 report_fatal_error("Missing metadata for llvm.preserve.type.info intrinsic");
423 report_fatal_error("Incorrect flag for llvm.bpf.preserve.type.info intrinsic");
425 CInfo.AccessIndex = BTF::TYPE_EXISTENCE;
427 CInfo.AccessIndex = BTF::TYPE_MATCH;
428 else
429 CInfo.AccessIndex = BTF::TYPE_SIZE;
430 return true;
431 }
432 if (GV->getName().starts_with("llvm.bpf.preserve.enum.value")) {
433 CInfo.Kind = BPFPreserveFieldInfoAI;
434 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
435 if (!CInfo.Metadata)
436 report_fatal_error("Missing metadata for llvm.preserve.enum.value intrinsic");
439 report_fatal_error("Incorrect flag for llvm.bpf.preserve.enum.value intrinsic");
441 CInfo.AccessIndex = BTF::ENUM_VALUE_EXISTENCE;
442 else
443 CInfo.AccessIndex = BTF::ENUM_VALUE;
444 return true;
445 }
446
447 return false;
448}
449
450static void replaceWithGEP(CallInst *Call, uint32_t DimensionIndex,
451 uint32_t GEPIndex) {
452 uint32_t Dimension = 1;
453 if (DimensionIndex > 0)
454 Dimension = getConstant(Call->getArgOperand(DimensionIndex));
455
456 Constant *Zero =
457 ConstantInt::get(Type::getInt32Ty(Call->getParent()->getContext()), 0);
458 SmallVector<Value *, 4> IdxList(Dimension, Zero);
459 IdxList.push_back(Call->getArgOperand(GEPIndex));
460
462 Call->getArgOperand(0), IdxList,
463 "", Call->getIterator());
464 Call->replaceAllUsesWith(GEP);
465 Call->eraseFromParent();
466}
467
471
475
477 Call->replaceAllUsesWith(Call->getArgOperand(0));
478 Call->eraseFromParent();
479}
480
481bool BPFAbstractMemberAccess::removePreserveAccessIndexIntrinsic(Function &F) {
482 std::vector<CallInst *> PreserveArrayIndexCalls;
483 std::vector<CallInst *> PreserveUnionIndexCalls;
484 std::vector<CallInst *> PreserveStructIndexCalls;
485 std::vector<CallInst *> PreserveFieldInfoCalls;
486 bool Found = false;
487
488 for (auto &BB : F)
489 for (auto &I : BB) {
490 auto *Call = dyn_cast<CallInst>(&I);
491 CallInfo CInfo;
492 if (!IsPreserveDIAccessIndexCall(Call, CInfo))
493 continue;
494
495 Found = true;
496 if (CInfo.Kind == BPFPreserveArrayAI)
497 PreserveArrayIndexCalls.push_back(Call);
498 else if (CInfo.Kind == BPFPreserveUnionAI)
499 PreserveUnionIndexCalls.push_back(Call);
500 else if (CInfo.Kind == BPFPreserveFieldInfoAI)
501 PreserveFieldInfoCalls.push_back(Call);
502 else
503 PreserveStructIndexCalls.push_back(Call);
504 }
505
506 // A preserve_field_info(), preserve_type_info() or preserve_enum_value()
507 // call left here has an unused result, so it is not relocated. It has no
508 // side effects, so just remove it.
509 for (CallInst *Call : PreserveFieldInfoCalls)
510 if (Call->use_empty())
511 Call->eraseFromParent();
512
513 // do the following transformation:
514 // . addr = preserve_array_access_index(base, dimension, index)
515 // is transformed to
516 // addr = GEP(base, dimenion's zero's, index)
517 // . addr = preserve_union_access_index(base, di_index)
518 // is transformed to
519 // addr = base, i.e., all usages of "addr" are replaced by "base".
520 // . addr = preserve_struct_access_index(base, gep_index, di_index)
521 // is transformed to
522 // addr = GEP(base, 0, gep_index)
523 for (CallInst *Call : PreserveArrayIndexCalls)
525 for (CallInst *Call : PreserveStructIndexCalls)
527 for (CallInst *Call : PreserveUnionIndexCalls)
529
530 return Found;
531}
532
533/// Check whether the access index chain is valid. We check
534/// here because there may be type casts between two
535/// access indexes. We want to ensure memory access still valid.
536bool BPFAbstractMemberAccess::IsValidAIChain(const MDNode *ParentType,
537 uint32_t ParentAI,
538 const MDNode *ChildType) {
539 if (!ChildType)
540 return true; // preserve_field_info, no type comparison needed.
541
542 const DIType *PType = stripQualifiers(cast<DIType>(ParentType));
543 const DIType *CType = stripQualifiers(cast<DIType>(ChildType));
544
545 // Child is a derived/pointer type, which is due to type casting.
546 // Pointer type cannot be in the middle of chain.
547 if (isa<DIDerivedType>(CType))
548 return false;
549
550 // Parent is a pointer type.
551 if (const auto *PtrTy = dyn_cast<DIDerivedType>(PType)) {
552 if (PtrTy->getTag() != dwarf::DW_TAG_pointer_type)
553 return false;
554 return stripQualifiers(PtrTy->getBaseType()) == CType;
555 }
556
557 // Otherwise, struct/union/array types
558 const auto *PTy = dyn_cast<DICompositeType>(PType);
559 const auto *CTy = dyn_cast<DICompositeType>(CType);
560 assert(PTy && CTy && "ParentType or ChildType is null or not composite");
561
562 uint32_t PTyTag = PTy->getTag();
563 assert(PTyTag == dwarf::DW_TAG_array_type ||
564 PTyTag == dwarf::DW_TAG_structure_type ||
565 PTyTag == dwarf::DW_TAG_union_type);
566
567 uint32_t CTyTag = CTy->getTag();
568 assert(CTyTag == dwarf::DW_TAG_array_type ||
569 CTyTag == dwarf::DW_TAG_structure_type ||
570 CTyTag == dwarf::DW_TAG_union_type);
571
572 // Multi dimensional arrays, base element should be the same. Otherwise the
573 // child may still be the element type, e.g. Row in Row a[2] with
574 // typedef struct S Row[3].
575 if (PTyTag == dwarf::DW_TAG_array_type && PTyTag == CTyTag &&
576 PTy->getBaseType() == CTy->getBaseType())
577 return true;
578
579 DIType *Ty;
580 if (PTyTag == dwarf::DW_TAG_array_type)
581 Ty = PTy->getBaseType();
582 else
583 Ty = dyn_cast<DIType>(PTy->getElements()[ParentAI]);
584
586}
587
588void BPFAbstractMemberAccess::traceAICall(CallInst *Call,
589 CallInfo &ParentInfo) {
590 for (Instruction *Inst : Call->users()) {
591 if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
592 traceBitCast(BI, Call, ParentInfo);
593 } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
594 CallInfo ChildInfo;
595
596 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
597 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
598 ChildInfo.Metadata)) {
599 AIChain[CI] = std::make_pair(Call, ParentInfo);
600 traceAICall(CI, ChildInfo);
601 } else {
602 BaseAICalls[Call] = ParentInfo;
603 }
604 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
605 if (GI->hasAllZeroIndices())
606 traceGEP(GI, Call, ParentInfo);
607 else
608 BaseAICalls[Call] = ParentInfo;
609 } else {
610 BaseAICalls[Call] = ParentInfo;
611 }
612 }
613}
614
615void BPFAbstractMemberAccess::traceBitCast(BitCastInst *BitCast,
616 CallInst *Parent,
617 CallInfo &ParentInfo) {
618 for (Instruction *Inst : BitCast->users()) {
619 if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
620 traceBitCast(BI, Parent, ParentInfo);
621 } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
622 CallInfo ChildInfo;
623 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
624 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
625 ChildInfo.Metadata)) {
626 AIChain[CI] = std::make_pair(Parent, ParentInfo);
627 traceAICall(CI, ChildInfo);
628 } else {
629 BaseAICalls[Parent] = ParentInfo;
630 }
631 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
632 if (GI->hasAllZeroIndices())
633 traceGEP(GI, Parent, ParentInfo);
634 else
635 BaseAICalls[Parent] = ParentInfo;
636 } else {
637 BaseAICalls[Parent] = ParentInfo;
638 }
639 }
640}
641
642void BPFAbstractMemberAccess::traceGEP(GetElementPtrInst *GEP, CallInst *Parent,
643 CallInfo &ParentInfo) {
644 for (Instruction *Inst : GEP->users()) {
645 if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
646 traceBitCast(BI, Parent, ParentInfo);
647 } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
648 CallInfo ChildInfo;
649 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
650 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
651 ChildInfo.Metadata)) {
652 AIChain[CI] = std::make_pair(Parent, ParentInfo);
653 traceAICall(CI, ChildInfo);
654 } else {
655 BaseAICalls[Parent] = ParentInfo;
656 }
657 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
658 if (GI->hasAllZeroIndices())
659 traceGEP(GI, Parent, ParentInfo);
660 else
661 BaseAICalls[Parent] = ParentInfo;
662 } else {
663 BaseAICalls[Parent] = ParentInfo;
664 }
665 }
666}
667
668void BPFAbstractMemberAccess::collectAICallChains(Function &F) {
669 AIChain.clear();
670 BaseAICalls.clear();
671
672 for (auto &BB : F)
673 for (auto &I : BB) {
674 CallInfo CInfo;
675 auto *Call = dyn_cast<CallInst>(&I);
676 if (!IsPreserveDIAccessIndexCall(Call, CInfo) ||
677 AIChain.find(Call) != AIChain.end())
678 continue;
679
680 traceAICall(Call, CInfo);
681 }
682}
683
684/// Get the start and the end of storage offset for \p MemberTy.
685void BPFAbstractMemberAccess::GetStorageBitRange(DIDerivedType *MemberTy,
686 Align RecordAlignment,
687 uint32_t &StartBitOffset,
688 uint32_t &EndBitOffset) {
689 uint32_t MemberBitSize = MemberTy->getSizeInBits();
690 uint32_t MemberBitOffset = MemberTy->getOffsetInBits();
691
692 if (RecordAlignment > 8) {
693 // If the Bits are within an aligned 8-byte, set the RecordAlignment
694 // to 8, other report the fatal error.
695 if (MemberBitOffset / 64 != (MemberBitOffset + MemberBitSize) / 64)
696 report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info, "
697 "requiring too big alignment");
698 RecordAlignment = Align(8);
699 }
700
701 uint32_t AlignBits = RecordAlignment.value() * 8;
702 if (MemberBitSize > AlignBits)
703 report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info, "
704 "bitfield size greater than record alignment");
705
706 StartBitOffset = MemberBitOffset & ~(AlignBits - 1);
707 if ((StartBitOffset + AlignBits) < (MemberBitOffset + MemberBitSize))
708 report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info, "
709 "cross alignment boundary");
710 EndBitOffset = StartBitOffset + AlignBits;
711}
712
713uint32_t BPFAbstractMemberAccess::GetFieldInfo(uint32_t InfoKind,
714 DICompositeType *CTy,
715 uint32_t AccessIndex,
716 uint32_t PatchImm,
717 MaybeAlign RecordAlignment) {
718 if (InfoKind == BTF::FIELD_EXISTENCE)
719 return 1;
720
721 uint32_t Tag = CTy->getTag();
722 if (InfoKind == BTF::FIELD_BYTE_OFFSET) {
723 if (Tag == dwarf::DW_TAG_array_type) {
724 auto *EltTy = stripQualifiers(CTy->getBaseType());
725 PatchImm += AccessIndex * calcArraySize(CTy, 1) *
726 (EltTy->getSizeInBits() >> 3);
727 } else if (Tag == dwarf::DW_TAG_structure_type) {
728 auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
729 if (!MemberTy->isBitField()) {
730 PatchImm += MemberTy->getOffsetInBits() >> 3;
731 } else {
732 unsigned SBitOffset, NextSBitOffset;
733 GetStorageBitRange(MemberTy, *RecordAlignment, SBitOffset,
734 NextSBitOffset);
735 PatchImm += SBitOffset >> 3;
736 }
737 }
738 return PatchImm;
739 }
740
741 if (InfoKind == BTF::FIELD_BYTE_SIZE) {
742 if (Tag == dwarf::DW_TAG_array_type) {
743 auto *EltTy = stripQualifiers(CTy->getBaseType());
744 return calcArraySize(CTy, 1) * (EltTy->getSizeInBits() >> 3);
745 } else {
746 auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
747 uint32_t SizeInBits = MemberTy->getSizeInBits();
748 if (!MemberTy->isBitField())
749 return SizeInBits >> 3;
750
751 unsigned SBitOffset, NextSBitOffset;
752 GetStorageBitRange(MemberTy, *RecordAlignment, SBitOffset,
753 NextSBitOffset);
754 SizeInBits = NextSBitOffset - SBitOffset;
755 if (SizeInBits & (SizeInBits - 1))
756 report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info");
757 return SizeInBits >> 3;
758 }
759 }
760
761 if (InfoKind == BTF::FIELD_SIGNEDNESS) {
762 const DIType *BaseTy;
763 if (Tag == dwarf::DW_TAG_array_type) {
764 // Signedness only checked when final array elements are accessed.
765 if (CTy->getElements().size() != 1)
766 report_fatal_error("Invalid array expression for llvm.bpf.preserve.field.info");
767 BaseTy = stripQualifiers(CTy->getBaseType());
768 } else {
769 auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
770 BaseTy = stripQualifiers(MemberTy->getBaseType());
771 }
772
773 // Only basic types and enum types have signedness.
774 const auto *BTy = dyn_cast<DIBasicType>(BaseTy);
775 while (!BTy) {
776 const auto *CompTy = dyn_cast<DICompositeType>(BaseTy);
777 // Report an error if the field expression does not have signedness.
778 if (!CompTy || CompTy->getTag() != dwarf::DW_TAG_enumeration_type)
779 report_fatal_error("Invalid field expression for llvm.bpf.preserve.field.info");
780 BaseTy = stripQualifiers(CompTy->getBaseType());
781 BTy = dyn_cast<DIBasicType>(BaseTy);
782 }
783 uint32_t Encoding = BTy->getEncoding();
784 return (Encoding == dwarf::DW_ATE_signed || Encoding == dwarf::DW_ATE_signed_char);
785 }
786
787 if (InfoKind == BTF::FIELD_LSHIFT_U64) {
788 // The value is loaded into a value with FIELD_BYTE_SIZE size,
789 // and then zero or sign extended to U64.
790 // FIELD_LSHIFT_U64 and FIELD_RSHIFT_U64 are operations
791 // to extract the original value.
792 const Triple &Triple = TM->getTargetTriple();
793 DIDerivedType *MemberTy = nullptr;
794 bool IsBitField = false;
795 uint32_t SizeInBits;
796
797 if (Tag == dwarf::DW_TAG_array_type) {
798 auto *EltTy = stripQualifiers(CTy->getBaseType());
799 SizeInBits = calcArraySize(CTy, 1) * EltTy->getSizeInBits();
800 } else {
801 MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
802 SizeInBits = MemberTy->getSizeInBits();
803 IsBitField = MemberTy->isBitField();
804 }
805
806 if (!IsBitField) {
807 if (SizeInBits > 64)
808 report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
809 return 64 - SizeInBits;
810 }
811
812 unsigned SBitOffset, NextSBitOffset;
813 GetStorageBitRange(MemberTy, *RecordAlignment, SBitOffset, NextSBitOffset);
814 if (NextSBitOffset - SBitOffset > 64)
815 report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
816
817 unsigned OffsetInBits = MemberTy->getOffsetInBits();
819 return SBitOffset + 64 - OffsetInBits - SizeInBits;
820 else
821 return OffsetInBits + 64 - NextSBitOffset;
822 }
823
824 if (InfoKind == BTF::FIELD_RSHIFT_U64) {
825 DIDerivedType *MemberTy = nullptr;
826 bool IsBitField = false;
827 uint32_t SizeInBits;
828 if (Tag == dwarf::DW_TAG_array_type) {
829 auto *EltTy = stripQualifiers(CTy->getBaseType());
830 SizeInBits = calcArraySize(CTy, 1) * EltTy->getSizeInBits();
831 } else {
832 MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
833 SizeInBits = MemberTy->getSizeInBits();
834 IsBitField = MemberTy->isBitField();
835 }
836
837 if (!IsBitField) {
838 if (SizeInBits > 64)
839 report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
840 return 64 - SizeInBits;
841 }
842
843 unsigned SBitOffset, NextSBitOffset;
844 GetStorageBitRange(MemberTy, *RecordAlignment, SBitOffset, NextSBitOffset);
845 if (NextSBitOffset - SBitOffset > 64)
846 report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
847
848 return 64 - SizeInBits;
849 }
850
851 llvm_unreachable("Unknown llvm.bpf.preserve.field.info info kind");
852}
853
854/// Consume leading array accesses, leaving the first record access on the
855/// stack.
856std::optional<BPFAbstractMemberAccess::AccessRoot>
857BPFAbstractMemberAccess::consumeAccessRoot(
858 SmallVectorImpl<CallInfo> &CallStack) {
859 // Fold the leading array accesses into one index, counted in units of the
860 // innermost element, such as struct S in Row a[2] with
861 // typedef struct S Row[3].
862 uint32_t FirstIndex = 0;
863 DIType *ElementTy = nullptr;
864 while (!CallStack.empty() && CallStack.back().Kind == BPFPreserveArrayAI) {
865 const CallInfo &CInfo = CallStack.back();
866 auto *Ty = stripQualifiers(cast<DIType>(CInfo.Metadata));
867 uint32_t Stride;
868 switch (Ty->getTag()) {
869 case dwarf::DW_TAG_array_type: {
870 auto *Array = cast<DICompositeType>(Ty);
871 ElementTy = Array->getBaseType();
872 Stride = calcArraySize(Array, 1) * calcElementCount(ElementTy);
873 break;
874 }
875 case dwarf::DW_TAG_pointer_type:
876 ElementTy = cast<DIDerivedType>(Ty)->getBaseType();
877 Stride = calcElementCount(ElementTy);
878 break;
879 default:
880 llvm_unreachable("Expected an array or pointer type");
881 }
882 FirstIndex += CInfo.AccessIndex * Stride;
883 CallStack.pop_back();
884 }
885
886 if (!ElementTy) {
887 // A typedef may be the only name the loader can match for this record.
888 const CallInfo &CInfo = CallStack.back();
889 assert(CInfo.Kind == BPFPreserveStructAI ||
890 CInfo.Kind == BPFPreserveUnionAI);
891 return AccessRoot{
892 stripQualifiers(cast<DIType>(CInfo.Metadata), /*skipTypedef=*/false),
893 0};
894 }
895
896 // The innermost element supplies the relocation root.
897 auto *Record = stripQualifiers(ElementTy);
898 switch (Record->getTag()) {
899 case dwarf::DW_TAG_structure_type:
900 case dwarf::DW_TAG_union_type:
901 // An anonymous record can only be matched by its typedef name.
902 return AccessRoot{Record->getName().empty()
903 ? stripQualifiers(ElementTy, /*skipTypedef=*/false)
904 : Record,
905 FirstIndex};
906 default:
907 return std::nullopt;
908 }
909}
910
911static std::string formatAmaSuffix(uint32_t Kind, int64_t PatchImm,
912 const Twine &AccessString) {
913 return (":" + Twine(Kind) + ":" + Twine(PatchImm) + "$" + AccessString).str();
914}
915
916/// Compute the base pointer, root type and relocation suffix of a field access.
917Value *BPFAbstractMemberAccess::computeFieldAccess(CallInst *Call,
918 const CallInfo &Terminal,
919 std::string &RelocSuffix,
920 DIType *&RootType) {
921 // Put the access chain into a stack with the top as the head of the chain.
922 // A terminal preserve_field_info call is not part of the chain.
923 const bool IsFieldInfo = Terminal.Kind == BPFPreserveFieldInfoAI;
924 SmallVector<CallInfo, 4> CallStack;
925 if (!IsFieldInfo)
926 CallStack.push_back(Terminal);
927 for (auto It = AIChain.find(Call); It != AIChain.end();
928 It = AIChain.find(It->second.first))
929 CallStack.push_back(It->second.second);
930
931 Value *const Base = CallStack.back().Base;
932 const auto Root = consumeAccessRoot(CallStack);
933 if (!Root) {
934 if (IsFieldInfo)
936 "Invalid field access for llvm.preserve.field.info intrinsic");
937 // With no record root, accesses such as &p[4] (int *p) or &a[2][3]
938 // (int a[10][20]) lower to ordinary GEPs.
939 return nullptr;
940 }
941 assert(!Root->Type->getName().empty());
942 const uint32_t InfoKind =
943 IsFieldInfo ? Terminal.AccessIndex : BTF::FIELD_BYTE_OFFSET;
944 uint32_t PatchImm =
945 Root->Index * (stripQualifiers(Root->Type)->getSizeInBits() >> 3);
946 std::string AccessString = std::to_string(Root->Index);
947
948 // Build the access string and compute the local byte offset or requested
949 // field property while each access still has its debug type.
950 ArrayRef<CallInfo> Fields = CallStack;
951 while (!Fields.empty()) {
952 const CallInfo &CInfo = Fields.back();
953 Fields = Fields.drop_back();
954
955 // Access Index
956 uint64_t AccessIndex = CInfo.AccessIndex;
957 MDNode *MDN = CInfo.Metadata;
958 // At this stage, it cannot be pointer type.
960
961 uint64_t BTFIndex = AccessIndex;
962 if (CTy->getTag() == dwarf::DW_TAG_structure_type) {
963 DINodeArray Elements = CTy->getElements();
964 uint64_t Offset = getBTFRecordElementOffset(Elements[AccessIndex]);
965 // Find this element's position in the stable offset order without
966 // sorting the whole record for every CO-RE access.
967 BTFIndex = 0;
968 for (unsigned I = 0; I < Elements.size(); ++I) {
969 uint64_t ElementOffset = getBTFRecordElementOffset(Elements[I]);
970 if (ElementOffset < Offset ||
971 (ElementOffset == Offset && I < AccessIndex))
972 ++BTFIndex;
973 }
974 }
975 AccessString += ":" + std::to_string(BTFIndex);
976
977 // Earlier accesses contribute byte offsets. Only the final field supplies
978 // the property requested by preserve_field_info.
979 const uint32_t FieldKind =
981 PatchImm = GetFieldInfo(FieldKind, CTy, AccessIndex, PatchImm,
982 CInfo.RecordAlignment);
983 }
984
985 if (InfoKind == BTF::FIELD_EXISTENCE)
986 PatchImm = 1;
987
988 RootType = Root->Type;
989 RelocSuffix = formatAmaSuffix(InfoKind, PatchImm, AccessString);
990
991 return Base;
992}
993
994BPFAbstractMemberAccess::EnumAccess
995BPFAbstractMemberAccess::computeEnumAccess(const CallInst *Call,
996 const DIType *Ty) {
997 // The argument can be a global or a GEP into a global.
998 const auto *GV =
1000 assert(GV->hasInitializer());
1001 const auto *DA = cast<ConstantDataArray>(GV->getInitializer());
1002 assert(DA->isString());
1003 StringRef ValueStr = DA->getAsString();
1004 size_t Separator = ValueStr.find(':');
1005 StringRef Enumerator = ValueStr.substr(0, Separator);
1006 StringRef Value = ValueStr.substr(Separator + 1);
1007
1008 const auto *CTy = cast<DICompositeType>(stripQualifiers(Ty));
1009 assert(CTy->getTag() == dwarf::DW_TAG_enumeration_type);
1010 for (auto [Index, Element] : enumerate(CTy->getElements()))
1011 if (cast<DIEnumerator>(Element)->getName() == Enumerator)
1012 return {Index, Value};
1013 return {0, Value};
1014}
1015
1016DIType *BPFAbstractMemberAccess::computeTypeAccess(CallInst *Call,
1017 const CallInfo &CInfo,
1018 std::string &RelocSuffix) {
1019 DIType *Ty = stripQualifiers(cast<DIType>(CInfo.Metadata), false);
1020 assert(!Ty->getName().empty());
1021
1022 int64_t PatchImm = 1;
1023 size_t AccessIndex = 0;
1024 switch (CInfo.AccessIndex) {
1026 case BTF::TYPE_MATCH:
1027 break;
1028 case BTF::TYPE_SIZE:
1029 // typedef debuginfo type has size 0, get the eventual base type.
1030 PatchImm = stripQualifiers(Ty)->getSizeInBits() / 8;
1031 break;
1033 AccessIndex = computeEnumAccess(Call, Ty).Index;
1034 break;
1035 case BTF::ENUM_VALUE: {
1036 auto [Index, Value] = computeEnumAccess(Call, Ty);
1037 PatchImm = std::stoll(Value.str());
1038 AccessIndex = Index;
1039 break;
1040 }
1041 default:
1042 llvm_unreachable("Unexpected BPF type relocation kind");
1043 }
1044
1045 RelocSuffix =
1046 formatAmaSuffix(CInfo.AccessIndex, PatchImm, Twine(AccessIndex));
1047
1048 return Ty;
1049}
1050
1053 StringRef RelocSuffix) {
1054 const std::string Prefix = ("llvm." + Root->getName()).str();
1055 std::string Name = (Twine(Prefix) + RelocSuffix).str();
1056 for (unsigned N = 1; GlobalValue *Existing = M.getNamedValue(Name); ++N) {
1057 auto *GV = dyn_cast<GlobalVariable>(Existing);
1058 if (GV && GV->isDeclaration() && GV->hasExternalLinkage() &&
1059 GV->hasAttribute(BPFCoreSharedInfo::AmaAttr) &&
1060 GV->getValueType() == ValueType &&
1061 GV->getMetadata(LLVMContext::MD_preserve_access_index) == Root)
1062 return GV;
1063 // Same-named roots and different load widths need distinct globals. Keep
1064 // the discriminator before the suffix that the backend will decode.
1065 Name = (Twine(Prefix) + "." + Twine(N) + RelocSuffix).str();
1066 }
1067
1068 auto *GV = new GlobalVariable(M, ValueType, false,
1069 GlobalValue::ExternalLinkage, nullptr, Name);
1070 GV->addAttribute(BPFCoreSharedInfo::AmaAttr);
1071 GV->setMetadata(LLVMContext::MD_preserve_access_index, Root);
1072 return GV;
1073}
1074
1075/// Call/Kind is the base preserve_*_access_index() call. Attempts to do
1076/// transformation to a chain of relocable GEPs.
1077bool BPFAbstractMemberAccess::transformGEPChain(CallInst *Call,
1078 const CallInfo &CInfo) {
1079 std::string RelocSuffix;
1080 DIType *Root;
1081 Value *Base = nullptr;
1082
1083 const bool IsFieldInfo = CInfo.Kind == BPFPreserveFieldInfoAI;
1084 if (IsFieldInfo && CInfo.Metadata) {
1085 Root = computeTypeAccess(Call, CInfo, RelocSuffix);
1086 } else {
1087 Base = computeFieldAccess(Call, CInfo, RelocSuffix, Root);
1088 if (!Base)
1089 return false;
1090 }
1091
1092 BasicBlock *BB = Call->getParent();
1093 auto *ValueType = IsFieldInfo ? cast<IntegerType>(Call->getType())
1094 : Type::getInt64Ty(Call->getContext());
1095 auto *GV = getOrCreateAmaGlobal(*M, Root, ValueType, RelocSuffix);
1096 Instruction *Input = new LoadInst(ValueType, GV, "", Call->getIterator());
1097 if (!IsFieldInfo) {
1099 Base, Input);
1100 GEP->insertBefore(Call->getIterator());
1101 Input = GEP;
1102 }
1103
1104 // For the following code,
1105 // Block0:
1106 // ...
1107 // if (...) goto Block1 else ...
1108 // Block1:
1109 // %6 = load llvm.sk_buff:0:50$0:0:0:2:0
1110 // %8 = getelementptr i8, i8* %2, %6
1111 // ...
1112 // goto CommonExit
1113 // Block2:
1114 // ...
1115 // if (...) goto Block3 else ...
1116 // Block3:
1117 // %6 = load llvm.bpf_map:0:40$0:0:0:2:0
1118 // %8 = getelementptr i8, i8* %2, %6
1119 // ...
1120 // goto CommonExit
1121 // CommonExit
1122 // SimplifyCFG may generate:
1123 // Block0:
1124 // ...
1125 // if (...) goto Block_Common else ...
1126 // Block2:
1127 // ...
1128 // if (...) goto Block_Common else ...
1129 // Block_Common:
1130 // PHI = [llvm.sk_buff:0:50$0:0:0:2:0, llvm.bpf_map:0:40$0:0:0:2:0]
1131 // %6 = load PHI
1132 // %8 = getelementptr i8, i8* %2, %6
1133 // ...
1134 // goto CommonExit
1135 // For the above code, we cannot perform proper relocation since
1136 // "load PHI" has two possible relocations.
1137 //
1138 // To prevent above tail merging, we use __builtin_bpf_passthrough()
1139 // where one of its parameters is a seq_num. Since two
1140 // __builtin_bpf_passthrough() funcs will always have different seq_num,
1141 // tail merging cannot happen. The __builtin_bpf_passthrough() will be
1142 // removed in the beginning of Target IR passes.
1143 //
1144 // This approach is also used in other places when global var
1145 // representing a relocation is used.
1146 Instruction *PassThroughInst =
1148 Call->replaceAllUsesWith(PassThroughInst);
1150
1151 return true;
1152}
1153
1154bool BPFAbstractMemberAccess::doTransformation(Function &F) {
1155 bool Transformed = false;
1156
1157 // Collect PreserveDIAccessIndex Intrinsic call chains.
1158 // The call chains will be used to generate the access
1159 // patterns similar to GEP.
1160 collectAICallChains(F);
1161
1162 for (auto &C : BaseAICalls)
1163 Transformed = transformGEPChain(C.first, C.second) || Transformed;
1164
1165 return removePreserveAccessIndexIntrinsic(F) || Transformed;
1166}
1167
1170 return BPFAbstractMemberAccess(TM).run(F) ? PreservedAnalyses::none()
1172}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GlobalVariable * getOrCreateAmaGlobal(Module &M, DIType *Root, IntegerType *ValueType, StringRef RelocSuffix)
static void replaceWithGEP(CallInst *Call, uint32_t DimensionIndex, uint32_t GEPIndex)
static uint64_t getConstant(const Value *IndexValue)
static std::string formatAmaSuffix(uint32_t Kind, int64_t PatchImm, const Twine &AccessString)
static Type * getBaseElementType(const CallInst *Call)
static uint32_t calcArraySize(const DICompositeType *CTy, uint32_t StartDim)
static bool SkipDIDerivedTag(unsigned Tag, bool skipTypedef)
static DIType * stripQualifiers(DIType *Ty, bool skipTypedef=true)
static uint32_t calcElementCount(DIType *&Ty)
Return the number of innermost elements in Ty, looking through array element types such as Row in typ...
This file contains the layout of .BTF and .BTF.ext ELF sections.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
dxil translate DXIL Translate Metadata
This file contains constants used for implementing Dwarf debug support.
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static StringRef getName(Value *V)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
The Input class is used to parse a yaml document into in-memory structs and vectors.
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
Definition ArrayRef.h:200
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static void removeArrayAccessCall(CallInst *Call)
static uint32_t SeqNum
llvm.bpf.passthrough builtin seq number
Definition BPFCORE.h:75
static void removeStructAccessCall(CallInst *Call)
static void removeUnionAccessCall(CallInst *Call)
static Instruction * insertPassThrough(Module *M, BasicBlock *BB, Instruction *Input, Instruction *Before)
Insert a bpf passthrough builtin function.
static constexpr StringRef AmaAttr
The attribute attached to globals representing a field access.
Definition BPFCORE.h:62
LLVM Basic Block Representation.
Definition BasicBlock.h:61
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
This class represents a no-op cast from one type to another.
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This is an important base class in LLVM.
Definition Constant.h:44
DINodeArray getElements() const
DIType * getBaseType() const
LLVM_ABI dwarf::Tag getTag() const
Subprogram description. Uses SubclassData1.
Array subrange.
LLVM_ABI BoundType getCount() const
Base class for types.
bool isBitField() const
uint64_t getOffsetInBits() const
StringRef getName() const
uint64_t getSizeInBits() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static GetElementPtrInst * CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Create an "inbounds" getelementptr.
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
iterator_range< user_iterator > users()
Class to represent integer types.
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1087
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
StringRef getName() const
Definition Record.h:1760
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:482
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
std::pair< StringRef, StringRef > rsplit(StringRef Separator) const
Split into two substrings around the last occurrence of a separator string.
Definition StringRef.h:761
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition Triple.h:518
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
InfoKind
Entry kind values for the .amdgpu.info section.
PatchableRelocKind
CO-RE relocation kind codes used in .BTF.ext section.
Definition BTF.h:280
@ FIELD_RSHIFT_U64
Definition BTF.h:286
@ ENUM_VALUE
Definition BTF.h:292
@ FIELD_SIGNEDNESS
Definition BTF.h:284
@ FIELD_BYTE_OFFSET
Definition BTF.h:281
@ FIELD_BYTE_SIZE
Definition BTF.h:282
@ ENUM_VALUE_EXISTENCE
Definition BTF.h:291
@ MAX_FIELD_RELOC_KIND
Definition BTF.h:294
@ TYPE_EXISTENCE
Definition BTF.h:289
@ FIELD_LSHIFT_U64
Definition BTF.h:285
@ TYPE_MATCH
Definition BTF.h:293
@ TYPE_SIZE
Definition BTF.h:290
@ FIELD_EXISTENCE
Definition BTF.h:283
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr MCPhysReg SP
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
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:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
uint64_t getBTFRecordElementOffset(const DINode *Element)
Return the bit offset used to order an element of a BTF structure record.
Definition BPFCORE.h:26
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
BTF::PatchableRelocKind Kind
Definition BPFCORE.h:67
static AmaRelocation decode(StringRef Name)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111