Thanks very much!
Dongyan Chen
在 2025/6/17 15:34, Yangyu Chen 写道:
On 17/6/2025 12:08, Dongyan Chen wrote:
Hi, I've come across a question regarding the branch cost of gcc. In
the link
https://gcc.godbolt.org/z/hnddevd5h, gcc fails to recognize the
optimization
branch judgment, while llvm does. I eventually discovered that the
value of the branch
cost was too small. Moreover, in that link, if I add
"-mbranch-cost=4" (a larger
number can also be used) for gcc, the zicond extension functions
properly. So, is
it necessary to modify the branch cost for gcc? According to the
source code, the
default mtun is rocket, which has a branch cost of 3. I think it
should be set to 4.
Nice catch!
I've tested your testcase on Spacemit K1, and it shows a 1.48x speedup
using zicond!
Here are the results:
➜ ~ cat 2.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 100000000
int condition_reduction (int *a, int min_v);
int a[N];
int main() {
for (int i=0;i<N;i++) a[i] = rand();
clock_t start, stop;
start = clock();
condition_reduction(a, RAND_MAX / 2);
stop = clock();
printf("time: %0.3f\n", (double)(stop - start) / CLOCKS_PER_SEC);
return 0;
}
➜ ~ cat 3.c
#define N 100000000
int condition_reduction (int *a, int min_v)
{
int last = 0;
for (int i = 0; i < N; i++)
{
if (a[i] < min_v)
last = a[i];
}
return last;
}
➜ ~ gcc 2.c 3.c -O3 -march=rv64gc_zicond -mbranch-cost=4
➜ ~ ./a.out
time: 0.340
➜ ~ ./a.out
time: 0.340
➜ ~ gcc 2.c 3.c -O3 -march=rv64gc_zicond -mbranch-cost=3
➜ ~ ./a.out
time: 0.503
➜ ~ ./a.out
time: 0.502
➜ ~
Thanks,
Yangyu Chen