<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/116583>116583</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[CodeGen][WinEH] Miscompilation due to inlining of inalloca functions
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
MuellerMP
</td>
</tr>
</table>
<pre>
For the Microsoft C++ ABI call parameters may be attributed inalloca https://llvm.org/docs/InAlloca.html.
The lifetime of an inalloca parameter is bound to the call, even if the call is inlined.
Thus inlined InAlloca allocas always lower to dynamic allocas which modify the stack pointer.
For WinEH we safe the stack pointer in fs[0]-4 which will we reloaded by the c runtime when unwinding.
Dynamic allocas, as is the case for inalloca allocas, modify the stack pointer thus breaking stack access after unwinding.
This can be shown with the following C++ code:
```C++
// can be compiled with clang-cl -target i386-pc-windows-msvc /EHs /O2
// O2 is required for inlining and EHs enabled basic c++ exceptions
#include "stdio.h"
struct Foo { int a{123};int b{2}; Foo(){}; ~Foo(){}; Foo(const Foo &){} __declspec(noinline) void bar(int a, int b) {}};
int g(Foo foo) {
try {
throw 1;
} catch(...) {
}
foo.bar(0, 1); // overwrites the inalloca stack buffer with params
printf("%d %d\n", foo.a, foo.b); // prints '0 1'
return 0;
}
int main(int argc, char**) {
return g(Foo());
}
```
Since godbolt doesn't provide access to microsoft C/STL headers here is a simplified version which visualizes generated code:
https://llvm.godbolt.org/z/TPq4Pnxch
We see that esp is moved to -28(%ebp) and -24(%ebp) is moved to %fs:0 which represents the typical 32bit WinEH Prolog.
Afterwards there are two pushes and then a call to alwaysthrows.
This means that in our catch block our esp will we rewound to its value before the pushes.
This also means any following pushes will overwrite the foo members.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJx0Vl-P26oT_TTkZZTIxnb-PORhs2l-rfRbdaWu1McKwzjmFoMLOG76cD_7FRgn2d5eKUpiGM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