Quick doubt about IR


While looking over the IR generated by my source code, I came across the following:

%arr = alloca [30 x i8], align 1

In the source code this particular line of code is represented by:

int arr[30];

I was wondering how I could change the capacity of arr from 30 to any other integral value via a function-pass. I know that ‘alloca’ can be used for reserving space on stack; further, ‘store’ can be used for writing to memory. I was wondering how that would work for an array though?


Create a new alloca instruction, insert it into the IR right before (or after) the old one, RAUW the value, then delete the old instruction. You should be able to find a variety of examples of this sort of thing in most of the IR level optimization passes. I’d look at InstCombine in particular.



So I included this in my code:

ArrayType* b = ArrayType::get(IntegerType::get(getGlobalContext(), 8), 10);
AllocaInst* pa = new AllocaInst(b, “arr”);

//Considering that I represents the instruction iterator pointing to the instruction that I want to replace (i.e. %arr = alloca [30 x i8], align 1)

I->getParent()->getInstList().insert(*I, pa);

I’m running into the following error:

Stack dump:

Return code not zero; aborting
void llvm::Value::replaceAllUsesWith(llvm::Value*): Assertion `New->getType() == getType() && “replaceAllUses of value with new value of different type!”’ failed.
0 opt 0x08fc4996 llvm::sys::PrintStackTrace(_IO_FILE*) + 50
1 opt 0x08fc4be9
2 opt 0x08fc45f0
3 0xb77c4400 __kernel_sigreturn + 0
4 0xb77c4422 __kernel_vsyscall + 2
5 libc.so.6 0xb751f941 gsignal + 81
6 libc.so.6 0xb7522d72 abort + 386
7 libc.so.6 0xb7518b58 __assert_fail + 248
8 opt 0x08edfb85 llvm::Value::replaceAllUsesWith(llvm::Value*) + 187
9 CS6265Pass.so 0xb77bdee4
10 opt 0x08ec5317 llvm::FPPassManager::runOnFunction(llvm::Function&) + 301
11 opt 0x08ec54b8 llvm::FPPassManager::runOnModule(llvm::Module&) + 92
12 opt 0x08ec57bc llvm::MPPassManager::runOnModule(llvm::Module&) + 496
13 opt 0x08ec5d4d llvm::PassManagerImpl::run(llvm::Module&) + 229
14 opt 0x08ec5f41 llvm::PassManager::run(llvm::Module&) + 39
15 opt 0x0849c28b main + 5835
16 libc.so.6 0xb750be46 __libc_start_main + 230
17 opt 0x0848e4b1

How can I fix it?



I wonder why the type of %arr is i8, instead of i32 in your code?