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/IR/DebugInfoMetadata.h"
81 #include "llvm/IR/GlobalVariable.h"
82 #include "llvm/IR/Instruction.h"
83 #include "llvm/IR/Instructions.h"
84 #include "llvm/IR/IntrinsicsBPF.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/PassManager.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/IR/User.h"
89 #include "llvm/IR/Value.h"
90 #include "llvm/Pass.h"
91 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
92 #include <stack>
93 
94 #define DEBUG_TYPE "bpf-abstract-member-access"
95 
96 namespace llvm {
97 constexpr StringRef BPFCoreSharedInfo::AmaAttr;
98 uint32_t BPFCoreSharedInfo::SeqNum;
99 
100 Instruction *BPFCoreSharedInfo::insertPassThrough(Module *M, BasicBlock *BB,
101                                                   Instruction *Input,
102                                                   Instruction *Before) {
103   Function *Fn = Intrinsic::getDeclaration(
104       M, Intrinsic::bpf_passthrough, {Input->getType(), Input->getType()});
105   Constant *SeqNumVal = ConstantInt::get(Type::getInt32Ty(BB->getContext()),
106                                          BPFCoreSharedInfo::SeqNum++);
107 
108   auto *NewInst = CallInst::Create(Fn, {SeqNumVal, Input});
109   BB->getInstList().insert(Before->getIterator(), NewInst);
110   return NewInst;
111 }
112 } // namespace llvm
113 
114 using namespace llvm;
115 
116 namespace {
117 class BPFAbstractMemberAccess final {
118 public:
119   BPFAbstractMemberAccess(BPFTargetMachine *TM) : TM(TM) {}
120 
121   bool run(Function &F);
122 
123   struct CallInfo {
124     uint32_t Kind;
125     uint32_t AccessIndex;
126     Align RecordAlignment;
127     MDNode *Metadata;
128     Value *Base;
129   };
130   typedef std::stack<std::pair<CallInst *, CallInfo>> CallInfoStack;
131 
132 private:
133   enum : uint32_t {
134     BPFPreserveArrayAI = 1,
135     BPFPreserveUnionAI = 2,
136     BPFPreserveStructAI = 3,
137     BPFPreserveFieldInfoAI = 4,
138   };
139 
140   TargetMachine *TM;
141   const DataLayout *DL = nullptr;
142   Module *M = nullptr;
143 
144   std::map<std::string, GlobalVariable *> GEPGlobals;
145   // A map to link preserve_*_access_index instrinsic calls.
146   std::map<CallInst *, std::pair<CallInst *, CallInfo>> AIChain;
147   // A map to hold all the base preserve_*_access_index instrinsic calls.
148   // The base call is not an input of any other preserve_*
149   // intrinsics.
150   std::map<CallInst *, CallInfo> BaseAICalls;
151 
152   bool doTransformation(Function &F);
153 
154   void traceAICall(CallInst *Call, CallInfo &ParentInfo);
155   void traceBitCast(BitCastInst *BitCast, CallInst *Parent,
156                     CallInfo &ParentInfo);
157   void traceGEP(GetElementPtrInst *GEP, CallInst *Parent,
158                 CallInfo &ParentInfo);
159   void collectAICallChains(Function &F);
160 
161   bool IsPreserveDIAccessIndexCall(const CallInst *Call, CallInfo &Cinfo);
162   bool IsValidAIChain(const MDNode *ParentMeta, uint32_t ParentAI,
163                       const MDNode *ChildMeta);
164   bool removePreserveAccessIndexIntrinsic(Function &F);
165   void replaceWithGEP(std::vector<CallInst *> &CallList,
166                       uint32_t NumOfZerosIndex, uint32_t DIIndex);
167   bool HasPreserveFieldInfoCall(CallInfoStack &CallStack);
168   void GetStorageBitRange(DIDerivedType *MemberTy, Align RecordAlignment,
169                           uint32_t &StartBitOffset, uint32_t &EndBitOffset);
170   uint32_t GetFieldInfo(uint32_t InfoKind, DICompositeType *CTy,
171                         uint32_t AccessIndex, uint32_t PatchImm,
172                         Align RecordAlignment);
173 
174   Value *computeBaseAndAccessKey(CallInst *Call, CallInfo &CInfo,
175                                  std::string &AccessKey, MDNode *&BaseMeta);
176   MDNode *computeAccessKey(CallInst *Call, CallInfo &CInfo,
177                            std::string &AccessKey, bool &IsInt32Ret);
178   uint64_t getConstant(const Value *IndexValue);
179   bool transformGEPChain(CallInst *Call, CallInfo &CInfo);
180 };
181 
182 class BPFAbstractMemberAccessLegacyPass final : public FunctionPass {
183   BPFTargetMachine *TM;
184 
185   bool runOnFunction(Function &F) override {
186     return BPFAbstractMemberAccess(TM).run(F);
187   }
188 
189 public:
190   static char ID;
191 
192   // Add optional BPFTargetMachine parameter so that BPF backend can add the
193   // phase with target machine to find out the endianness. The default
194   // constructor (without parameters) is used by the pass manager for managing
195   // purposes.
196   BPFAbstractMemberAccessLegacyPass(BPFTargetMachine *TM = nullptr)
197       : FunctionPass(ID), TM(TM) {}
198 };
199 
200 } // End anonymous namespace
201 
202 char BPFAbstractMemberAccessLegacyPass::ID = 0;
203 INITIALIZE_PASS(BPFAbstractMemberAccessLegacyPass, DEBUG_TYPE,
204                 "BPF Abstract Member Access", false, false)
205 
206 FunctionPass *llvm::createBPFAbstractMemberAccess(BPFTargetMachine *TM) {
207   return new BPFAbstractMemberAccessLegacyPass(TM);
208 }
209 
210 bool BPFAbstractMemberAccess::run(Function &F) {
211   LLVM_DEBUG(dbgs() << "********** Abstract Member Accesses **********\n");
212 
213   M = F.getParent();
214   if (!M)
215     return false;
216 
217   // Bail out if no debug info.
218   if (M->debug_compile_units().empty())
219     return false;
220 
221   DL = &M->getDataLayout();
222   return doTransformation(F);
223 }
224 
225 static bool SkipDIDerivedTag(unsigned Tag, bool skipTypedef) {
226   if (Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type &&
227       Tag != dwarf::DW_TAG_volatile_type &&
228       Tag != dwarf::DW_TAG_restrict_type &&
229       Tag != dwarf::DW_TAG_member)
230     return false;
231   if (Tag == dwarf::DW_TAG_typedef && !skipTypedef)
232     return false;
233   return true;
234 }
235 
236 static DIType * stripQualifiers(DIType *Ty, bool skipTypedef = true) {
237   while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
238     if (!SkipDIDerivedTag(DTy->getTag(), skipTypedef))
239       break;
240     Ty = DTy->getBaseType();
241   }
242   return Ty;
243 }
244 
245 static const DIType * stripQualifiers(const DIType *Ty) {
246   while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
247     if (!SkipDIDerivedTag(DTy->getTag(), true))
248       break;
249     Ty = DTy->getBaseType();
250   }
251   return Ty;
252 }
253 
254 static uint32_t calcArraySize(const DICompositeType *CTy, uint32_t StartDim) {
255   DINodeArray Elements = CTy->getElements();
256   uint32_t DimSize = 1;
257   for (uint32_t I = StartDim; I < Elements.size(); ++I) {
258     if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
259       if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
260         const DISubrange *SR = cast<DISubrange>(Element);
261         auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
262         DimSize *= CI->getSExtValue();
263       }
264   }
265 
266   return DimSize;
267 }
268 
269 /// Check whether a call is a preserve_*_access_index intrinsic call or not.
270 bool BPFAbstractMemberAccess::IsPreserveDIAccessIndexCall(const CallInst *Call,
271                                                           CallInfo &CInfo) {
272   if (!Call)
273     return false;
274 
275   const auto *GV = dyn_cast<GlobalValue>(Call->getCalledOperand());
276   if (!GV)
277     return false;
278   if (GV->getName().startswith("llvm.preserve.array.access.index")) {
279     CInfo.Kind = BPFPreserveArrayAI;
280     CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
281     if (!CInfo.Metadata)
282       report_fatal_error("Missing metadata for llvm.preserve.array.access.index intrinsic");
283     CInfo.AccessIndex = getConstant(Call->getArgOperand(2));
284     CInfo.Base = Call->getArgOperand(0);
285     CInfo.RecordAlignment =
286         DL->getABITypeAlign(CInfo.Base->getType()->getPointerElementType());
287     return true;
288   }
289   if (GV->getName().startswith("llvm.preserve.union.access.index")) {
290     CInfo.Kind = BPFPreserveUnionAI;
291     CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
292     if (!CInfo.Metadata)
293       report_fatal_error("Missing metadata for llvm.preserve.union.access.index intrinsic");
294     CInfo.AccessIndex = getConstant(Call->getArgOperand(1));
295     CInfo.Base = Call->getArgOperand(0);
296     CInfo.RecordAlignment =
297         DL->getABITypeAlign(CInfo.Base->getType()->getPointerElementType());
298     return true;
299   }
300   if (GV->getName().startswith("llvm.preserve.struct.access.index")) {
301     CInfo.Kind = BPFPreserveStructAI;
302     CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
303     if (!CInfo.Metadata)
304       report_fatal_error("Missing metadata for llvm.preserve.struct.access.index intrinsic");
305     CInfo.AccessIndex = getConstant(Call->getArgOperand(2));
306     CInfo.Base = Call->getArgOperand(0);
307     CInfo.RecordAlignment =
308         DL->getABITypeAlign(CInfo.Base->getType()->getPointerElementType());
309     return true;
310   }
311   if (GV->getName().startswith("llvm.bpf.preserve.field.info")) {
312     CInfo.Kind = BPFPreserveFieldInfoAI;
313     CInfo.Metadata = nullptr;
314     // Check validity of info_kind as clang did not check this.
315     uint64_t InfoKind = getConstant(Call->getArgOperand(1));
316     if (InfoKind >= BPFCoreSharedInfo::MAX_FIELD_RELOC_KIND)
317       report_fatal_error("Incorrect info_kind for llvm.bpf.preserve.field.info intrinsic");
318     CInfo.AccessIndex = InfoKind;
319     return true;
320   }
321   if (GV->getName().startswith("llvm.bpf.preserve.type.info")) {
322     CInfo.Kind = BPFPreserveFieldInfoAI;
323     CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
324     if (!CInfo.Metadata)
325       report_fatal_error("Missing metadata for llvm.preserve.type.info intrinsic");
326     uint64_t Flag = getConstant(Call->getArgOperand(1));
327     if (Flag >= BPFCoreSharedInfo::MAX_PRESERVE_TYPE_INFO_FLAG)
328       report_fatal_error("Incorrect flag for llvm.bpf.preserve.type.info intrinsic");
329     if (Flag == BPFCoreSharedInfo::PRESERVE_TYPE_INFO_EXISTENCE)
330       CInfo.AccessIndex = BPFCoreSharedInfo::TYPE_EXISTENCE;
331     else
332       CInfo.AccessIndex = BPFCoreSharedInfo::TYPE_SIZE;
333     return true;
334   }
335   if (GV->getName().startswith("llvm.bpf.preserve.enum.value")) {
336     CInfo.Kind = BPFPreserveFieldInfoAI;
337     CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
338     if (!CInfo.Metadata)
339       report_fatal_error("Missing metadata for llvm.preserve.enum.value intrinsic");
340     uint64_t Flag = getConstant(Call->getArgOperand(2));
341     if (Flag >= BPFCoreSharedInfo::MAX_PRESERVE_ENUM_VALUE_FLAG)
342       report_fatal_error("Incorrect flag for llvm.bpf.preserve.enum.value intrinsic");
343     if (Flag == BPFCoreSharedInfo::PRESERVE_ENUM_VALUE_EXISTENCE)
344       CInfo.AccessIndex = BPFCoreSharedInfo::ENUM_VALUE_EXISTENCE;
345     else
346       CInfo.AccessIndex = BPFCoreSharedInfo::ENUM_VALUE;
347     return true;
348   }
349 
350   return false;
351 }
352 
353 void BPFAbstractMemberAccess::replaceWithGEP(std::vector<CallInst *> &CallList,
354                                              uint32_t DimensionIndex,
355                                              uint32_t GEPIndex) {
356   for (auto Call : CallList) {
357     uint32_t Dimension = 1;
358     if (DimensionIndex > 0)
359       Dimension = getConstant(Call->getArgOperand(DimensionIndex));
360 
361     Constant *Zero =
362         ConstantInt::get(Type::getInt32Ty(Call->getParent()->getContext()), 0);
363     SmallVector<Value *, 4> IdxList;
364     for (unsigned I = 0; I < Dimension; ++I)
365       IdxList.push_back(Zero);
366     IdxList.push_back(Call->getArgOperand(GEPIndex));
367 
368     auto *GEP = GetElementPtrInst::CreateInBounds(Call->getArgOperand(0),
369                                                   IdxList, "", Call);
370     Call->replaceAllUsesWith(GEP);
371     Call->eraseFromParent();
372   }
373 }
374 
375 bool BPFAbstractMemberAccess::removePreserveAccessIndexIntrinsic(Function &F) {
376   std::vector<CallInst *> PreserveArrayIndexCalls;
377   std::vector<CallInst *> PreserveUnionIndexCalls;
378   std::vector<CallInst *> PreserveStructIndexCalls;
379   bool Found = false;
380 
381   for (auto &BB : F)
382     for (auto &I : BB) {
383       auto *Call = dyn_cast<CallInst>(&I);
384       CallInfo CInfo;
385       if (!IsPreserveDIAccessIndexCall(Call, CInfo))
386         continue;
387 
388       Found = true;
389       if (CInfo.Kind == BPFPreserveArrayAI)
390         PreserveArrayIndexCalls.push_back(Call);
391       else if (CInfo.Kind == BPFPreserveUnionAI)
392         PreserveUnionIndexCalls.push_back(Call);
393       else
394         PreserveStructIndexCalls.push_back(Call);
395     }
396 
397   // do the following transformation:
398   // . addr = preserve_array_access_index(base, dimension, index)
399   //   is transformed to
400   //     addr = GEP(base, dimenion's zero's, index)
401   // . addr = preserve_union_access_index(base, di_index)
402   //   is transformed to
403   //     addr = base, i.e., all usages of "addr" are replaced by "base".
404   // . addr = preserve_struct_access_index(base, gep_index, di_index)
405   //   is transformed to
406   //     addr = GEP(base, 0, gep_index)
407   replaceWithGEP(PreserveArrayIndexCalls, 1, 2);
408   replaceWithGEP(PreserveStructIndexCalls, 0, 1);
409   for (auto Call : PreserveUnionIndexCalls) {
410     Call->replaceAllUsesWith(Call->getArgOperand(0));
411     Call->eraseFromParent();
412   }
413 
414   return Found;
415 }
416 
417 /// Check whether the access index chain is valid. We check
418 /// here because there may be type casts between two
419 /// access indexes. We want to ensure memory access still valid.
420 bool BPFAbstractMemberAccess::IsValidAIChain(const MDNode *ParentType,
421                                              uint32_t ParentAI,
422                                              const MDNode *ChildType) {
423   if (!ChildType)
424     return true; // preserve_field_info, no type comparison needed.
425 
426   const DIType *PType = stripQualifiers(cast<DIType>(ParentType));
427   const DIType *CType = stripQualifiers(cast<DIType>(ChildType));
428 
429   // Child is a derived/pointer type, which is due to type casting.
430   // Pointer type cannot be in the middle of chain.
431   if (isa<DIDerivedType>(CType))
432     return false;
433 
434   // Parent is a pointer type.
435   if (const auto *PtrTy = dyn_cast<DIDerivedType>(PType)) {
436     if (PtrTy->getTag() != dwarf::DW_TAG_pointer_type)
437       return false;
438     return stripQualifiers(PtrTy->getBaseType()) == CType;
439   }
440 
441   // Otherwise, struct/union/array types
442   const auto *PTy = dyn_cast<DICompositeType>(PType);
443   const auto *CTy = dyn_cast<DICompositeType>(CType);
444   assert(PTy && CTy && "ParentType or ChildType is null or not composite");
445 
446   uint32_t PTyTag = PTy->getTag();
447   assert(PTyTag == dwarf::DW_TAG_array_type ||
448          PTyTag == dwarf::DW_TAG_structure_type ||
449          PTyTag == dwarf::DW_TAG_union_type);
450 
451   uint32_t CTyTag = CTy->getTag();
452   assert(CTyTag == dwarf::DW_TAG_array_type ||
453          CTyTag == dwarf::DW_TAG_structure_type ||
454          CTyTag == dwarf::DW_TAG_union_type);
455 
456   // Multi dimensional arrays, base element should be the same
457   if (PTyTag == dwarf::DW_TAG_array_type && PTyTag == CTyTag)
458     return PTy->getBaseType() == CTy->getBaseType();
459 
460   DIType *Ty;
461   if (PTyTag == dwarf::DW_TAG_array_type)
462     Ty = PTy->getBaseType();
463   else
464     Ty = dyn_cast<DIType>(PTy->getElements()[ParentAI]);
465 
466   return dyn_cast<DICompositeType>(stripQualifiers(Ty)) == CTy;
467 }
468 
469 void BPFAbstractMemberAccess::traceAICall(CallInst *Call,
470                                           CallInfo &ParentInfo) {
471   for (User *U : Call->users()) {
472     Instruction *Inst = dyn_cast<Instruction>(U);
473     if (!Inst)
474       continue;
475 
476     if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
477       traceBitCast(BI, Call, ParentInfo);
478     } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
479       CallInfo ChildInfo;
480 
481       if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
482           IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
483                          ChildInfo.Metadata)) {
484         AIChain[CI] = std::make_pair(Call, ParentInfo);
485         traceAICall(CI, ChildInfo);
486       } else {
487         BaseAICalls[Call] = ParentInfo;
488       }
489     } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
490       if (GI->hasAllZeroIndices())
491         traceGEP(GI, Call, ParentInfo);
492       else
493         BaseAICalls[Call] = ParentInfo;
494     } else {
495       BaseAICalls[Call] = ParentInfo;
496     }
497   }
498 }
499 
500 void BPFAbstractMemberAccess::traceBitCast(BitCastInst *BitCast,
501                                            CallInst *Parent,
502                                            CallInfo &ParentInfo) {
503   for (User *U : BitCast->users()) {
504     Instruction *Inst = dyn_cast<Instruction>(U);
505     if (!Inst)
506       continue;
507 
508     if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
509       traceBitCast(BI, Parent, ParentInfo);
510     } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
511       CallInfo ChildInfo;
512       if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
513           IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
514                          ChildInfo.Metadata)) {
515         AIChain[CI] = std::make_pair(Parent, ParentInfo);
516         traceAICall(CI, ChildInfo);
517       } else {
518         BaseAICalls[Parent] = ParentInfo;
519       }
520     } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
521       if (GI->hasAllZeroIndices())
522         traceGEP(GI, Parent, ParentInfo);
523       else
524         BaseAICalls[Parent] = ParentInfo;
525     } else {
526       BaseAICalls[Parent] = ParentInfo;
527     }
528   }
529 }
530 
531 void BPFAbstractMemberAccess::traceGEP(GetElementPtrInst *GEP, CallInst *Parent,
532                                        CallInfo &ParentInfo) {
533   for (User *U : GEP->users()) {
534     Instruction *Inst = dyn_cast<Instruction>(U);
535     if (!Inst)
536       continue;
537 
538     if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
539       traceBitCast(BI, Parent, ParentInfo);
540     } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
541       CallInfo ChildInfo;
542       if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
543           IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
544                          ChildInfo.Metadata)) {
545         AIChain[CI] = std::make_pair(Parent, ParentInfo);
546         traceAICall(CI, ChildInfo);
547       } else {
548         BaseAICalls[Parent] = ParentInfo;
549       }
550     } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
551       if (GI->hasAllZeroIndices())
552         traceGEP(GI, Parent, ParentInfo);
553       else
554         BaseAICalls[Parent] = ParentInfo;
555     } else {
556       BaseAICalls[Parent] = ParentInfo;
557     }
558   }
559 }
560 
561 void BPFAbstractMemberAccess::collectAICallChains(Function &F) {
562   AIChain.clear();
563   BaseAICalls.clear();
564 
565   for (auto &BB : F)
566     for (auto &I : BB) {
567       CallInfo CInfo;
568       auto *Call = dyn_cast<CallInst>(&I);
569       if (!IsPreserveDIAccessIndexCall(Call, CInfo) ||
570           AIChain.find(Call) != AIChain.end())
571         continue;
572 
573       traceAICall(Call, CInfo);
574     }
575 }
576 
577 uint64_t BPFAbstractMemberAccess::getConstant(const Value *IndexValue) {
578   const ConstantInt *CV = dyn_cast<ConstantInt>(IndexValue);
579   assert(CV);
580   return CV->getValue().getZExtValue();
581 }
582 
583 /// Get the start and the end of storage offset for \p MemberTy.
584 void BPFAbstractMemberAccess::GetStorageBitRange(DIDerivedType *MemberTy,
585                                                  Align RecordAlignment,
586                                                  uint32_t &StartBitOffset,
587                                                  uint32_t &EndBitOffset) {
588   uint32_t MemberBitSize = MemberTy->getSizeInBits();
589   uint32_t MemberBitOffset = MemberTy->getOffsetInBits();
590   uint32_t AlignBits = RecordAlignment.value() * 8;
591   if (RecordAlignment > 8 || MemberBitSize > AlignBits)
592     report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info, "
593                        "requiring too big alignment");
594 
595   StartBitOffset = MemberBitOffset & ~(AlignBits - 1);
596   if ((StartBitOffset + AlignBits) < (MemberBitOffset + MemberBitSize))
597     report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info, "
598                        "cross alignment boundary");
599   EndBitOffset = StartBitOffset + AlignBits;
600 }
601 
602 uint32_t BPFAbstractMemberAccess::GetFieldInfo(uint32_t InfoKind,
603                                                DICompositeType *CTy,
604                                                uint32_t AccessIndex,
605                                                uint32_t PatchImm,
606                                                Align RecordAlignment) {
607   if (InfoKind == BPFCoreSharedInfo::FIELD_EXISTENCE)
608       return 1;
609 
610   uint32_t Tag = CTy->getTag();
611   if (InfoKind == BPFCoreSharedInfo::FIELD_BYTE_OFFSET) {
612     if (Tag == dwarf::DW_TAG_array_type) {
613       auto *EltTy = stripQualifiers(CTy->getBaseType());
614       PatchImm += AccessIndex * calcArraySize(CTy, 1) *
615                   (EltTy->getSizeInBits() >> 3);
616     } else if (Tag == dwarf::DW_TAG_structure_type) {
617       auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
618       if (!MemberTy->isBitField()) {
619         PatchImm += MemberTy->getOffsetInBits() >> 3;
620       } else {
621         unsigned SBitOffset, NextSBitOffset;
622         GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset,
623                            NextSBitOffset);
624         PatchImm += SBitOffset >> 3;
625       }
626     }
627     return PatchImm;
628   }
629 
630   if (InfoKind == BPFCoreSharedInfo::FIELD_BYTE_SIZE) {
631     if (Tag == dwarf::DW_TAG_array_type) {
632       auto *EltTy = stripQualifiers(CTy->getBaseType());
633       return calcArraySize(CTy, 1) * (EltTy->getSizeInBits() >> 3);
634     } else {
635       auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
636       uint32_t SizeInBits = MemberTy->getSizeInBits();
637       if (!MemberTy->isBitField())
638         return SizeInBits >> 3;
639 
640       unsigned SBitOffset, NextSBitOffset;
641       GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
642       SizeInBits = NextSBitOffset - SBitOffset;
643       if (SizeInBits & (SizeInBits - 1))
644         report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info");
645       return SizeInBits >> 3;
646     }
647   }
648 
649   if (InfoKind == BPFCoreSharedInfo::FIELD_SIGNEDNESS) {
650     const DIType *BaseTy;
651     if (Tag == dwarf::DW_TAG_array_type) {
652       // Signedness only checked when final array elements are accessed.
653       if (CTy->getElements().size() != 1)
654         report_fatal_error("Invalid array expression for llvm.bpf.preserve.field.info");
655       BaseTy = stripQualifiers(CTy->getBaseType());
656     } else {
657       auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
658       BaseTy = stripQualifiers(MemberTy->getBaseType());
659     }
660 
661     // Only basic types and enum types have signedness.
662     const auto *BTy = dyn_cast<DIBasicType>(BaseTy);
663     while (!BTy) {
664       const auto *CompTy = dyn_cast<DICompositeType>(BaseTy);
665       // Report an error if the field expression does not have signedness.
666       if (!CompTy || CompTy->getTag() != dwarf::DW_TAG_enumeration_type)
667         report_fatal_error("Invalid field expression for llvm.bpf.preserve.field.info");
668       BaseTy = stripQualifiers(CompTy->getBaseType());
669       BTy = dyn_cast<DIBasicType>(BaseTy);
670     }
671     uint32_t Encoding = BTy->getEncoding();
672     return (Encoding == dwarf::DW_ATE_signed || Encoding == dwarf::DW_ATE_signed_char);
673   }
674 
675   if (InfoKind == BPFCoreSharedInfo::FIELD_LSHIFT_U64) {
676     // The value is loaded into a value with FIELD_BYTE_SIZE size,
677     // and then zero or sign extended to U64.
678     // FIELD_LSHIFT_U64 and FIELD_RSHIFT_U64 are operations
679     // to extract the original value.
680     const Triple &Triple = TM->getTargetTriple();
681     DIDerivedType *MemberTy = nullptr;
682     bool IsBitField = false;
683     uint32_t SizeInBits;
684 
685     if (Tag == dwarf::DW_TAG_array_type) {
686       auto *EltTy = stripQualifiers(CTy->getBaseType());
687       SizeInBits = calcArraySize(CTy, 1) * EltTy->getSizeInBits();
688     } else {
689       MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
690       SizeInBits = MemberTy->getSizeInBits();
691       IsBitField = MemberTy->isBitField();
692     }
693 
694     if (!IsBitField) {
695       if (SizeInBits > 64)
696         report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
697       return 64 - SizeInBits;
698     }
699 
700     unsigned SBitOffset, NextSBitOffset;
701     GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
702     if (NextSBitOffset - SBitOffset > 64)
703       report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
704 
705     unsigned OffsetInBits = MemberTy->getOffsetInBits();
706     if (Triple.getArch() == Triple::bpfel)
707       return SBitOffset + 64 - OffsetInBits - SizeInBits;
708     else
709       return OffsetInBits + 64 - NextSBitOffset;
710   }
711 
712   if (InfoKind == BPFCoreSharedInfo::FIELD_RSHIFT_U64) {
713     DIDerivedType *MemberTy = nullptr;
714     bool IsBitField = false;
715     uint32_t SizeInBits;
716     if (Tag == dwarf::DW_TAG_array_type) {
717       auto *EltTy = stripQualifiers(CTy->getBaseType());
718       SizeInBits = calcArraySize(CTy, 1) * EltTy->getSizeInBits();
719     } else {
720       MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
721       SizeInBits = MemberTy->getSizeInBits();
722       IsBitField = MemberTy->isBitField();
723     }
724 
725     if (!IsBitField) {
726       if (SizeInBits > 64)
727         report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
728       return 64 - SizeInBits;
729     }
730 
731     unsigned SBitOffset, NextSBitOffset;
732     GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
733     if (NextSBitOffset - SBitOffset > 64)
734       report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
735 
736     return 64 - SizeInBits;
737   }
738 
739   llvm_unreachable("Unknown llvm.bpf.preserve.field.info info kind");
740 }
741 
742 bool BPFAbstractMemberAccess::HasPreserveFieldInfoCall(CallInfoStack &CallStack) {
743   // This is called in error return path, no need to maintain CallStack.
744   while (CallStack.size()) {
745     auto StackElem = CallStack.top();
746     if (StackElem.second.Kind == BPFPreserveFieldInfoAI)
747       return true;
748     CallStack.pop();
749   }
750   return false;
751 }
752 
753 /// Compute the base of the whole preserve_* intrinsics chains, i.e., the base
754 /// pointer of the first preserve_*_access_index call, and construct the access
755 /// string, which will be the name of a global variable.
756 Value *BPFAbstractMemberAccess::computeBaseAndAccessKey(CallInst *Call,
757                                                         CallInfo &CInfo,
758                                                         std::string &AccessKey,
759                                                         MDNode *&TypeMeta) {
760   Value *Base = nullptr;
761   std::string TypeName;
762   CallInfoStack CallStack;
763 
764   // Put the access chain into a stack with the top as the head of the chain.
765   while (Call) {
766     CallStack.push(std::make_pair(Call, CInfo));
767     CInfo = AIChain[Call].second;
768     Call = AIChain[Call].first;
769   }
770 
771   // The access offset from the base of the head of chain is also
772   // calculated here as all debuginfo types are available.
773 
774   // Get type name and calculate the first index.
775   // We only want to get type name from typedef, structure or union.
776   // If user wants a relocation like
777   //    int *p; ... __builtin_preserve_access_index(&p[4]) ...
778   // or
779   //    int a[10][20]; ... __builtin_preserve_access_index(&a[2][3]) ...
780   // we will skip them.
781   uint32_t FirstIndex = 0;
782   uint32_t PatchImm = 0; // AccessOffset or the requested field info
783   uint32_t InfoKind = BPFCoreSharedInfo::FIELD_BYTE_OFFSET;
784   while (CallStack.size()) {
785     auto StackElem = CallStack.top();
786     Call = StackElem.first;
787     CInfo = StackElem.second;
788 
789     if (!Base)
790       Base = CInfo.Base;
791 
792     DIType *PossibleTypeDef = stripQualifiers(cast<DIType>(CInfo.Metadata),
793                                               false);
794     DIType *Ty = stripQualifiers(PossibleTypeDef);
795     if (CInfo.Kind == BPFPreserveUnionAI ||
796         CInfo.Kind == BPFPreserveStructAI) {
797       // struct or union type. If the typedef is in the metadata, always
798       // use the typedef.
799       TypeName = std::string(PossibleTypeDef->getName());
800       TypeMeta = PossibleTypeDef;
801       PatchImm += FirstIndex * (Ty->getSizeInBits() >> 3);
802       break;
803     }
804 
805     assert(CInfo.Kind == BPFPreserveArrayAI);
806 
807     // Array entries will always be consumed for accumulative initial index.
808     CallStack.pop();
809 
810     // BPFPreserveArrayAI
811     uint64_t AccessIndex = CInfo.AccessIndex;
812 
813     DIType *BaseTy = nullptr;
814     bool CheckElemType = false;
815     if (const auto *CTy = dyn_cast<DICompositeType>(Ty)) {
816       // array type
817       assert(CTy->getTag() == dwarf::DW_TAG_array_type);
818 
819 
820       FirstIndex += AccessIndex * calcArraySize(CTy, 1);
821       BaseTy = stripQualifiers(CTy->getBaseType());
822       CheckElemType = CTy->getElements().size() == 1;
823     } else {
824       // pointer type
825       auto *DTy = cast<DIDerivedType>(Ty);
826       assert(DTy->getTag() == dwarf::DW_TAG_pointer_type);
827 
828       BaseTy = stripQualifiers(DTy->getBaseType());
829       CTy = dyn_cast<DICompositeType>(BaseTy);
830       if (!CTy) {
831         CheckElemType = true;
832       } else if (CTy->getTag() != dwarf::DW_TAG_array_type) {
833         FirstIndex += AccessIndex;
834         CheckElemType = true;
835       } else {
836         FirstIndex += AccessIndex * calcArraySize(CTy, 0);
837       }
838     }
839 
840     if (CheckElemType) {
841       auto *CTy = dyn_cast<DICompositeType>(BaseTy);
842       if (!CTy) {
843         if (HasPreserveFieldInfoCall(CallStack))
844           report_fatal_error("Invalid field access for llvm.preserve.field.info intrinsic");
845         return nullptr;
846       }
847 
848       unsigned CTag = CTy->getTag();
849       if (CTag == dwarf::DW_TAG_structure_type || CTag == dwarf::DW_TAG_union_type) {
850         TypeName = std::string(CTy->getName());
851       } else {
852         if (HasPreserveFieldInfoCall(CallStack))
853           report_fatal_error("Invalid field access for llvm.preserve.field.info intrinsic");
854         return nullptr;
855       }
856       TypeMeta = CTy;
857       PatchImm += FirstIndex * (CTy->getSizeInBits() >> 3);
858       break;
859     }
860   }
861   assert(TypeName.size());
862   AccessKey += std::to_string(FirstIndex);
863 
864   // Traverse the rest of access chain to complete offset calculation
865   // and access key construction.
866   while (CallStack.size()) {
867     auto StackElem = CallStack.top();
868     CInfo = StackElem.second;
869     CallStack.pop();
870 
871     if (CInfo.Kind == BPFPreserveFieldInfoAI) {
872       InfoKind = CInfo.AccessIndex;
873       break;
874     }
875 
876     // If the next Call (the top of the stack) is a BPFPreserveFieldInfoAI,
877     // the action will be extracting field info.
878     if (CallStack.size()) {
879       auto StackElem2 = CallStack.top();
880       CallInfo CInfo2 = StackElem2.second;
881       if (CInfo2.Kind == BPFPreserveFieldInfoAI) {
882         InfoKind = CInfo2.AccessIndex;
883         assert(CallStack.size() == 1);
884       }
885     }
886 
887     // Access Index
888     uint64_t AccessIndex = CInfo.AccessIndex;
889     AccessKey += ":" + std::to_string(AccessIndex);
890 
891     MDNode *MDN = CInfo.Metadata;
892     // At this stage, it cannot be pointer type.
893     auto *CTy = cast<DICompositeType>(stripQualifiers(cast<DIType>(MDN)));
894     PatchImm = GetFieldInfo(InfoKind, CTy, AccessIndex, PatchImm,
895                             CInfo.RecordAlignment);
896   }
897 
898   // Access key is the
899   //   "llvm." + type name + ":" + reloc type + ":" + patched imm + "$" +
900   //   access string,
901   // uniquely identifying one relocation.
902   // The prefix "llvm." indicates this is a temporary global, which should
903   // not be emitted to ELF file.
904   AccessKey = "llvm." + TypeName + ":" + std::to_string(InfoKind) + ":" +
905               std::to_string(PatchImm) + "$" + AccessKey;
906 
907   return Base;
908 }
909 
910 MDNode *BPFAbstractMemberAccess::computeAccessKey(CallInst *Call,
911                                                   CallInfo &CInfo,
912                                                   std::string &AccessKey,
913                                                   bool &IsInt32Ret) {
914   DIType *Ty = stripQualifiers(cast<DIType>(CInfo.Metadata), false);
915   assert(!Ty->getName().empty());
916 
917   int64_t PatchImm;
918   std::string AccessStr("0");
919   if (CInfo.AccessIndex == BPFCoreSharedInfo::TYPE_EXISTENCE) {
920     PatchImm = 1;
921   } else if (CInfo.AccessIndex == BPFCoreSharedInfo::TYPE_SIZE) {
922     // typedef debuginfo type has size 0, get the eventual base type.
923     DIType *BaseTy = stripQualifiers(Ty, true);
924     PatchImm = BaseTy->getSizeInBits() / 8;
925   } else {
926     // ENUM_VALUE_EXISTENCE and ENUM_VALUE
927     IsInt32Ret = false;
928 
929     const auto *CE = cast<ConstantExpr>(Call->getArgOperand(1));
930     const GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
931     assert(GV->hasInitializer());
932     const ConstantDataArray *DA = cast<ConstantDataArray>(GV->getInitializer());
933     assert(DA->isString());
934     StringRef ValueStr = DA->getAsString();
935 
936     // ValueStr format: <EnumeratorStr>:<Value>
937     size_t Separator = ValueStr.find_first_of(':');
938     StringRef EnumeratorStr = ValueStr.substr(0, Separator);
939 
940     // Find enumerator index in the debuginfo
941     DIType *BaseTy = stripQualifiers(Ty, true);
942     const auto *CTy = cast<DICompositeType>(BaseTy);
943     assert(CTy->getTag() == dwarf::DW_TAG_enumeration_type);
944     int EnumIndex = 0;
945     for (const auto Element : CTy->getElements()) {
946       const auto *Enum = cast<DIEnumerator>(Element);
947       if (Enum->getName() == EnumeratorStr) {
948         AccessStr = std::to_string(EnumIndex);
949         break;
950       }
951       EnumIndex++;
952     }
953 
954     if (CInfo.AccessIndex == BPFCoreSharedInfo::ENUM_VALUE) {
955       StringRef EValueStr = ValueStr.substr(Separator + 1);
956       PatchImm = std::stoll(std::string(EValueStr));
957     } else {
958       PatchImm = 1;
959     }
960   }
961 
962   AccessKey = "llvm." + Ty->getName().str() + ":" +
963               std::to_string(CInfo.AccessIndex) + std::string(":") +
964               std::to_string(PatchImm) + std::string("$") + AccessStr;
965 
966   return Ty;
967 }
968 
969 /// Call/Kind is the base preserve_*_access_index() call. Attempts to do
970 /// transformation to a chain of relocable GEPs.
971 bool BPFAbstractMemberAccess::transformGEPChain(CallInst *Call,
972                                                 CallInfo &CInfo) {
973   std::string AccessKey;
974   MDNode *TypeMeta;
975   Value *Base = nullptr;
976   bool IsInt32Ret;
977 
978   IsInt32Ret = CInfo.Kind == BPFPreserveFieldInfoAI;
979   if (CInfo.Kind == BPFPreserveFieldInfoAI && CInfo.Metadata) {
980     TypeMeta = computeAccessKey(Call, CInfo, AccessKey, IsInt32Ret);
981   } else {
982     Base = computeBaseAndAccessKey(Call, CInfo, AccessKey, TypeMeta);
983     if (!Base)
984       return false;
985   }
986 
987   BasicBlock *BB = Call->getParent();
988   GlobalVariable *GV;
989 
990   if (GEPGlobals.find(AccessKey) == GEPGlobals.end()) {
991     IntegerType *VarType;
992     if (IsInt32Ret)
993       VarType = Type::getInt32Ty(BB->getContext()); // 32bit return value
994     else
995       VarType = Type::getInt64Ty(BB->getContext()); // 64bit ptr or enum value
996 
997     GV = new GlobalVariable(*M, VarType, false, GlobalVariable::ExternalLinkage,
998                             NULL, AccessKey);
999     GV->addAttribute(BPFCoreSharedInfo::AmaAttr);
1000     GV->setMetadata(LLVMContext::MD_preserve_access_index, TypeMeta);
1001     GEPGlobals[AccessKey] = GV;
1002   } else {
1003     GV = GEPGlobals[AccessKey];
1004   }
1005 
1006   if (CInfo.Kind == BPFPreserveFieldInfoAI) {
1007     // Load the global variable which represents the returned field info.
1008     LoadInst *LDInst;
1009     if (IsInt32Ret)
1010       LDInst = new LoadInst(Type::getInt32Ty(BB->getContext()), GV, "", Call);
1011     else
1012       LDInst = new LoadInst(Type::getInt64Ty(BB->getContext()), GV, "", Call);
1013 
1014     Instruction *PassThroughInst =
1015         BPFCoreSharedInfo::insertPassThrough(M, BB, LDInst, Call);
1016     Call->replaceAllUsesWith(PassThroughInst);
1017     Call->eraseFromParent();
1018     return true;
1019   }
1020 
1021   // For any original GEP Call and Base %2 like
1022   //   %4 = bitcast %struct.net_device** %dev1 to i64*
1023   // it is transformed to:
1024   //   %6 = load llvm.sk_buff:0:50$0:0:0:2:0
1025   //   %7 = bitcast %struct.sk_buff* %2 to i8*
1026   //   %8 = getelementptr i8, i8* %7, %6
1027   //   %9 = bitcast i8* %8 to i64*
1028   //   using %9 instead of %4
1029   // The original Call inst is removed.
1030 
1031   // Load the global variable.
1032   auto *LDInst = new LoadInst(Type::getInt64Ty(BB->getContext()), GV, "", Call);
1033 
1034   // Generate a BitCast
1035   auto *BCInst = new BitCastInst(Base, Type::getInt8PtrTy(BB->getContext()));
1036   BB->getInstList().insert(Call->getIterator(), BCInst);
1037 
1038   // Generate a GetElementPtr
1039   auto *GEP = GetElementPtrInst::Create(Type::getInt8Ty(BB->getContext()),
1040                                         BCInst, LDInst);
1041   BB->getInstList().insert(Call->getIterator(), GEP);
1042 
1043   // Generate a BitCast
1044   auto *BCInst2 = new BitCastInst(GEP, Call->getType());
1045   BB->getInstList().insert(Call->getIterator(), BCInst2);
1046 
1047   // For the following code,
1048   //    Block0:
1049   //      ...
1050   //      if (...) goto Block1 else ...
1051   //    Block1:
1052   //      %6 = load llvm.sk_buff:0:50$0:0:0:2:0
1053   //      %7 = bitcast %struct.sk_buff* %2 to i8*
1054   //      %8 = getelementptr i8, i8* %7, %6
1055   //      ...
1056   //      goto CommonExit
1057   //    Block2:
1058   //      ...
1059   //      if (...) goto Block3 else ...
1060   //    Block3:
1061   //      %6 = load llvm.bpf_map:0:40$0:0:0:2:0
1062   //      %7 = bitcast %struct.sk_buff* %2 to i8*
1063   //      %8 = getelementptr i8, i8* %7, %6
1064   //      ...
1065   //      goto CommonExit
1066   //    CommonExit
1067   // SimplifyCFG may generate:
1068   //    Block0:
1069   //      ...
1070   //      if (...) goto Block_Common else ...
1071   //     Block2:
1072   //       ...
1073   //      if (...) goto Block_Common else ...
1074   //    Block_Common:
1075   //      PHI = [llvm.sk_buff:0:50$0:0:0:2:0, llvm.bpf_map:0:40$0:0:0:2:0]
1076   //      %6 = load PHI
1077   //      %7 = bitcast %struct.sk_buff* %2 to i8*
1078   //      %8 = getelementptr i8, i8* %7, %6
1079   //      ...
1080   //      goto CommonExit
1081   //  For the above code, we cannot perform proper relocation since
1082   //  "load PHI" has two possible relocations.
1083   //
1084   // To prevent above tail merging, we use __builtin_bpf_passthrough()
1085   // where one of its parameters is a seq_num. Since two
1086   // __builtin_bpf_passthrough() funcs will always have different seq_num,
1087   // tail merging cannot happen. The __builtin_bpf_passthrough() will be
1088   // removed in the beginning of Target IR passes.
1089   //
1090   // This approach is also used in other places when global var
1091   // representing a relocation is used.
1092   Instruction *PassThroughInst =
1093       BPFCoreSharedInfo::insertPassThrough(M, BB, BCInst2, Call);
1094   Call->replaceAllUsesWith(PassThroughInst);
1095   Call->eraseFromParent();
1096 
1097   return true;
1098 }
1099 
1100 bool BPFAbstractMemberAccess::doTransformation(Function &F) {
1101   bool Transformed = false;
1102 
1103   // Collect PreserveDIAccessIndex Intrinsic call chains.
1104   // The call chains will be used to generate the access
1105   // patterns similar to GEP.
1106   collectAICallChains(F);
1107 
1108   for (auto &C : BaseAICalls)
1109     Transformed = transformGEPChain(C.first, C.second) || Transformed;
1110 
1111   return removePreserveAccessIndexIntrinsic(F) || Transformed;
1112 }
1113 
1114 PreservedAnalyses
1115 BPFAbstractMemberAccessPass::run(Function &F, FunctionAnalysisManager &AM) {
1116   return BPFAbstractMemberAccess(TM).run(F) ? PreservedAnalyses::none()
1117                                             : PreservedAnalyses::all();
1118 }
1119