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