How to do a short-lived alloca (in a loop)?

I need a temporary allocation to do some stuff and then need to get rid of it again. The problem with Builder.CreateAlloca is, that the allocation lives until the function return. I don’t see a way to reclaim it.
So in a loop, the unreclaimed allocations accumulate and may overflow the stack.

llvm::AllocaInst  *alloca;
llvm::Value       *emitMarker;

alloca = Builder.CreateAlloca( llvmType);
emitMarker = EmitLifetimeStart( typeSize, alloca);

// do very simple stuff 

EmitLifetimeEnd( emitMarker, alloca);

I hoped that EmitLifetimeStart/EmitLifetimeEnd would be able to reclaim the storage, but it didn’t. This is only a problem for DEBUG code, since the optimizer can get rid of the temporary allocation code. In assembler it would just be adjusting the stack pointer, not really a biggy, but I don’t see how I can do this with what IRBuilder provides.

LLVM’s code generator divides allocas into two kinds: “static” and “dynamic”. “static” allocas are allocas with fixed size, located in the entry block of the function. These are generally allocated in the function prologue. “dynamic” allocas are everything else; they’re allocated when the “alloca” instruction executes.

If you have dynamic allocas, you probably want to look at llvm.stacksave/llvm.stackrestore. This is the closest to “adjusting the stack pointer”.

See also 7. Kaleidoscope: Extending the Language: Mutable Variables — LLVM 15.0.0git documentation .

Thanks a lot. With llvm.stacksave / llvm.stackrestore I got the short-lived alloca I needed.