ApsarasX/llvm-bindings

Crash when writing bitcode if using addBasicBlock

wintermute-motherbrain opened this issue · 1 comments

  • OS version: macOS 11.6
  • Node.js version: v17.0.1
  • LLVM version: 13.0.0

It is possible to get a seg fault when executing the function WriteBitcodeToFile. The crash occurs about 1/10 times when running the same code over and over. I have not been able to create an isolated test case but this code is at the root of the issue:

`const test = load(s.test) // <-- load a value
const parent = builder.GetInsertBlock().getParent()
const thenBlock = llvm.BasicBlock.Create(context, "then", parent)
const elseBlock = llvm.BasicBlock.Create(context, "else", parent)
const continueBlock = llvm.BasicBlock.Create(context, "ifcont", parent)

builder.CreateCondBr(test, thenBlock, elseBlock)

parent.addBasicBlock(thenBlock)
builder.SetInsertPoint(thenBlock)
gen(s.consequent)
builder.CreateBr(continueBlock)

parent.addBasicBlock(elseBlock)
builder.SetInsertPoint(elseBlock)
gen(s.alternate) <--- generate additional if else
builder.CreateBr(continueBlock)

parent.addBasicBlock(continueBlock)
builder.SetInsertPoint(continueBlock)`

If I print out the module before writing the bitcode, the IR is always the same/valid. My hunch is its something to do with the addBasicBlock specifically (since that seems to be a custom function). If I remove the calls to addBasicBlock, I don't get the crash.

Expected behavior

Won't crash on valid IR when writing bitcode.

Was able to solve this using saving and restoring the insert point instead.