// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Tsiry Sandratraina // // kwbridge: an LLVM pass plugin for XNU on wasm (.agents/xnu.md, "The kext // bridge"). Closed arm64e kexts run in kwemu; this pass is the wasm side of // the calling convention between them and the kernel. Built by // kernel/xnu.sh into vendor/build/xnu/kwbridge.dylib, loaded with // -fpass-plugin for every kernel and built-in kext object. // // - Every indirect call gets a range check: a target at or above // kw_kext_lo is arm64 code, and goes to kw_kext_call() (osfmk/wasm/ // kw_kext.c) with its arguments laid out by Darwin's arm64 rules in a // struct kw_xframe; everything else is the call as it was. // - Every function the kexts may call (external, or address-taken) gets // an entry, __kw_entry.NAME(struct kw_regs *), that reads its arguments // from arm64 registers and stack and writes its result back. // - kw_syms, a section of struct kw_sym records: name, address and entry // of each function, name and address of each global. The bridge binds // the kexts' imports with it. // // The arm64 rules (Apple's variant of AAPCS64): integers and pointers in // x0..x7, floating point in v0..v7, then the stack, each argument at its // natural alignment (not in 8-byte slots); an indirect result in x8; // aggregates of at most 16 bytes in up to two x registers (homogeneous // floating-point aggregates of up to four in v registers), larger ones by // a pointer to a copy. The wasm side passes aggregates byval (a pointer to // the caller's copy) and returns them through sret. #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/IR/PassManager.h" #include "llvm/Passes/PassBuilder.h" #include "llvm/Plugins/PassPlugin.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include #include #include using namespace llvm; namespace { // struct kw_xframe (osfmk/wasm/kw_kext.h): arguments in, results out. constexpr unsigned XF_X = 0; // uint64_t x[9]: x0..x7, x8 (indirect result) constexpr unsigned XF_V = 72; // uint64_t v[8]: low 64 bits of v0..v7 constexpr unsigned XF_RX = 136; // uint64_t rx[2]: x0, x1 on return constexpr unsigned XF_RV = 152; // uint64_t rv[4]: v0..v3 on return constexpr unsigned XF_STACK = 192; // stack arguments, as they go at sp // struct kw_regs (include/kw_emu.h). constexpr unsigned KR_X = 0, KR_SP = 248, KR_V = 288; // Where one value (or one piece of an aggregate) goes. struct Piece { enum Kind { GPR, FPR, STACK } kind; unsigned index; // register number, or stack offset unsigned offset; // byte offset in the aggregate (0 for scalars) Type *type; // the type moved: an integer, float or double }; // How one IR argument travels. struct ArgPlan { enum Kind { SCALAR, AGG, SRET, PTR_COPY, UNSUPPORTED } kind; std::vector pieces; }; struct RetPlan { enum Kind { VOID, SCALAR, AGG_REGS, AGG_X8, UNSUPPORTED } kind; std::vector pieces; // registers (GPR/FPR index), aggregate offsets Type *aggType = nullptr; int sretArg = -1; // IR argument index of the wasm sret pointer }; struct Plan { std::vector args; RetPlan ret; unsigned stackBytes = 0; bool ok = true; }; // A homogeneous floating-point aggregate: up to four of one float type. static bool hfa(Type *t, Type *&elt, unsigned &n) { if (t->isFloatTy() || t->isDoubleTy()) { if (elt && elt != t) return false; elt = t; n++; return n <= 4; } if (auto *st = dyn_cast(t)) { if (st->getNumElements() == 0) return false; for (Type *e : st->elements()) if (!hfa(e, elt, n)) return false; return true; } if (auto *at = dyn_cast(t)) { for (uint64_t i = 0; i < at->getNumElements(); i++) if (!hfa(at->getElementType(), elt, n)) return false; return true; } return false; } static unsigned alignTo(unsigned v, unsigned a) { return (v + a - 1) & ~(a - 1); } // Pieces of an aggregate of `size` bytes in integer words. static void aggWords(LLVMContext &C, uint64_t size, std::vector &out, Piece::Kind k, unsigned first) { for (uint64_t off = 0, i = 0; off < size; off += 8, i++) { unsigned bytes = size - off >= 8 ? 8 : (unsigned)(size - off); out.push_back({k, (unsigned)(first + (k == Piece::STACK ? off : i)), (unsigned)off, Type::getIntNTy(C, bytes * 8)}); } } static Plan plan(FunctionType *ft, AttributeList attrs, const DataLayout &DL) { Plan p; LLVMContext &C = ft->getContext(); unsigned ngpr = 0, nfpr = 0, stack = 0; auto toStack = [&](Type *t, unsigned off = 0) { unsigned sz = DL.getTypeStoreSize(t), al = sz >= 8 ? 8 : (sz ? sz : 1); stack = alignTo(stack, al); Piece pc{Piece::STACK, stack, off, t}; stack += sz; return pc; }; Type *rt = ft->getReturnType(); for (unsigned i = 0; i < ft->getNumParams(); i++) { Type *t = ft->getParamType(i); ArgPlan a; if (attrs.hasParamAttr(i, Attribute::StructRet)) { Type *st = attrs.getParamStructRetType(i); uint64_t sz = DL.getTypeAllocSize(st); Type *elt = nullptr; unsigned n = 0; p.ret.sretArg = i; p.ret.aggType = st; if (hfa(st, elt, n)) { p.ret.kind = RetPlan::AGG_REGS; for (unsigned k = 0; k < n; k++) p.ret.pieces.push_back({Piece::FPR, k, (unsigned)(k * DL.getTypeAllocSize(elt)), elt}); } else if (sz <= 16) { p.ret.kind = RetPlan::AGG_REGS; aggWords(C, sz, p.ret.pieces, Piece::GPR, 0); } else { p.ret.kind = RetPlan::AGG_X8; } a.kind = ArgPlan::SRET; p.args.push_back(a); continue; } if (attrs.hasParamAttr(i, Attribute::ByVal)) { Type *bt = attrs.getParamByValType(i); uint64_t sz = DL.getTypeAllocSize(bt); Type *elt = nullptr; unsigned n = 0; if (hfa(bt, elt, n)) { a.kind = ArgPlan::AGG; unsigned esz = DL.getTypeAllocSize(elt); if (nfpr + n <= 8) { for (unsigned k = 0; k < n; k++) a.pieces.push_back({Piece::FPR, nfpr++, k * esz, elt}); } else { nfpr = 8; for (unsigned k = 0; k < n; k++) a.pieces.push_back(toStack(elt, k * esz)); } } else if (sz <= 16) { a.kind = ArgPlan::AGG; unsigned words = (sz + 7) / 8; if (ngpr + words <= 8) { aggWords(C, sz, a.pieces, Piece::GPR, ngpr); ngpr += words; } else { ngpr = 8; stack = alignTo(stack, 8); aggWords(C, sz, a.pieces, Piece::STACK, stack); stack += words * 8; } } else { // A pointer to a copy: the wasm caller's byval copy is one. a.kind = ArgPlan::PTR_COPY; Type *pt = Type::getInt64Ty(C); a.pieces.push_back(ngpr < 8 ? Piece{Piece::GPR, ngpr++, 0, pt} : toStack(pt)); } p.args.push_back(a); continue; } a.kind = ArgPlan::SCALAR; if (t->isPointerTy() || (t->isIntegerTy() && t->getIntegerBitWidth() <= 64)) { Type *it = t->isPointerTy() ? Type::getInt64Ty(C) : t; a.pieces.push_back(ngpr < 8 ? Piece{Piece::GPR, ngpr++, 0, it} : toStack(it)); } else if (t->isFloatTy() || t->isDoubleTy()) { a.pieces.push_back(nfpr < 8 ? Piece{Piece::FPR, nfpr++, 0, t} : toStack(t)); } else if (t->isIntegerTy(128)) { if (ngpr & 1) ngpr++; if (ngpr + 2 <= 8) { a.pieces.push_back({Piece::GPR, ngpr++, 0, Type::getInt64Ty(C)}); a.pieces.push_back({Piece::GPR, ngpr++, 8, Type::getInt64Ty(C)}); } else { ngpr = 8; stack = alignTo(stack, 16); a.pieces.push_back({Piece::STACK, stack, 0, Type::getInt64Ty(C)}); a.pieces.push_back({Piece::STACK, stack + 8, 8, Type::getInt64Ty(C)}); stack += 16; } } else { a.kind = ArgPlan::UNSUPPORTED; p.ok = false; } p.args.push_back(a); } if (p.ret.sretArg < 0) { if (rt->isVoidTy()) { p.ret.kind = RetPlan::VOID; } else if (rt->isPointerTy() || (rt->isIntegerTy() && rt->getIntegerBitWidth() <= 64)) { p.ret.kind = RetPlan::SCALAR; p.ret.pieces.push_back({Piece::GPR, 0, 0, rt->isPointerTy() ? Type::getInt64Ty(C) : rt}); } else if (rt->isFloatTy() || rt->isDoubleTy()) { p.ret.kind = RetPlan::SCALAR; p.ret.pieces.push_back({Piece::FPR, 0, 0, rt}); } else if (rt->isIntegerTy(128)) { p.ret.kind = RetPlan::SCALAR; p.ret.pieces.push_back({Piece::GPR, 0, 0, Type::getInt64Ty(C)}); p.ret.pieces.push_back({Piece::GPR, 1, 8, Type::getInt64Ty(C)}); } else { p.ret.kind = RetPlan::UNSUPPORTED; p.ok = false; } } p.stackBytes = alignTo(stack, 16); return p; } // A value of type `want` from the low bits of a 64-bit word. static Value *fromWord(IRBuilder<> &B, Value *w, Type *want) { if (want->isIntegerTy(64)) return w; if (want->isIntegerTy()) return B.CreateTrunc(w, want); if (want->isDoubleTy()) return B.CreateBitCast(w, want); if (want->isFloatTy()) return B.CreateBitCast(B.CreateTrunc(w, B.getInt32Ty()), want); if (want->isPointerTy()) return B.CreateIntToPtr(w, want); llvm_unreachable("fromWord"); } // A 64-bit word holding v in its low bits (integers extended as `sext`). static Value *toWord(IRBuilder<> &B, Value *v, bool sext = false) { Type *t = v->getType(); if (t->isPointerTy()) return B.CreatePtrToInt(v, B.getInt64Ty()); if (t->isIntegerTy(64)) return v; if (t->isIntegerTy()) return sext ? B.CreateSExt(v, B.getInt64Ty()) : B.CreateZExt(v, B.getInt64Ty()); if (t->isDoubleTy()) return B.CreateBitCast(v, B.getInt64Ty()); if (t->isFloatTy()) return B.CreateZExt(B.CreateBitCast(v, B.getInt32Ty()), B.getInt64Ty()); llvm_unreachable("toWord"); } static std::string sigKey(FunctionType *ft, AttributeList attrs) { std::string s; raw_string_ostream os(s); ft->print(os); for (unsigned i = 0; i < ft->getNumParams(); i++) { if (attrs.hasParamAttr(i, Attribute::StructRet)) { os << " sret" << i << ":"; attrs.getParamStructRetType(i)->print(os); } if (attrs.hasParamAttr(i, Attribute::ByVal)) { os << " byval" << i << ":"; attrs.getParamByValType(i)->print(os); } if (attrs.hasParamAttr(i, Attribute::SExt)) os << " sext" << i; } return s; } struct KWBridge : PassInfoMixin { Module *M = nullptr; const DataLayout *DL = nullptr; std::map callers; GlobalVariable *lo = nullptr; Function *kextCall = nullptr, *badCall = nullptr; StructType *symTy = nullptr; std::vector syms; Type *i64() { return Type::getInt64Ty(M->getContext()); } Type *ptr() { return PointerType::get(M->getContext(), 0); } // The kext side of an indirect call: __kw_xcall.N(fp, args...). Function *caller(FunctionType *ft, AttributeList attrs) { std::string key = sigKey(ft, attrs); auto it = callers.find(key); if (it != callers.end()) return it->second; LLVMContext &C = M->getContext(); std::vector params{ptr()}; for (Type *t : ft->params()) params.push_back(t); auto *wt = FunctionType::get(ft->getReturnType(), params, false); auto *F = Function::Create(wt, GlobalValue::PrivateLinkage, "__kw_xcall." + std::to_string(callers.size()), M); callers[key] = F; for (unsigned i = 0; i < ft->getNumParams(); i++) { // Keep sret/byval types on our parameters (for reading the copy). if (attrs.hasParamAttr(i, Attribute::StructRet)) F->addParamAttr(i + 1, Attribute::getWithStructRetType(C, attrs.getParamStructRetType(i))); } Plan p = plan(ft, attrs, *DL); IRBuilder<> B(BasicBlock::Create(C, "", F)); if (!p.ok) { B.CreateCall(badCall, {F->getArg(0)}); B.CreateUnreachable(); return F; } Value *frame = B.CreateAlloca(B.getInt8Ty(), B.getInt32(XF_STACK + p.stackBytes)); B.CreateMemSet(frame, B.getInt8(0), XF_STACK + p.stackBytes, MaybeAlign(16)); auto slot = [&](unsigned off) { return B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), frame, off); }; auto store = [&](const Piece &pc, Value *v) { unsigned off = pc.kind == Piece::GPR ? XF_X + 8 * pc.index : pc.kind == Piece::FPR ? XF_V + 8 * pc.index : XF_STACK + pc.index; if (pc.kind == Piece::STACK) B.CreateStore(v, slot(off)); // natural size on the stack else B.CreateStore(toWord(B, v, false), slot(off)); }; for (unsigned i = 0; i < ft->getNumParams(); i++) { Value *arg = F->getArg(i + 1); const ArgPlan &a = p.args[i]; switch (a.kind) { case ArgPlan::SRET: if (p.ret.kind == RetPlan::AGG_X8) B.CreateStore(B.CreatePtrToInt(arg, i64()), slot(XF_X + 8 * 8)); break; case ArgPlan::SCALAR: if (a.pieces.size() == 2) { // i128 store(a.pieces[0], B.CreateTrunc(arg, i64())); store(a.pieces[1], B.CreateTrunc(B.CreateLShr(arg, 64), i64())); } else { Value *v = arg; if (attrs.hasParamAttr(i, Attribute::SExt) && a.pieces[0].kind != Piece::STACK) v = B.CreateSExt(arg, i64()); store(a.pieces[0], v); } break; case ArgPlan::AGG: for (const Piece &pc : a.pieces) store(pc, B.CreateLoad(pc.type, B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), arg, pc.offset))); break; case ArgPlan::PTR_COPY: store(a.pieces[0], B.CreatePtrToInt(arg, i64())); break; case ArgPlan::UNSUPPORTED: break; } } B.CreateCall(kextCall, {F->getArg(0), frame, B.getInt32(p.stackBytes)}); auto rslot = [&](const Piece &pc) { return slot(pc.kind == Piece::GPR ? XF_RX + 8 * pc.index : XF_RV + 8 * pc.index); }; switch (p.ret.kind) { case RetPlan::VOID: case RetPlan::AGG_X8: if (ft->getReturnType()->isVoidTy()) B.CreateRetVoid(); else B.CreateRet(UndefValue::get(ft->getReturnType())); break; case RetPlan::SCALAR: { Type *rt = ft->getReturnType(); if (p.ret.pieces.size() == 2) { Value *lo64 = B.CreateZExt(B.CreateLoad(i64(), rslot(p.ret.pieces[0])), rt); Value *hi64 = B.CreateZExt(B.CreateLoad(i64(), rslot(p.ret.pieces[1])), rt); B.CreateRet(B.CreateOr(lo64, B.CreateShl(hi64, 64))); } else { Value *w = B.CreateLoad(i64(), rslot(p.ret.pieces[0])); B.CreateRet(fromWord(B, w, rt)); } break; } case RetPlan::AGG_REGS: { Value *dst = F->getArg(p.ret.sretArg + 1); for (const Piece &pc : p.ret.pieces) { Value *w = B.CreateLoad(i64(), rslot(pc)); B.CreateStore(fromWord(B, w, pc.type), B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), dst, pc.offset)); } if (ft->getReturnType()->isVoidTy()) B.CreateRetVoid(); else B.CreateRet(UndefValue::get(ft->getReturnType())); break; } case RetPlan::UNSUPPORTED: B.CreateUnreachable(); break; } return F; } // The wasm side of a kext's call to F: __kw_entry.F(struct kw_regs *r). Function *entry(Function &Fn) { LLVMContext &C = M->getContext(); FunctionType *ft = Fn.getFunctionType(); AttributeList attrs = Fn.getAttributes(); Plan p = plan(ft, attrs, *DL); if (!p.ok || ft->isVarArg()) return nullptr; auto *et = FunctionType::get(Type::getVoidTy(C), {ptr()}, false); GlobalValue::LinkageTypes link = Fn.hasLocalLinkage() ? GlobalValue::InternalLinkage : GlobalValue::LinkOnceODRLinkage; auto *E = Function::Create(et, link, "__kw_entry." + Fn.getName(), M); if (link == GlobalValue::LinkOnceODRLinkage && M->getTargetTriple().supportsCOMDAT()) { E->setComdat(M->getOrInsertComdat(E->getName())); } IRBuilder<> B(BasicBlock::Create(C, "", E)); Value *r = E->getArg(0); Value *sp = B.CreateIntToPtr(B.CreateLoad(i64(), B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), r, KR_SP)), ptr()); auto src = [&](const Piece &pc) -> Value * { if (pc.kind == Piece::GPR) return B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), r, KR_X + 8 * pc.index); if (pc.kind == Piece::FPR) return B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), r, KR_V + 16 * pc.index); return B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), sp, pc.index); }; auto load = [&](const Piece &pc) -> Value * { if (pc.kind == Piece::STACK) return B.CreateLoad(pc.type, src(pc)); return fromWord(B, B.CreateLoad(i64(), src(pc)), pc.type); }; std::vector args; Value *sret = nullptr; for (unsigned i = 0; i < ft->getNumParams(); i++) { const ArgPlan &a = p.args[i]; Type *t = ft->getParamType(i); switch (a.kind) { case ArgPlan::SRET: if (p.ret.kind == RetPlan::AGG_X8) { sret = B.CreateIntToPtr(B.CreateLoad(i64(), B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), r, KR_X + 64)), ptr()); } else { sret = B.CreateAlloca(p.ret.aggType); } args.push_back(sret); break; case ArgPlan::SCALAR: if (a.pieces.size() == 2) { Value *lo64 = B.CreateZExt(load(a.pieces[0]), t); Value *hi64 = B.CreateZExt(load(a.pieces[1]), t); args.push_back(B.CreateOr(lo64, B.CreateShl(hi64, 64))); } else if (t->isPointerTy()) { args.push_back(B.CreateIntToPtr(load(a.pieces[0]), t)); } else { args.push_back(load(a.pieces[0])); } break; case ArgPlan::AGG: { Value *copy = B.CreateAlloca(attrs.getParamByValType(i)); for (const Piece &pc : a.pieces) B.CreateStore(load(pc), B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), copy, pc.offset)); args.push_back(copy); break; } case ArgPlan::PTR_COPY: args.push_back(B.CreateIntToPtr(load(a.pieces[0]), t)); break; case ArgPlan::UNSUPPORTED: return nullptr; } } CallInst *call = B.CreateCall(ft, &Fn, args); call->setAttributes(attrs); call->setCallingConv(Fn.getCallingConv()); auto dst = [&](const Piece &pc) { return B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), r, pc.kind == Piece::GPR ? KR_X + 8 * pc.index : KR_V + 16 * pc.index); }; switch (p.ret.kind) { case RetPlan::SCALAR: if (p.ret.pieces.size() == 2) { B.CreateStore(B.CreateTrunc(call, i64()), dst(p.ret.pieces[0])); B.CreateStore(B.CreateTrunc(B.CreateLShr(call, 64), i64()), dst(p.ret.pieces[1])); } else { bool sext = attrs.hasRetAttr(Attribute::SExt); B.CreateStore(toWord(B, call, sext), dst(p.ret.pieces[0])); } break; case RetPlan::AGG_REGS: for (const Piece &pc : p.ret.pieces) B.CreateStore(toWord(B, B.CreateLoad(pc.type, B.CreateConstInBoundsGEP1_32(B.getInt8Ty(), sret, pc.offset))), dst(pc)); break; default: break; } B.CreateRetVoid(); return E; } void addSym(StringRef name, Constant *addr, Constant *ent, uint64_t flags) { LLVMContext &C = M->getContext(); Constant *str = ConstantDataArray::getString(C, name); auto *gs = new GlobalVariable(*M, str->getType(), true, GlobalValue::PrivateLinkage, str, "__kw_symname"); syms.push_back(ConstantStruct::get(symTy, {gs, ConstantExpr::getPtrToInt(addr, i64()), ent ? ConstantExpr::getPtrToInt(ent, i64()) : ConstantInt::get(i64(), 0), ConstantInt::get(i64(), flags)})); } PreservedAnalyses run(Module &Mod, ModuleAnalysisManager &) { M = &Mod; DL = &Mod.getDataLayout(); LLVMContext &C = Mod.getContext(); lo = Mod.getGlobalVariable("kw_kext_lo"); if (!lo) lo = new GlobalVariable(Mod, i64(), false, GlobalValue::ExternalLinkage, nullptr, "kw_kext_lo"); kextCall = cast(Mod.getOrInsertFunction("kw_kext_call", FunctionType::get(Type::getVoidTy(C), {ptr(), ptr(), Type::getInt32Ty(C)}, false)).getCallee()); badCall = cast(Mod.getOrInsertFunction("kw_kext_call_unsupported", FunctionType::get(Type::getVoidTy(C), {ptr()}, false)).getCallee()); symTy = StructType::get(C, {ptr(), i64(), i64(), i64()}); // Functions and globals as they are before we add any. std::vector fns; for (Function &F : Mod) if (!F.isDeclaration() && !F.isIntrinsic() && !F.getName().starts_with("__kw_")) fns.push_back(&F); std::vector gvs; for (GlobalVariable &G : Mod.globals()) if (!G.isDeclaration() && !G.hasLocalLinkage() && !G.getName().starts_with("__kw_") && !G.getName().starts_with("llvm.")) gvs.push_back(&G); // 1. Indirect calls. std::vector sites; for (Function *F : fns) for (Instruction &I : instructions(*F)) if (auto *CI = dyn_cast(&I)) if (CI->isIndirectCall() && !CI->isInlineAsm() && !CI->isMustTailCall() && !CI->getFunctionType()->isVarArg()) sites.push_back(CI); for (CallInst *CI : sites) { IRBuilder<> B(CI); B.SetCurrentDebugLocation(CI->getDebugLoc()); Value *fp = B.CreatePtrToInt(CI->getCalledOperand(), i64()); Value *isKext = B.CreateICmpUGE(fp, B.CreateLoad(i64(), lo)); Instruction *thenT, *elseT; SplitBlockAndInsertIfThenElse(isKext, CI, &thenT, &elseT); CI->moveBefore(elseT->getIterator()); B.SetInsertPoint(thenT); B.SetCurrentDebugLocation(CI->getDebugLoc()); std::vector args{CI->getCalledOperand()}; for (Value *a : CI->args()) args.push_back(a); Function *w = caller(CI->getFunctionType(), CI->getAttributes()); CallInst *kc = B.CreateCall(w, args); if (!CI->getType()->isVoidTy()) { BasicBlock *tail = thenT->getSuccessor(0); PHINode *phi = PHINode::Create(CI->getType(), 2, "", tail->begin()); CI->replaceAllUsesWith(phi); phi->addIncoming(kc, thenT->getParent()); phi->addIncoming(CI, elseT->getParent()); } } // 2. Entries and the symbol records. for (Function *F : fns) { if (F->hasFnAttribute(Attribute::Naked) || F->hasAvailableExternallyLinkage()) continue; bool ext = !F->hasLocalLinkage(); if (!ext && !F->hasAddressTaken()) continue; Function *E = entry(*F); addSym(ext ? F->getName() : "", F, E, (ext ? 0 : 2) | (E ? 0 : 4)); } for (GlobalVariable *G : gvs) addSym(G->getName(), G, nullptr, 1); if (!syms.empty()) { auto *at = ArrayType::get(symTy, syms.size()); auto *g = new GlobalVariable(Mod, at, true, GlobalValue::PrivateLinkage, ConstantArray::get(at, syms), "__kw_syms"); g->setSection("kw_syms"); g->setAlignment(Align(8)); appendToUsed(Mod, {g}); } return PreservedAnalyses::none(); } static void appendToUsed(Module &Mod, ArrayRef vals) { LLVMContext &C = Mod.getContext(); GlobalVariable *used = Mod.getGlobalVariable("llvm.used"); std::vector list; if (used) { if (auto *init = dyn_cast(used->getInitializer())) for (Value *v : init->operands()) list.push_back(cast(v)); used->eraseFromParent(); } for (GlobalValue *v : vals) list.push_back(v); auto *at = ArrayType::get(PointerType::get(C, 0), list.size()); auto *g = new GlobalVariable(Mod, at, false, GlobalValue::AppendingLinkage, ConstantArray::get(at, list), "llvm.used"); g->setSection("llvm.metadata"); } }; } // namespace extern "C" LLVM_ATTRIBUTE_WEAK PassPluginLibraryInfo llvmGetPassPluginInfo() { return {LLVM_PLUGIN_API_VERSION, "kwbridge", "1", [](PassBuilder &PB) { PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM, OptimizationLevel, ThinOrFullLTOPhase) { MPM.addPass(KWBridge()); }); }}; }