1 //===- llvm/unittest/IR/BasicBlockTest.cpp - BasicBlock unit tests --------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/IR/BasicBlock.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/AsmParser/Parser.h"
12 #include "llvm/IR/Function.h"
13 #include "llvm/IR/IRBuilder.h"
14 #include "llvm/IR/Instructions.h"
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/IR/NoFolder.h"
18 #include "llvm/IR/Verifier.h"
19 #include "llvm/Support/SourceMgr.h"
20 #include "gmock/gmock-matchers.h"
21 #include "gtest/gtest.h"
22 #include <memory>
23 
24 namespace llvm {
25 namespace {
26 
TEST(BasicBlockTest,PhiRange)27 TEST(BasicBlockTest, PhiRange) {
28   LLVMContext Context;
29 
30   // Create the main block.
31   std::unique_ptr<BasicBlock> BB(BasicBlock::Create(Context));
32 
33   // Create some predecessors of it.
34   std::unique_ptr<BasicBlock> BB1(BasicBlock::Create(Context));
35   BranchInst::Create(BB.get(), BB1.get());
36   std::unique_ptr<BasicBlock> BB2(BasicBlock::Create(Context));
37   BranchInst::Create(BB.get(), BB2.get());
38 
39   // Make sure this doesn't crash if there are no phis.
40   int PhiCount = 0;
41   for (auto &PN : BB->phis()) {
42     (void)PN;
43     PhiCount++;
44   }
45   ASSERT_EQ(PhiCount, 0) << "empty block should have no phis";
46 
47   // Make it a cycle.
48   auto *BI = BranchInst::Create(BB.get(), BB.get());
49 
50   // Now insert some PHI nodes.
51   auto *Int32Ty = Type::getInt32Ty(Context);
52   auto *P1 = PHINode::Create(Int32Ty, /*NumReservedValues*/ 3, "phi.1", BI);
53   auto *P2 = PHINode::Create(Int32Ty, /*NumReservedValues*/ 3, "phi.2", BI);
54   auto *P3 = PHINode::Create(Int32Ty, /*NumReservedValues*/ 3, "phi.3", BI);
55 
56   // Some non-PHI nodes.
57   auto *Sum = BinaryOperator::CreateAdd(P1, P2, "sum", BI);
58 
59   // Now wire up the incoming values that are interesting.
60   P1->addIncoming(P2, BB.get());
61   P2->addIncoming(P1, BB.get());
62   P3->addIncoming(Sum, BB.get());
63 
64   // Finally, let's iterate them, which is the thing we're trying to test.
65   // We'll use this to wire up the rest of the incoming values.
66   for (auto &PN : BB->phis()) {
67     PN.addIncoming(UndefValue::get(Int32Ty), BB1.get());
68     PN.addIncoming(UndefValue::get(Int32Ty), BB2.get());
69   }
70 
71   // Test that we can use const iterators and generally that the iterators
72   // behave like iterators.
73   BasicBlock::const_phi_iterator CI;
74   CI = BB->phis().begin();
75   EXPECT_NE(CI, BB->phis().end());
76 
77   // Test that filtering iterators work with basic blocks.
78   auto isPhi = [](Instruction &I) { return isa<PHINode>(&I); };
79   auto Phis = make_filter_range(*BB, isPhi);
80   auto ReversedPhis = reverse(make_filter_range(*BB, isPhi));
81   EXPECT_EQ(std::distance(Phis.begin(), Phis.end()), 3);
82   EXPECT_EQ(&*Phis.begin(), P1);
83   EXPECT_EQ(std::distance(ReversedPhis.begin(), ReversedPhis.end()), 3);
84   EXPECT_EQ(&*ReversedPhis.begin(), P3);
85 
86   // And iterate a const range.
87   for (const auto &PN : const_cast<const BasicBlock *>(BB.get())->phis()) {
88     EXPECT_EQ(BB.get(), PN.getIncomingBlock(0));
89     EXPECT_EQ(BB1.get(), PN.getIncomingBlock(1));
90     EXPECT_EQ(BB2.get(), PN.getIncomingBlock(2));
91   }
92 }
93 
94 #define CHECK_ITERATORS(Range1, Range2)                                        \
95   EXPECT_EQ(std::distance(Range1.begin(), Range1.end()),                       \
96             std::distance(Range2.begin(), Range2.end()));                      \
97   for (auto Pair : zip(Range1, Range2))                                        \
98     EXPECT_EQ(&std::get<0>(Pair), std::get<1>(Pair));
99 
TEST(BasicBlockTest,TestInstructionsWithoutDebug)100 TEST(BasicBlockTest, TestInstructionsWithoutDebug) {
101   LLVMContext Ctx;
102 
103   Module *M = new Module("MyModule", Ctx);
104   Type *ArgTy1[] = {Type::getInt32PtrTy(Ctx)};
105   FunctionType *FT = FunctionType::get(Type::getVoidTy(Ctx), ArgTy1, false);
106   Argument *V = new Argument(Type::getInt32Ty(Ctx));
107   Function *F = Function::Create(FT, Function::ExternalLinkage, "", M);
108 
109   Function *DbgAddr = Intrinsic::getDeclaration(M, Intrinsic::dbg_addr);
110   Function *DbgDeclare = Intrinsic::getDeclaration(M, Intrinsic::dbg_declare);
111   Function *DbgValue = Intrinsic::getDeclaration(M, Intrinsic::dbg_value);
112   Value *DIV = MetadataAsValue::get(Ctx, (Metadata *)nullptr);
113   SmallVector<Value *, 3> Args = {DIV, DIV, DIV};
114 
115   BasicBlock *BB1 = BasicBlock::Create(Ctx, "", F);
116   const BasicBlock *BBConst = BB1;
117   IRBuilder<> Builder1(BB1);
118 
119   AllocaInst *Var = Builder1.CreateAlloca(Builder1.getInt8Ty());
120   Builder1.CreateCall(DbgValue, Args);
121   Instruction *AddInst = cast<Instruction>(Builder1.CreateAdd(V, V));
122   Instruction *MulInst = cast<Instruction>(Builder1.CreateMul(AddInst, V));
123   Builder1.CreateCall(DbgDeclare, Args);
124   Instruction *SubInst = cast<Instruction>(Builder1.CreateSub(MulInst, V));
125   Builder1.CreateCall(DbgAddr, Args);
126 
127   SmallVector<Instruction *, 4> Exp = {Var, AddInst, MulInst, SubInst};
128   CHECK_ITERATORS(BB1->instructionsWithoutDebug(), Exp);
129   CHECK_ITERATORS(BBConst->instructionsWithoutDebug(), Exp);
130 
131   EXPECT_EQ(static_cast<size_t>(BB1->sizeWithoutDebug()), Exp.size());
132   EXPECT_EQ(static_cast<size_t>(BBConst->sizeWithoutDebug()), Exp.size());
133 
134   delete M;
135   delete V;
136 }
137 
TEST(BasicBlockTest,ComesBefore)138 TEST(BasicBlockTest, ComesBefore) {
139   const char *ModuleString = R"(define i32 @f(i32 %x) {
140                                   %add = add i32 %x, 42
141                                   ret i32 %add
142                                 })";
143   LLVMContext Ctx;
144   SMDiagnostic Err;
145   auto M = parseAssemblyString(ModuleString, Err, Ctx);
146   ASSERT_TRUE(M.get());
147 
148   Function *F = M->getFunction("f");
149   BasicBlock &BB = F->front();
150   BasicBlock::iterator I = BB.begin();
151   Instruction *Add = &*I++;
152   Instruction *Ret = &*I++;
153 
154   // Intentionally duplicated to verify cached and uncached are the same.
155   EXPECT_FALSE(BB.isInstrOrderValid());
156   EXPECT_FALSE(Add->comesBefore(Add));
157   EXPECT_TRUE(BB.isInstrOrderValid());
158   EXPECT_FALSE(Add->comesBefore(Add));
159   BB.invalidateOrders();
160   EXPECT_FALSE(BB.isInstrOrderValid());
161   EXPECT_TRUE(Add->comesBefore(Ret));
162   EXPECT_TRUE(BB.isInstrOrderValid());
163   EXPECT_TRUE(Add->comesBefore(Ret));
164   BB.invalidateOrders();
165   EXPECT_FALSE(Ret->comesBefore(Add));
166   EXPECT_FALSE(Ret->comesBefore(Add));
167   BB.invalidateOrders();
168   EXPECT_FALSE(Ret->comesBefore(Ret));
169   EXPECT_FALSE(Ret->comesBefore(Ret));
170 }
171 
TEST(BasicBlockTest,EmptyPhi)172 TEST(BasicBlockTest, EmptyPhi) {
173   LLVMContext Ctx;
174 
175   Module *M = new Module("MyModule", Ctx);
176   FunctionType *FT = FunctionType::get(Type::getVoidTy(Ctx), {}, false);
177   Function *F = Function::Create(FT, Function::ExternalLinkage, "", M);
178 
179   BasicBlock *BB1 = BasicBlock::Create(Ctx, "", F);
180   ReturnInst::Create(Ctx, BB1);
181 
182   Type *Ty = Type::getInt32PtrTy(Ctx);
183   BasicBlock *BB2 = BasicBlock::Create(Ctx, "", F);
184   PHINode::Create(Ty, 0, "", BB2);
185   ReturnInst::Create(Ctx, BB2);
186   EXPECT_FALSE(verifyModule(*M, &errs()));
187 }
188 
189 class InstrOrderInvalidationTest : public ::testing::Test {
190 protected:
SetUp()191   void SetUp() override {
192     M.reset(new Module("MyModule", Ctx));
193     Nop = Intrinsic::getDeclaration(M.get(), Intrinsic::donothing);
194     FunctionType *FT = FunctionType::get(Type::getVoidTy(Ctx), {}, false);
195     Function *F = Function::Create(FT, Function::ExternalLinkage, "foo", *M);
196     BB = BasicBlock::Create(Ctx, "entry", F);
197 
198     IRBuilder<> Builder(BB);
199     I1 = Builder.CreateCall(Nop);
200     I2 = Builder.CreateCall(Nop);
201     I3 = Builder.CreateCall(Nop);
202     Ret = Builder.CreateRetVoid();
203   }
204 
205   LLVMContext Ctx;
206   std::unique_ptr<Module> M;
207   Function *Nop = nullptr;
208   BasicBlock *BB = nullptr;
209   Instruction *I1 = nullptr;
210   Instruction *I2 = nullptr;
211   Instruction *I3 = nullptr;
212   Instruction *Ret = nullptr;
213 };
214 
TEST_F(InstrOrderInvalidationTest,InsertInvalidation)215 TEST_F(InstrOrderInvalidationTest, InsertInvalidation) {
216   EXPECT_FALSE(BB->isInstrOrderValid());
217   EXPECT_TRUE(I1->comesBefore(I2));
218   EXPECT_TRUE(BB->isInstrOrderValid());
219   EXPECT_TRUE(I2->comesBefore(I3));
220   EXPECT_TRUE(I3->comesBefore(Ret));
221   EXPECT_TRUE(BB->isInstrOrderValid());
222 
223   // Invalidate orders.
224   IRBuilder<> Builder(BB, I2->getIterator());
225   Instruction *I1a = Builder.CreateCall(Nop);
226   EXPECT_FALSE(BB->isInstrOrderValid());
227   EXPECT_TRUE(I1->comesBefore(I1a));
228   EXPECT_TRUE(BB->isInstrOrderValid());
229   EXPECT_TRUE(I1a->comesBefore(I2));
230   EXPECT_TRUE(I2->comesBefore(I3));
231   EXPECT_TRUE(I3->comesBefore(Ret));
232   EXPECT_TRUE(BB->isInstrOrderValid());
233 }
234 
TEST_F(InstrOrderInvalidationTest,SpliceInvalidation)235 TEST_F(InstrOrderInvalidationTest, SpliceInvalidation) {
236   EXPECT_TRUE(I1->comesBefore(I2));
237   EXPECT_TRUE(I2->comesBefore(I3));
238   EXPECT_TRUE(I3->comesBefore(Ret));
239   EXPECT_TRUE(BB->isInstrOrderValid());
240 
241   // Use Instruction::moveBefore, which uses splice.
242   I2->moveBefore(I1);
243   EXPECT_FALSE(BB->isInstrOrderValid());
244 
245   EXPECT_TRUE(I2->comesBefore(I1));
246   EXPECT_TRUE(I1->comesBefore(I3));
247   EXPECT_TRUE(I3->comesBefore(Ret));
248   EXPECT_TRUE(BB->isInstrOrderValid());
249 }
250 
TEST_F(InstrOrderInvalidationTest,RemoveNoInvalidation)251 TEST_F(InstrOrderInvalidationTest, RemoveNoInvalidation) {
252   // Cache the instruction order.
253   EXPECT_FALSE(BB->isInstrOrderValid());
254   EXPECT_TRUE(I1->comesBefore(I2));
255   EXPECT_TRUE(BB->isInstrOrderValid());
256 
257   // Removing does not invalidate instruction order.
258   I2->removeFromParent();
259   I2->deleteValue();
260   I2 = nullptr;
261   EXPECT_TRUE(BB->isInstrOrderValid());
262   EXPECT_TRUE(I1->comesBefore(I3));
263   EXPECT_EQ(std::next(I1->getIterator()), I3->getIterator());
264 }
265 
TEST_F(InstrOrderInvalidationTest,EraseNoInvalidation)266 TEST_F(InstrOrderInvalidationTest, EraseNoInvalidation) {
267   // Cache the instruction order.
268   EXPECT_FALSE(BB->isInstrOrderValid());
269   EXPECT_TRUE(I1->comesBefore(I2));
270   EXPECT_TRUE(BB->isInstrOrderValid());
271 
272   // Removing does not invalidate instruction order.
273   I2->eraseFromParent();
274   I2 = nullptr;
275   EXPECT_TRUE(BB->isInstrOrderValid());
276   EXPECT_TRUE(I1->comesBefore(I3));
277   EXPECT_EQ(std::next(I1->getIterator()), I3->getIterator());
278 }
279 
280 } // End anonymous namespace.
281 } // End llvm namespace.
282