Skip to content

Commit 5efb1ee

Browse files
committed
[BasicBlockUtils] Add BasicBlock printer (#163066)
1 parent a0a9d0c commit 5efb1ee

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -612,6 +612,8 @@ LLVM_ABI void InvertBranch(BranchInst *PBI, IRBuilderBase &Builder);
612612
// br/brcond/unreachable/ret
613613
LLVM_ABI bool hasOnlySimpleTerminator(const Function &F);
614614

615+
/// Print BasicBlock \p BB as an operand or print "<nullptr>" if \p BB is a
616+
/// nullptr.
615617
LLVM_ABI Printable printBasicBlock(const BasicBlock *BB);
616618

617619
} // end namespace llvm

llvm/lib/Transforms/Utils/BasicBlockUtils.cpp

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1778,7 +1778,10 @@ bool llvm::hasOnlySimpleTerminator(const Function &F) {
17781778

17791779
Printable llvm::printBasicBlock(const BasicBlock *BB) {
17801780
return Printable([BB](raw_ostream &OS) {
1781-
if (BB)
1782-
return BB->printAsOperand(OS);
1781+
if (!BB) {
1782+
OS << "<nullptr>";
1783+
return;
1784+
}
1785+
BB->printAsOperand(OS);
17831786
});
17841787
}

llvm/unittests/Transforms/Utils/BasicBlockUtilsTest.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -716,3 +716,32 @@ attributes #0 = { presplitcoroutine }
716716
EXPECT_FALSE(llvm::isPresplitCoroSuspendExitEdge(
717717
*ExitN.getSinglePredecessor(), ExitN));
718718
}
719+
720+
TEST(BasicBlockUtils, BasicBlockPrintable) {
721+
std::string S;
722+
std::string SCheck;
723+
llvm::raw_string_ostream OS{S};
724+
llvm::raw_string_ostream OSCheck{SCheck};
725+
726+
LLVMContext C;
727+
std::unique_ptr<Module> M = parseIR(C, R"IR(
728+
define void @foo() {
729+
br label %bb0
730+
bb0:
731+
br label %.exit
732+
.exit:
733+
ret void
734+
}
735+
)IR");
736+
737+
Function *F = M->getFunction("foo");
738+
for (const BasicBlock &BB : *F) {
739+
OS << printBasicBlock(&BB);
740+
BB.printAsOperand(OSCheck);
741+
EXPECT_EQ(OS.str(), OSCheck.str());
742+
S.clear();
743+
SCheck.clear();
744+
}
745+
OS << printBasicBlock(nullptr);
746+
EXPECT_EQ(OS.str(), "<nullptr>");
747+
}

0 commit comments

Comments
 (0)