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