| 1 | //===----- BPFMISimplifyPatchable.cpp - MI Simplify Patchable Insts -------===// |
| 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 targets a subset of instructions like below |
| 10 | // ld_imm64 r1, @global |
| 11 | // ldd r2, r1, 0 |
| 12 | // add r3, struct_base_reg, r2 |
| 13 | // |
| 14 | // Here @global should represent an AMA (abstruct member access). |
| 15 | // Such an access is subject to bpf load time patching. After this pass, the |
| 16 | // code becomes |
| 17 | // ld_imm64 r1, @global |
| 18 | // add r3, struct_base_reg, r1 |
| 19 | // |
| 20 | // Eventually, at BTF output stage, a relocation record will be generated |
| 21 | // for ld_imm64 which should be replaced later by bpf loader: |
| 22 | // r1 = <calculated field_info> |
| 23 | // add r3, struct_base_reg, r1 |
| 24 | // |
| 25 | // This pass also removes the intermediate load generated in IR pass for |
| 26 | // __builtin_btf_type_id() intrinsic. |
| 27 | // |
| 28 | //===----------------------------------------------------------------------===// |
| 29 | |
| 30 | #include "BPF.h" |
| 31 | #include "BPFCORE.h" |
| 32 | #include "BPFInstrInfo.h" |
| 33 | #include "BPFTargetMachine.h" |
| 34 | #include "llvm/CodeGen/MachineFunctionAnalysisManager.h" |
| 35 | #include "llvm/CodeGen/MachineFunctionPass.h" |
| 36 | #include "llvm/CodeGen/MachineInstrBuilder.h" |
| 37 | #include "llvm/CodeGen/MachinePassManager.h" |
| 38 | #include "llvm/CodeGen/MachineRegisterInfo.h" |
| 39 | #include "llvm/IR/Analysis.h" |
| 40 | #include "llvm/IR/GlobalVariable.h" |
| 41 | #include "llvm/Support/Debug.h" |
| 42 | #include <set> |
| 43 | |
| 44 | using namespace llvm; |
| 45 | |
| 46 | #define DEBUG_TYPE "bpf-mi-simplify-patchable" |
| 47 | |
| 48 | static cl::opt<bool> |
| 49 | DisableCOREOptimization("disable-bpf-core-optimization" , cl::Hidden, |
| 50 | cl::desc("Disable CORE relocation optimization" )); |
| 51 | |
| 52 | namespace { |
| 53 | |
| 54 | struct BPFMISimplifyPatchableImpl { |
| 55 | const BPFInstrInfo *TII; |
| 56 | MachineFunction *MF; |
| 57 | |
| 58 | private: |
| 59 | std::set<MachineInstr *> SkipInsts; |
| 60 | |
| 61 | // Initialize class variables. |
| 62 | void initialize(MachineFunction &MFParm); |
| 63 | |
| 64 | bool isLoadInst(unsigned Opcode); |
| 65 | bool removeLD(); |
| 66 | void processCandidate(MachineRegisterInfo *MRI, MachineBasicBlock &MBB, |
| 67 | MachineInstr &MI, Register &SrcReg, Register &DstReg, |
| 68 | const GlobalValue *GVal, bool IsAma); |
| 69 | void processDstReg(MachineRegisterInfo *MRI, Register &DstReg, |
| 70 | Register &SrcReg, const GlobalValue *GVal, |
| 71 | bool doSrcRegProp, bool IsAma); |
| 72 | void processInst(MachineRegisterInfo *MRI, MachineInstr *Inst, |
| 73 | MachineOperand *RelocOp, const GlobalValue *GVal); |
| 74 | void checkADDrr(MachineRegisterInfo *MRI, MachineOperand *RelocOp, |
| 75 | const GlobalValue *GVal); |
| 76 | void checkShift(MachineRegisterInfo *MRI, MachineBasicBlock &MBB, |
| 77 | MachineOperand *RelocOp, const GlobalValue *GVal, |
| 78 | unsigned Opcode); |
| 79 | |
| 80 | public: |
| 81 | // Main entry point for this pass. |
| 82 | bool runOnMachineFunction(MachineFunction &MF) { |
| 83 | initialize(MFParm&: MF); |
| 84 | return removeLD(); |
| 85 | } |
| 86 | }; |
| 87 | |
| 88 | class BPFMISimplifyPatchableLegacy : public MachineFunctionPass { |
| 89 | public: |
| 90 | static char ID; |
| 91 | |
| 92 | BPFMISimplifyPatchableLegacy() : MachineFunctionPass(ID) {} |
| 93 | |
| 94 | // Main entry point for this pass. |
| 95 | bool runOnMachineFunction(MachineFunction &MF) override; |
| 96 | }; |
| 97 | |
| 98 | // Initialize class variables. |
| 99 | void BPFMISimplifyPatchableImpl::initialize(MachineFunction &MFParm) { |
| 100 | MF = &MFParm; |
| 101 | TII = MF->getSubtarget<BPFSubtarget>().getInstrInfo(); |
| 102 | LLVM_DEBUG(dbgs() << "*** BPF simplify patchable insts pass ***\n\n" ); |
| 103 | } |
| 104 | |
| 105 | static bool isStoreImm(unsigned Opcode) { |
| 106 | return Opcode == BPF::STB_imm || Opcode == BPF::STH_imm || |
| 107 | Opcode == BPF::STW_imm || Opcode == BPF::STD_imm; |
| 108 | } |
| 109 | |
| 110 | static bool isStore32(unsigned Opcode) { |
| 111 | return Opcode == BPF::STB32 || Opcode == BPF::STH32 || Opcode == BPF::STW32 || |
| 112 | Opcode == BPF::STBREL32 || Opcode == BPF::STHREL32 || |
| 113 | Opcode == BPF::STWREL32; |
| 114 | } |
| 115 | |
| 116 | static bool isStore64(unsigned Opcode) { |
| 117 | return Opcode == BPF::STB || Opcode == BPF::STH || Opcode == BPF::STW || |
| 118 | Opcode == BPF::STD || Opcode == BPF::STDREL; |
| 119 | } |
| 120 | |
| 121 | static bool isLoad32(unsigned Opcode) { |
| 122 | return Opcode == BPF::LDB32 || Opcode == BPF::LDH32 || Opcode == BPF::LDW32 || |
| 123 | Opcode == BPF::LDBACQ32 || Opcode == BPF::LDHACQ32 || |
| 124 | Opcode == BPF::LDWACQ32; |
| 125 | } |
| 126 | |
| 127 | static bool isLoad64(unsigned Opcode) { |
| 128 | return Opcode == BPF::LDB || Opcode == BPF::LDH || Opcode == BPF::LDW || |
| 129 | Opcode == BPF::LDD || Opcode == BPF::LDDACQ; |
| 130 | } |
| 131 | |
| 132 | static bool isLoadSext(unsigned Opcode) { |
| 133 | return Opcode == BPF::LDBSX || Opcode == BPF::LDHSX || Opcode == BPF::LDWSX; |
| 134 | } |
| 135 | |
| 136 | bool BPFMISimplifyPatchableImpl::isLoadInst(unsigned Opcode) { |
| 137 | return isLoad32(Opcode) || isLoad64(Opcode) || isLoadSext(Opcode); |
| 138 | } |
| 139 | |
| 140 | void BPFMISimplifyPatchableImpl::checkADDrr(MachineRegisterInfo *MRI, |
| 141 | MachineOperand *RelocOp, |
| 142 | const GlobalValue *GVal) { |
| 143 | const MachineInstr *Inst = RelocOp->getParent(); |
| 144 | const MachineOperand *Op1 = &Inst->getOperand(i: 1); |
| 145 | const MachineOperand *Op2 = &Inst->getOperand(i: 2); |
| 146 | const MachineOperand *BaseOp = (RelocOp == Op1) ? Op2 : Op1; |
| 147 | |
| 148 | // Go through all uses of %1 as in %1 = ADD_rr %2, %3 |
| 149 | const MachineOperand Op0 = Inst->getOperand(i: 0); |
| 150 | for (MachineOperand &MO : |
| 151 | llvm::make_early_inc_range(Range: MRI->use_operands(Reg: Op0.getReg()))) { |
| 152 | // The candidate needs to have a unique definition. |
| 153 | if (!MRI->getUniqueVRegDef(Reg: MO.getReg())) |
| 154 | continue; |
| 155 | |
| 156 | MachineInstr *DefInst = MO.getParent(); |
| 157 | unsigned Opcode = DefInst->getOpcode(); |
| 158 | unsigned COREOp; |
| 159 | if (isLoad64(Opcode) || isLoadSext(Opcode)) |
| 160 | COREOp = BPF::CORE_LD64; |
| 161 | else if (isLoad32(Opcode)) |
| 162 | COREOp = BPF::CORE_LD32; |
| 163 | else if (isStore64(Opcode) || isStore32(Opcode) || isStoreImm(Opcode)) |
| 164 | COREOp = BPF::CORE_ST; |
| 165 | else |
| 166 | continue; |
| 167 | |
| 168 | // It must be a form of %2 = *(type *)(%1 + 0) or *(type *)(%1 + 0) = %2. |
| 169 | const MachineOperand &ImmOp = DefInst->getOperand(i: 2); |
| 170 | if (!ImmOp.isImm() || ImmOp.getImm() != 0) |
| 171 | continue; |
| 172 | |
| 173 | // Reject the form: |
| 174 | // %1 = ADD_rr %2, %3 |
| 175 | // *(type *)(%2 + 0) = %1 |
| 176 | if (isStore64(Opcode) || isStore32(Opcode)) { |
| 177 | const MachineOperand &Opnd = DefInst->getOperand(i: 0); |
| 178 | if (Opnd.isReg() && Opnd.getReg() == MO.getReg()) |
| 179 | continue; |
| 180 | } |
| 181 | |
| 182 | BuildMI(BB&: *DefInst->getParent(), I&: *DefInst, MIMD: DefInst->getDebugLoc(), MCID: TII->get(Opcode: COREOp)) |
| 183 | .add(MO: DefInst->getOperand(i: 0)).addImm(Val: Opcode).add(MO: *BaseOp) |
| 184 | .addGlobalAddress(GV: GVal); |
| 185 | DefInst->eraseFromParent(); |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | void BPFMISimplifyPatchableImpl::checkShift(MachineRegisterInfo *MRI, |
| 190 | MachineBasicBlock &MBB, |
| 191 | MachineOperand *RelocOp, |
| 192 | const GlobalValue *GVal, |
| 193 | unsigned Opcode) { |
| 194 | // Relocation operand should be the operand #2. |
| 195 | MachineInstr *Inst = RelocOp->getParent(); |
| 196 | if (RelocOp != &Inst->getOperand(i: 2)) |
| 197 | return; |
| 198 | |
| 199 | BuildMI(BB&: MBB, I&: *Inst, MIMD: Inst->getDebugLoc(), MCID: TII->get(Opcode: BPF::CORE_SHIFT)) |
| 200 | .add(MO: Inst->getOperand(i: 0)).addImm(Val: Opcode) |
| 201 | .add(MO: Inst->getOperand(i: 1)).addGlobalAddress(GV: GVal); |
| 202 | Inst->eraseFromParent(); |
| 203 | } |
| 204 | |
| 205 | void BPFMISimplifyPatchableImpl::processCandidate( |
| 206 | MachineRegisterInfo *MRI, MachineBasicBlock &MBB, MachineInstr &MI, |
| 207 | Register &SrcReg, Register &DstReg, const GlobalValue *GVal, bool IsAma) { |
| 208 | if (MRI->getRegClass(Reg: DstReg) == &BPF::GPR32RegClass) { |
| 209 | if (IsAma) { |
| 210 | // We can optimize such a pattern: |
| 211 | // %1:gpr = LD_imm64 @"llvm.s:0:4$0:2" |
| 212 | // %2:gpr32 = LDW32 %1:gpr, 0 |
| 213 | // %3:gpr = SUBREG_TO_REG %2:gpr32, %subreg.sub_32 |
| 214 | // %4:gpr = ADD_rr %0:gpr, %3:gpr |
| 215 | // or similar patterns below for non-alu32 case. |
| 216 | auto Begin = MRI->use_begin(RegNo: DstReg), End = MRI->use_end(); |
| 217 | decltype(End) NextI; |
| 218 | for (auto I = Begin; I != End; I = NextI) { |
| 219 | NextI = std::next(x: I); |
| 220 | if (!MRI->getUniqueVRegDef(Reg: I->getReg())) |
| 221 | continue; |
| 222 | |
| 223 | unsigned Opcode = I->getParent()->getOpcode(); |
| 224 | if (Opcode == BPF::SUBREG_TO_REG) { |
| 225 | Register TmpReg = I->getParent()->getOperand(i: 0).getReg(); |
| 226 | processDstReg(MRI, DstReg&: TmpReg, SrcReg&: DstReg, GVal, doSrcRegProp: false, IsAma); |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | BuildMI(BB&: MBB, I&: MI, MIMD: MI.getDebugLoc(), MCID: TII->get(Opcode: BPF::COPY), DestReg: DstReg) |
| 232 | .addReg(RegNo: SrcReg, Flags: {}, SubReg: BPF::sub_32); |
| 233 | return; |
| 234 | } |
| 235 | |
| 236 | // All uses of DstReg replaced by SrcReg |
| 237 | processDstReg(MRI, DstReg, SrcReg, GVal, doSrcRegProp: true, IsAma); |
| 238 | } |
| 239 | |
| 240 | void BPFMISimplifyPatchableImpl::processDstReg(MachineRegisterInfo *MRI, |
| 241 | Register &DstReg, |
| 242 | Register &SrcReg, |
| 243 | const GlobalValue *GVal, |
| 244 | bool doSrcRegProp, bool IsAma) { |
| 245 | auto Begin = MRI->use_begin(RegNo: DstReg), End = MRI->use_end(); |
| 246 | decltype(End) NextI; |
| 247 | for (auto I = Begin; I != End; I = NextI) { |
| 248 | NextI = std::next(x: I); |
| 249 | if (doSrcRegProp) { |
| 250 | // In situations like below it is not known if usage is a kill |
| 251 | // after setReg(): |
| 252 | // |
| 253 | // .-> %2:gpr = LD_imm64 @"llvm.t:0:0$0:0" |
| 254 | // | |
| 255 | // |`----------------. |
| 256 | // | %3:gpr = LDD %2:gpr, 0 |
| 257 | // | %4:gpr = ADD_rr %0:gpr(tied-def 0), killed %3:gpr <--- (1) |
| 258 | // | %5:gpr = LDD killed %4:gpr, 0 ^^^^^^^^^^^^^ |
| 259 | // | STD killed %5:gpr, %1:gpr, 0 this is I |
| 260 | // `----------------. |
| 261 | // %6:gpr = LDD %2:gpr, 0 |
| 262 | // %7:gpr = ADD_rr %0:gpr(tied-def 0), killed %6:gpr <--- (2) |
| 263 | // %8:gpr = LDD killed %7:gpr, 0 ^^^^^^^^^^^^^ |
| 264 | // STD killed %8:gpr, %1:gpr, 0 this is I |
| 265 | // |
| 266 | // Instructions (1) and (2) would be updated by setReg() to: |
| 267 | // |
| 268 | // ADD_rr %0:gpr(tied-def 0), %2:gpr |
| 269 | // |
| 270 | // %2:gpr is not killed at (1), so it is necessary to remove kill flag |
| 271 | // from I. |
| 272 | I->setReg(SrcReg); |
| 273 | I->setIsKill(false); |
| 274 | } |
| 275 | |
| 276 | // The candidate needs to have a unique definition. |
| 277 | if (IsAma && MRI->getUniqueVRegDef(Reg: I->getReg())) |
| 278 | processInst(MRI, Inst: I->getParent(), RelocOp: &*I, GVal); |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | // Check to see whether we could do some optimization |
| 283 | // to attach relocation to downstream dependent instructions. |
| 284 | // Two kinds of patterns are recognized below: |
| 285 | // Pattern 1: |
| 286 | // %1 = LD_imm64 @"llvm.b:0:4$0:1" <== patch_imm = 4 |
| 287 | // %2 = LDD %1, 0 <== this insn will be removed |
| 288 | // %3 = ADD_rr %0, %2 |
| 289 | // %4 = LDW[32] %3, 0 OR STW[32] %4, %3, 0 |
| 290 | // The `%4 = ...` will be transformed to |
| 291 | // CORE_[ALU32_]MEM(%4, mem_opcode, %0, @"llvm.b:0:4$0:1") |
| 292 | // and later on, BTF emit phase will translate to |
| 293 | // %4 = LDW[32] %0, 4 STW[32] %4, %0, 4 |
| 294 | // and attach a relocation to it. |
| 295 | // Pattern 2: |
| 296 | // %15 = LD_imm64 @"llvm.t:5:63$0:2" <== relocation type 5 |
| 297 | // %16 = LDD %15, 0 <== this insn will be removed |
| 298 | // %17 = SRA_rr %14, %16 |
| 299 | // The `%17 = ...` will be transformed to |
| 300 | // %17 = CORE_SHIFT(SRA_ri, %14, @"llvm.t:5:63$0:2") |
| 301 | // and later on, BTF emit phase will translate to |
| 302 | // %r4 = SRA_ri %r4, 63 |
| 303 | void BPFMISimplifyPatchableImpl::processInst(MachineRegisterInfo *MRI, |
| 304 | MachineInstr *Inst, |
| 305 | MachineOperand *RelocOp, |
| 306 | const GlobalValue *GVal) { |
| 307 | unsigned Opcode = Inst->getOpcode(); |
| 308 | if (isLoadInst(Opcode)) { |
| 309 | SkipInsts.insert(x: Inst); |
| 310 | return; |
| 311 | } |
| 312 | |
| 313 | if (DisableCOREOptimization) |
| 314 | return; |
| 315 | |
| 316 | if (Opcode == BPF::ADD_rr) { |
| 317 | // If the struct offset is greater than INT16_MAX, skip optimization. |
| 318 | StringRef AccessPattern = GVal->getName(); |
| 319 | size_t FirstDollar = AccessPattern.find_first_of(C: '$'); |
| 320 | size_t FirstColon = AccessPattern.find_first_of(C: ':'); |
| 321 | size_t SecondColon = AccessPattern.find_first_of(C: ':', From: FirstColon + 1); |
| 322 | StringRef PatchImmStr = |
| 323 | AccessPattern.substr(Start: SecondColon + 1, N: FirstDollar - SecondColon); |
| 324 | int PatchImm = std::stoll(str: std::string(PatchImmStr)); |
| 325 | if (PatchImm <= INT16_MAX) |
| 326 | checkADDrr(MRI, RelocOp, GVal); |
| 327 | return; |
| 328 | } |
| 329 | |
| 330 | if (Opcode == BPF::SLL_rr) |
| 331 | checkShift(MRI, MBB&: *Inst->getParent(), RelocOp, GVal, Opcode: BPF::SLL_ri); |
| 332 | else if (Opcode == BPF::SRA_rr) |
| 333 | checkShift(MRI, MBB&: *Inst->getParent(), RelocOp, GVal, Opcode: BPF::SRA_ri); |
| 334 | else if (Opcode == BPF::SRL_rr) |
| 335 | checkShift(MRI, MBB&: *Inst->getParent(), RelocOp, GVal, Opcode: BPF::SRL_ri); |
| 336 | } |
| 337 | |
| 338 | /// Remove unneeded Load instructions. |
| 339 | bool BPFMISimplifyPatchableImpl::removeLD() { |
| 340 | MachineRegisterInfo *MRI = &MF->getRegInfo(); |
| 341 | MachineInstr *ToErase = nullptr; |
| 342 | bool Changed = false; |
| 343 | |
| 344 | for (MachineBasicBlock &MBB : *MF) { |
| 345 | for (MachineInstr &MI : MBB) { |
| 346 | if (ToErase) { |
| 347 | ToErase->eraseFromParent(); |
| 348 | ToErase = nullptr; |
| 349 | } |
| 350 | |
| 351 | // Ensure the register format is LOAD <reg>, <reg>, 0 |
| 352 | if (!isLoadInst(Opcode: MI.getOpcode())) |
| 353 | continue; |
| 354 | |
| 355 | if (SkipInsts.find(x: &MI) != SkipInsts.end()) |
| 356 | continue; |
| 357 | |
| 358 | if (!MI.getOperand(i: 0).isReg() || !MI.getOperand(i: 1).isReg()) |
| 359 | continue; |
| 360 | |
| 361 | if (!MI.getOperand(i: 2).isImm() || MI.getOperand(i: 2).getImm()) |
| 362 | continue; |
| 363 | |
| 364 | Register DstReg = MI.getOperand(i: 0).getReg(); |
| 365 | Register SrcReg = MI.getOperand(i: 1).getReg(); |
| 366 | |
| 367 | MachineInstr *DefInst = MRI->getUniqueVRegDef(Reg: SrcReg); |
| 368 | if (!DefInst) |
| 369 | continue; |
| 370 | |
| 371 | if (DefInst->getOpcode() != BPF::LD_imm64) |
| 372 | continue; |
| 373 | |
| 374 | const MachineOperand &MO = DefInst->getOperand(i: 1); |
| 375 | if (!MO.isGlobal()) |
| 376 | continue; |
| 377 | |
| 378 | const GlobalValue *GVal = MO.getGlobal(); |
| 379 | auto *GVar = dyn_cast<GlobalVariable>(Val: GVal); |
| 380 | if (!GVar) |
| 381 | continue; |
| 382 | |
| 383 | // Global variables representing structure offset or type id. |
| 384 | bool IsAma = false; |
| 385 | if (GVar->hasAttribute(Kind: BPFCoreSharedInfo::AmaAttr)) |
| 386 | IsAma = true; |
| 387 | else if (!GVar->hasAttribute(Kind: BPFCoreSharedInfo::TypeIdAttr)) |
| 388 | continue; |
| 389 | |
| 390 | processCandidate(MRI, MBB, MI, SrcReg, DstReg, GVal, IsAma); |
| 391 | |
| 392 | ToErase = &MI; |
| 393 | Changed = true; |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | return Changed; |
| 398 | } |
| 399 | |
| 400 | } // namespace |
| 401 | |
| 402 | INITIALIZE_PASS(BPFMISimplifyPatchableLegacy, DEBUG_TYPE, |
| 403 | "BPF PreEmit SimplifyPatchable" , false, false) |
| 404 | |
| 405 | char BPFMISimplifyPatchableLegacy::ID = 0; |
| 406 | FunctionPass *llvm::createBPFMISimplifyPatchableLegacyPass() { |
| 407 | return new BPFMISimplifyPatchableLegacy(); |
| 408 | } |
| 409 | |
| 410 | bool BPFMISimplifyPatchableLegacy::runOnMachineFunction(MachineFunction &MF) { |
| 411 | if (skipFunction(F: MF.getFunction())) |
| 412 | return false; |
| 413 | |
| 414 | BPFMISimplifyPatchableImpl Impl; |
| 415 | return Impl.runOnMachineFunction(MF); |
| 416 | } |
| 417 | |
| 418 | PreservedAnalyses |
| 419 | BPFMISimplifyPatchablePass::run(MachineFunction &MF, |
| 420 | MachineFunctionAnalysisManager &MFAM) { |
| 421 | BPFMISimplifyPatchableImpl Impl; |
| 422 | return Impl.runOnMachineFunction(MF) |
| 423 | ? getMachineFunctionPassPreservedAnalyses() |
| 424 | .preserveSet<CFGAnalyses>() |
| 425 | : PreservedAnalyses::all(); |
| 426 | } |
| 427 | |