When compiling C to LLVM IR, how to lift an inline Bitcast of a function call to a global variable into the body of the caller function?

Viewed 243

I'm trying to understand why Clang compiles a function parameter, which is a global variable, into an inline Bitcast instruction. Is there a way to lift this inline instruction from the function call to the body of the caller function?

Here is my sample program that I used Clang (versions 6 and 8) to compile the following C to LLVM IR.

# File name: global-test.c

#include <stdio.h>
#include <stdlib.h>

int a = 10;
int* b = &a;

void foo(void* a, void* b) {
  return;
}

int main() {
  foo(b, &a);             // the first call to foo
  int* c = &a;
  foo(b, c);              // the second call to foo
  return 1;
}

Here are my compilation commands:

clang -c global-test.c -emit-llvm
llvm-dis global-test.bc

And here is the compiled LLVM Bitcode of the main function:

define dso_local i32 @main() #0 {
  %1 = alloca i32, align 4
  %2 = alloca i32*, align 8
  store i32 0, i32* %1, align 4
  %3 = load i32*, i32** @b, align 8
  %4 = bitcast i32* %3 to i8*
  call void @foo(i8* %4, i8* bitcast (i32* @a to i8*))   // the first call to foo
  store i32* @a, i32** %2, align 8
  %5 = load i32*, i32** @b, align 8
  %6 = bitcast i32* %5 to i8*
  %7 = load i32*, i32** %2, align 8
  %8 = bitcast i32* %7 to i8*
  call void @foo(i8* %6, i8* %8)                         // the second call to foo
  ret i32 1
}

In the first call to foo above, the global parameter &a is compiled into an inline Bitcast inside the function call.

Is there any option of Clang that can lift it up to the body the main function, similar to the second call to foo?

Thank you for spending time to take a look at my question.

0 Answers
Related