1 //===- BasicBlockUtils.cpp - Unit tests for BasicBlockUtils ---------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
10 #include "llvm/Analysis/PostDominators.h"
11 #include "llvm/AsmParser/Parser.h"
12 #include "llvm/IR/BasicBlock.h"
13 #include "llvm/IR/Dominators.h"
14 #include "llvm/IR/LLVMContext.h"
15 #include "llvm/Support/SourceMgr.h"
16 #include "gtest/gtest.h"
20 static std::unique_ptr
<Module
> parseIR(LLVMContext
&C
, const char *IR
) {
22 std::unique_ptr
<Module
> Mod
= parseAssemblyString(IR
, Err
, C
);
24 Err
.print("BasicBlockUtilsTests", errs());
28 TEST(BasicBlockUtils
, EliminateUnreachableBlocks
) {
31 std::unique_ptr
<Module
> M
= parseIR(
33 "define i32 @has_unreachable(i1 %cond) {\n"
35 " br i1 %cond, label %bb0, label %bb1\n"
39 " %phi = phi i32 [ 0, %entry ], [ 1, %bb0 ]"
47 auto *F
= M
->getFunction("has_unreachable");
49 DomTreeUpdater
DTU(DT
, DomTreeUpdater::UpdateStrategy::Eager
);
51 EXPECT_EQ(F
->size(), (size_t)4);
52 bool Result
= EliminateUnreachableBlocks(*F
, &DTU
);
54 EXPECT_EQ(F
->size(), (size_t)3);
55 EXPECT_TRUE(DT
.verify());
58 TEST(BasicBlockUtils
, NoUnreachableBlocksToEliminate
) {
61 std::unique_ptr
<Module
> M
= parseIR(
63 "define i32 @no_unreachable(i1 %cond) {\n"
65 " br i1 %cond, label %bb0, label %bb1\n"
69 " %phi = phi i32 [ 0, %entry ], [ 1, %bb0 ]"
75 auto *F
= M
->getFunction("no_unreachable");
77 DomTreeUpdater
DTU(DT
, DomTreeUpdater::UpdateStrategy::Eager
);
79 EXPECT_EQ(F
->size(), (size_t)3);
80 bool Result
= EliminateUnreachableBlocks(*F
, &DTU
);
82 EXPECT_EQ(F
->size(), (size_t)3);
83 EXPECT_TRUE(DT
.verify());
86 TEST(BasicBlockUtils
, SplitBlockPredecessors
) {
89 std::unique_ptr
<Module
> M
= parseIR(
91 "define i32 @basic_func(i1 %cond) {\n"
93 " br i1 %cond, label %bb0, label %bb1\n"
97 " %phi = phi i32 [ 0, %entry ], [ 1, %bb0 ]"
103 auto *F
= M
->getFunction("basic_func");
104 DominatorTree
DT(*F
);
106 // Make sure the dominator tree is properly updated if calling this on the
108 SplitBlockPredecessors(&F
->getEntryBlock(), {}, "split.entry", &DT
);
109 EXPECT_TRUE(DT
.verify());
112 TEST(BasicBlockUtils
, SplitCriticalEdge
) {
115 std::unique_ptr
<Module
> M
= parseIR(
117 "define void @crit_edge(i1 %cond0, i1 %cond1) {\n"
119 " br i1 %cond0, label %bb0, label %bb1\n"
130 auto *F
= M
->getFunction("crit_edge");
131 DominatorTree
DT(*F
);
132 PostDominatorTree
PDT(*F
);
134 CriticalEdgeSplittingOptions
CESO(&DT
, nullptr, nullptr, &PDT
);
135 EXPECT_EQ(1u, SplitAllCriticalEdges(*F
, CESO
));
136 EXPECT_TRUE(DT
.verify());
137 EXPECT_TRUE(PDT
.verify());