Maciej Ziarko
Maciej Ziarko

Reputation: 12094

Basic block coverage - what's the precise definition?

Let's say I have this piece of C/C++ code:

int c = 12; // Should I count this line as basic block?
if (a != 0 && b > 10) {
    c += (a + b);
} else {
    c += 1;
}
printf("%d", c); // Should I count this line as basic block?

What is the basic block coverage for test case a = 1, b = 12?

Is it 75% or 50%?

Should I count 1st and last lines as basic blocks? What is the precise definition of basic block?

Another point of confusion:

int c = 16;
d += c;

Is it one basic block or 2 basic blocks? Should every line be counted as a basic block?

Upvotes: 6

Views: 2923

Answers (1)

Mihai Maruseac
Mihai Maruseac

Reputation: 21460

A basic block contains all instructions which have the property that if one of them is executed then all of the others in the same basic block are. Naming the first instruction of the basic block a leader we get to the following definition of a basic block: the set of all instructions following a leader which get executed if the leader is executed. The leader is the start of the basic block.

To determine the leader find all jump instructions in your code. Each jump target and each instruction after a jump is a leader. The first instruction in a method is also a leader.

To find the basic blocks simply go through all instructions from a leader to the next.

Your first example:

int c = 12; // Leader
if (a != 0 && b > 10) { // Jump
    c += (a + b); // Leader
} else {
    c += 1; // Leader
}
printf("%d", c); // Leader -- target of jump from the end of the true branch

You have 4 basic blocks there: one for each branch of the if, one for the printf after the if and one for the initialization of c. If a == 1 && b == 12 only three basic blocks are executed thus coverage is 75%.

Your second example has no jump instruction => there is only one basic block.

Upvotes: 7

Related Questions