Skip to content

Commit b22c3c1

Browse files
authored
Register callbacks in Region for instruction creation/deletion. (#117088)
This will keep the current Region updated when region passes add/delete instructions.
1 parent cec5296 commit b22c3c1

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

llvm/include/llvm/SandboxIR/Region.h

+5
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ class Region {
6363

6464
Context &Ctx;
6565

66+
/// ID (for later deregistration) of the "create instruction" callback.
67+
Context::CallbackID CreateInstCB;
68+
/// ID (for later deregistration) of the "erase instruction" callback.
69+
Context::CallbackID EraseInstCB;
70+
6671
// TODO: Add cost modeling.
6772
// TODO: Add a way to encode/decode region info to/from metadata.
6873

llvm/lib/SandboxIR/Region.cpp

+9-1
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,17 @@ Region::Region(Context &Ctx) : Ctx(Ctx) {
1515
LLVMContext &LLVMCtx = Ctx.LLVMCtx;
1616
auto *RegionStrMD = MDString::get(LLVMCtx, RegionStr);
1717
RegionMDN = MDNode::getDistinct(LLVMCtx, {RegionStrMD});
18+
19+
CreateInstCB = Ctx.registerCreateInstrCallback(
20+
[this](Instruction *NewInst) { add(NewInst); });
21+
EraseInstCB = Ctx.registerEraseInstrCallback(
22+
[this](Instruction *ErasedInst) { remove(ErasedInst); });
1823
}
1924

20-
Region::~Region() {}
25+
Region::~Region() {
26+
Ctx.unregisterCreateInstrCallback(CreateInstCB);
27+
Ctx.unregisterEraseInstrCallback(EraseInstCB);
28+
}
2129

2230
void Region::add(Instruction *I) {
2331
Insts.insert(I);

llvm/unittests/SandboxIR/RegionTest.cpp

+31
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,37 @@ define i8 @foo(i8 %v0, i8 %v1) {
8181
#endif
8282
}
8383

84+
TEST_F(RegionTest, CallbackUpdates) {
85+
parseIR(C, R"IR(
86+
define i8 @foo(i8 %v0, i8 %v1, ptr %ptr) {
87+
%t0 = add i8 %v0, 1
88+
%t1 = add i8 %t0, %v1
89+
ret i8 %t0
90+
}
91+
)IR");
92+
llvm::Function *LLVMF = &*M->getFunction("foo");
93+
sandboxir::Context Ctx(C);
94+
auto *F = Ctx.createFunction(LLVMF);
95+
auto *Ptr = F->getArg(2);
96+
auto *BB = &*F->begin();
97+
auto It = BB->begin();
98+
auto *T0 = cast<sandboxir::Instruction>(&*It++);
99+
auto *T1 = cast<sandboxir::Instruction>(&*It++);
100+
auto *Ret = cast<sandboxir::Instruction>(&*It++);
101+
sandboxir::Region Rgn(Ctx);
102+
Rgn.add(T0);
103+
Rgn.add(T1);
104+
105+
// Test creation.
106+
auto *NewI = sandboxir::StoreInst::create(T0, Ptr, /*Align=*/std::nullopt,
107+
Ret->getIterator(), Ctx);
108+
EXPECT_THAT(Rgn.insts(), testing::ElementsAre(T0, T1, NewI));
109+
110+
// Test deletion.
111+
T1->eraseFromParent();
112+
EXPECT_THAT(Rgn.insts(), testing::ElementsAre(T0, NewI));
113+
}
114+
84115
TEST_F(RegionTest, MetadataFromIR) {
85116
parseIR(C, R"IR(
86117
define i8 @foo(i8 %v0, i8 %v1) {

0 commit comments

Comments
 (0)