1 //===- BlockFrequencyInfoTest.cpp - BlockFrequencyInfo 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/Analysis/BlockFrequencyInfo.h"
11 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
12 #include "llvm/Analysis/BranchProbabilityInfo.h"
13 #include "llvm/Analysis/LoopInfo.h"
14 #include "llvm/AsmParser/Parser.h"
15 #include "llvm/IR/BasicBlock.h"
16 #include "llvm/IR/Dominators.h"
17 #include "llvm/IR/Function.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/DataTypes.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "gtest/gtest.h"
24
25 namespace llvm {
26 namespace {
27
28 class BlockFrequencyInfoTest : public testing::Test {
29 protected:
30 std::unique_ptr<BranchProbabilityInfo> BPI;
31 std::unique_ptr<DominatorTree> DT;
32 std::unique_ptr<LoopInfo> LI;
33 LLVMContext C;
34
buildBFI(Function & F)35 BlockFrequencyInfo buildBFI(Function &F) {
36 DT.reset(new DominatorTree(F));
37 LI.reset(new LoopInfo(*DT));
38 BPI.reset(new BranchProbabilityInfo(F, *LI));
39 return BlockFrequencyInfo(F, *BPI, *LI);
40 }
makeLLVMModule()41 std::unique_ptr<Module> makeLLVMModule() {
42 const char *ModuleStrig = "define i32 @f(i32 %x) {\n"
43 "bb0:\n"
44 " %y1 = icmp eq i32 %x, 0 \n"
45 " br i1 %y1, label %bb1, label %bb2 \n"
46 "bb1:\n"
47 " br label %bb3\n"
48 "bb2:\n"
49 " br label %bb3\n"
50 "bb3:\n"
51 " %y2 = phi i32 [0, %bb1], [1, %bb2] \n"
52 " ret i32 %y2\n"
53 "}\n";
54 SMDiagnostic Err;
55 return parseAssemblyString(ModuleStrig, Err, C);
56 }
57 };
58
TEST_F(BlockFrequencyInfoTest,Basic)59 TEST_F(BlockFrequencyInfoTest, Basic) {
60 auto M = makeLLVMModule();
61 Function *F = M->getFunction("f");
62 F->setEntryCount(100);
63
64 BlockFrequencyInfo BFI = buildBFI(*F);
65 BasicBlock &BB0 = F->getEntryBlock();
66 BasicBlock *BB1 = BB0.getTerminator()->getSuccessor(0);
67 BasicBlock *BB2 = BB0.getTerminator()->getSuccessor(1);
68 BasicBlock *BB3 = BB1->getSingleSuccessor();
69
70 uint64_t BB0Freq = BFI.getBlockFreq(&BB0).getFrequency();
71 uint64_t BB1Freq = BFI.getBlockFreq(BB1).getFrequency();
72 uint64_t BB2Freq = BFI.getBlockFreq(BB2).getFrequency();
73 uint64_t BB3Freq = BFI.getBlockFreq(BB3).getFrequency();
74
75 EXPECT_EQ(BB0Freq, BB3Freq);
76 EXPECT_EQ(BB0Freq, BB1Freq + BB2Freq);
77 EXPECT_EQ(BB0Freq, BB3Freq);
78
79 EXPECT_EQ(BFI.getBlockProfileCount(&BB0).getValue(), UINT64_C(100));
80 EXPECT_EQ(BFI.getBlockProfileCount(BB3).getValue(), UINT64_C(100));
81 EXPECT_EQ(BFI.getBlockProfileCount(BB1).getValue(), 100 * BB1Freq / BB0Freq);
82 EXPECT_EQ(BFI.getBlockProfileCount(BB2).getValue(), 100 * BB2Freq / BB0Freq);
83 }
84
85 } // end anonymous namespace
86 } // end namespace llvm
87