LLVMBuildPhi() circular dependency problem

I’m having a circular dependency problem with LLVMBuildPhi.

The short explanation:

The compiler is complaining when I build the LLVMValueRef array for LLVMAddIncoming that one of the values is undefined, because it’s actually assigned later in the basic block.

The long explanation:

I have a loop init basic block which contains:

// Initialize loop counter
counter_init = LLVMConstInt(LLVMInt64Type(), count, 0);

The loop body basic block contains:

// Set the counter
sprintf(tmp_name, “tmp%d”, *tmp_num++);
counter = LLVMBuildPhi(builder, LLVMInt64Type(), tmp_name);
phi_values[0] = counter_init;
phi_values[1] = counter_next;
phi_basic_blocks[0] = loop_init;
phi_basic_blocks[1] = loop_body;
LLVMAddIncoming(data3_pntr, phi_values, phi_basic_blocks, 2);

// Decrement the counter
sprintf(tmp_name, “tmp%d”, *tmp_num++);
counter_next = LLVMBuildAdd(builder, counter, LLVMConstInt(LLVMInt64Type(), -1, 1), tmp_name);

When this code is compiled, a warning is issued:

capi_test.c:1520:16: error: ‘counter_next’ is used uninitialized in this function [-Werror=uninitialized]
phi_values[1] = counter_next;

What is the correct way to break this circular dependency?

Toshi

I wrote earlier:

I’m having a circular dependency problem with LLVMBuildPhi.

The short explanation:

The compiler is complaining when I build the LLVMValueRef array for
LLVMAddIncoming that one of the values is undefined, because it’s actually assigned
later in the basic block.

I think I just realized the correct solution: move LLVMAddIncoming() to the end of basic block?

Toshi

Hi Toshi,

You can add the incoming value later, after you actually created it.

     // Here you build the PHI and add the first incoming value
     counter = LLVMBuildPhi(builder, LLVMInt64Type(), tmp_name);
     phi_values[0] = counter_init;
     phi_basic_blocks[0] = loop_init;
     LLVMAddIncoming(counter, phi_values, phi_basic_blocks, 1);

     // When you created the loop body and the "counter_next" value, you can add another incoming value
     phi_values[0] = counter_next;
     phi_basic_blocks[0] = loop_body;
     LLVMAddIncoming(counter, phi_values, phi_basic_blocks, 1);

-Manuel