Arm Code Advisor insight: Cannot vectorize due to function call in loop

In this example, a loop cannot be vectorized because of a call to a function within the loop. In order to vectorize the code within a loop, the compiler must be able to prove that vectorization is safe. If the compiler cannot see the source code for a function, the compiler will not be able to vectorize loops containing calls to that function.

This situation can arise with calls to library functions.

Note:
Insights are only supported with Arm Compiler for HPC versions 18.4.2 and earlier.

Insight example

This example contains a loop which calls the function pow in the math library. Because the compiler cannot see the source code for this library, the loop cannot be vectorized.

#include <math.h>

#define ARRAY_SIZE 3000

void pow5(double *res, int n);

int main() {
  double res[ARRAY_SIZE];
  for (int j = 0; j < ARRAY_SIZE; j++) {
    res[j] = j;
  }

  for (int i = 0; i < 10000; i++) {
    pow5(res, ARRAY_SIZE);
  }

  return 0;
}

void pow5(double *res, int n) {
  for (int i = 0; i < n; i++) {
    res[i] = pow(res[i], 5);
  }
}

Solution description

A solution to this problem is to ensure that the compiler can see the source for all code within vectorizable loops.

In the example solution below, the pow function call has been replaced with a direct calculation.

Solution example

void pow5(double *res, int n) {
  for (int i = 0; i < n; i++) {
    res[i] = res[i] * res[i] * res[i] * res[i] * res[i];
  }
}

Related Information