Skip to content

Commit

Permalink
[IR] Adds Function::erase() for erasing a range of basic blocks
Browse files Browse the repository at this point in the history
This is part of a series of patches that aim at making Function::getBasicBlockList() private.

Differential Revision: https://reviews.llvm.org/D140064
  • Loading branch information
vporpo committed Dec 15, 2022
1 parent bfdc1a7 commit c2355b3
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
4 changes: 4 additions & 0 deletions llvm/include/llvm/IR/Function.h
Expand Up @@ -715,6 +715,10 @@ class LLVM_EXTERNAL_VISIBILITY Function : public GlobalObject,
Function::iterator FromBeginIt,
Function::iterator FromEndIt);

/// Erases a range of BasicBlocks from \p FromIt to (not including) \p ToIt.
/// \Returns \p ToIt.
Function::iterator erase(Function::iterator FromIt, Function::iterator ToIt);

/// Get the underlying elements of the Function... the basic block list is
/// empty for external functions.
///
Expand Down
5 changes: 5 additions & 0 deletions llvm/lib/IR/Function.cpp
Expand Up @@ -380,6 +380,11 @@ void Function::splice(Function::iterator ToIt, Function *FromF,
BasicBlocks.splice(ToIt, FromF->BasicBlocks, FromBeginIt, FromEndIt);
}

Function::iterator Function::erase(Function::iterator FromIt,
Function::iterator ToIt) {
return BasicBlocks.erase(FromIt, ToIt);
}

//===----------------------------------------------------------------------===//
// Function Implementation
//===----------------------------------------------------------------------===//
Expand Down
43 changes: 43 additions & 0 deletions llvm/unittests/IR/FunctionTest.cpp
Expand Up @@ -443,4 +443,47 @@ TEST(FunctionTest, SpliceEndBeforeBegin) {
"FromBeginIt not before FromEndIt!");
}
#endif //EXPENSIVE_CHECKS

TEST(FunctionTest, EraseBBs) {
LLVMContext Ctx;
std::unique_ptr<Module> M = parseIR(Ctx, R"(
define void @foo() {
bb1:
br label %bb2
bb2:
br label %bb3
bb3:
br label %bb4
bb4:
br label %bb5
bb5:
ret void
}
)");

Function *F = M->getFunction("foo");
BasicBlock *BB1 = getBBWithName(F, "bb1");
BasicBlock *BB2 = getBBWithName(F, "bb2");
BasicBlock *BB3 = getBBWithName(F, "bb3");
BasicBlock *BB4 = getBBWithName(F, "bb4");
BasicBlock *BB5 = getBBWithName(F, "bb5");
EXPECT_EQ(F->size(), 5u);

// Erase BB2.
BB1->getTerminator()->eraseFromParent();
auto It = F->erase(BB2->getIterator(), std::next(BB2->getIterator()));
EXPECT_EQ(F->size(), 4u);
// Check that the iterator returned matches the node after the erased one.
EXPECT_EQ(It, BB3->getIterator());

It = F->begin();
EXPECT_EQ(&*It++, BB1);
EXPECT_EQ(&*It++, BB3);
EXPECT_EQ(&*It++, BB4);
EXPECT_EQ(&*It++, BB5);

// Erase all BBs.
It = F->erase(F->begin(), F->end());
EXPECT_EQ(F->size(), 0u);
}
} // end namespace

0 comments on commit c2355b3

Please sign in to comment.