1 //===- llvm/unittest/IR/BasicBlockTest.cpp - BasicBlock unit tests --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/IR/BasicBlock.h" 11 #include "llvm/ADT/STLExtras.h" 12 #include "llvm/IR/Function.h" 13 #include "llvm/IR/IRBuilder.h" 14 #include "llvm/IR/LLVMContext.h" 15 #include "llvm/IR/Module.h" 16 #include "llvm/IR/NoFolder.h" 17 #include "gmock/gmock-matchers.h" 18 #include "gtest/gtest.h" 19 #include <memory> 20 21 namespace llvm { 22 namespace { 23 24 TEST(BasicBlockTest, PhiRange) { 25 LLVMContext Context; 26 27 // Create the main block. 28 std::unique_ptr<BasicBlock> BB(BasicBlock::Create(Context)); 29 30 // Create some predecessors of it. 31 std::unique_ptr<BasicBlock> BB1(BasicBlock::Create(Context)); 32 BranchInst::Create(BB.get(), BB1.get()); 33 std::unique_ptr<BasicBlock> BB2(BasicBlock::Create(Context)); 34 BranchInst::Create(BB.get(), BB2.get()); 35 36 // Make sure this doesn't crash if there are no phis. 37 for (auto &PN : BB->phis()) { 38 (void)PN; 39 EXPECT_TRUE(false) << "empty block should have no phis"; 40 } 41 42 // Make it a cycle. 43 auto *BI = BranchInst::Create(BB.get(), BB.get()); 44 45 // Now insert some PHI nodes. 46 auto *Int32Ty = Type::getInt32Ty(Context); 47 auto *P1 = PHINode::Create(Int32Ty, /*NumReservedValues*/ 3, "phi.1", BI); 48 auto *P2 = PHINode::Create(Int32Ty, /*NumReservedValues*/ 3, "phi.2", BI); 49 auto *P3 = PHINode::Create(Int32Ty, /*NumReservedValues*/ 3, "phi.3", BI); 50 51 // Some non-PHI nodes. 52 auto *Sum = BinaryOperator::CreateAdd(P1, P2, "sum", BI); 53 54 // Now wire up the incoming values that are interesting. 55 P1->addIncoming(P2, BB.get()); 56 P2->addIncoming(P1, BB.get()); 57 P3->addIncoming(Sum, BB.get()); 58 59 // Finally, let's iterate them, which is the thing we're trying to test. 60 // We'll use this to wire up the rest of the incoming values. 61 for (auto &PN : BB->phis()) { 62 PN.addIncoming(UndefValue::get(Int32Ty), BB1.get()); 63 PN.addIncoming(UndefValue::get(Int32Ty), BB2.get()); 64 } 65 66 // Test that we can use const iterators and generally that the iterators 67 // behave like iterators. 68 BasicBlock::const_phi_iterator CI; 69 CI = BB->phis().begin(); 70 EXPECT_NE(CI, BB->phis().end()); 71 72 // And iterate a const range. 73 for (const auto &PN : const_cast<const BasicBlock *>(BB.get())->phis()) { 74 EXPECT_EQ(BB.get(), PN.getIncomingBlock(0)); 75 EXPECT_EQ(BB1.get(), PN.getIncomingBlock(1)); 76 EXPECT_EQ(BB2.get(), PN.getIncomingBlock(2)); 77 } 78 } 79 80 } // End anonymous namespace. 81 } // End llvm namespace. 82