When I generate a simple function with a single basic block with two
return instructions, I had expected that if it did anything at all, it
would use the first one, but it actually seems to ignore the first one
and take the value of the second one.
I'm guessing what's going on here is something like "a basic block
must end in exactly one terminator instruction, having two of them is
undefined behavior and the code generator is entitled to do anything
including make demons fly out of your nose"; is this correct?
That's pretty much been my experience. Usually, something crashes
when I try it though.
Fair enough. In that case, is there an elegant way to test whether a
basic block already has a terminator instruction?
(I can think of several ways to do it in the front-end, but all of
them are fairly inelegant. The problem I'm trying to solve is things
like 'a return instruction needs to be added to the end of a function,
if and only if the programmer didn't already end the function with an
explicit return statement', 'if the programmer did write an explicit
return statement everything after it must be ignored' etc.)
Did your test include running llvm::verifyFunction(...) on the function in question?
I guess I should test this, but I would have thought this would catch the issue.
Ah! I didn't know about verifyFunction; it does indeed catch it,
thanks! I'll leave that call in my code for all cases for the moment,
should help identify problems like that.
Is there a recommended way to avoid this problem when compiling a
language that has an explicit and optional return statement?
Since terminators are only allowed at the end of a block, you could
always check the last statement of the block to see if it's a
terminator. For that matter, BasicBlock::getTerminator returns the
terminator, or NULL if it hasn't got one yet.