Subject: Re: [feature/native-comp] miscompilation(?) of functions with non local exits

From: Andrea Corallo <[email-masked]>
Date: Wed, 15 Jul 2020 21:19:37 +0000

Stefan Monnier <[email-masked]> writes:

>> Three options:
>>
>>   1- Because setq is evaluated the expression should always evaluate to
>>   t.
>>
>>   2- Unwinding the original state of the stack is restored, when it was
>>   saved 'x' was nil so the expression should evaluate to nil.
>>
>>   3- This is unspecified.
>
> Very definitely (1)!

All right, I pushed a fix that restores behavior 1.

>> FYI 1 implies C register variables cannot be used to implement Lisp
>> local variable if non local exits are present.
>
> IIUC, the problem only occurs for those vars which have
> a `condition-case` (or `unwind-protect` or `catch`) in their scope and
> where the var is modified within that construct and that a non-local
> exit can jump to the end of that construct after the var was thus
> modified, and that the var is used after the construct.

Correct.  If the compiler keep these variables in the stack then it's
all fine because setjump will restore SP and inside the stack you'll
find the most updated value.  On the contrary if the variable was kept
in a register then its updated value may be lost if the reg is callee
saved.

> This should be fairly rare (not sure if those cases can easily be
> written differently, OTOH).

The case I've encountered is `truncate-string-to-width'.

> The compiler could replace those vars
> by boxing them inside a cons-cell (so the register-stored C var is
> immutable and contains a pointer to a cons cell which holds the real
> value in the `car`), just like we do with mutated Elisp vars captured
> by closures.

What I pushed now is (for functions with non locals) just to keep stored
all local vars in an array (as the bytecompiler does).  I added note and
we should be able to implement something more selective as suggested.
Either adding an indirection or marking the sensitive variables as
volatile.

Thanks both for the feedback.

  Andrea

-- 
[email-masked]