Skip to content

Commit 66ed08c

Browse files
authored
Add documentation for [[msvc::musttail]] attribute
Document the [[msvc::musttail]] attribute with constraints and an example.
1 parent 11bcd73 commit 66ed08c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

docs/cpp/attributes.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,41 @@ void f() {
158158
i = my_move(i);
159159
}
160160
```
161+
### `[[msvc::musttail]]`
162+
163+
The `[[msvc::musttail]]` attribute is an experimental x64 only Microsoft-specific attribute that enforces tail-call optimization for a given function call. When applied on a qualifying return statement, it instructs the compiler to emit the call as a tail call. If the compiler cannot do so, it will produce a compilation error. The `[[msvc::musttail]]` attribute will enforce tail calling over inlining of a function.
164+
165+
The `[[msvc::musttail]]` attribute has constraints:
166+
- The caller and callee must have matching return types.
167+
- The calling conventions must be compatible.
168+
- The tail call must be in the return position (i.e., the final action in the calling function).
169+
- The callee must not use more stack space than the calling function.
170+
- If more than 4 integer parameters are passed, the calling function must allocate enough stack space for those additional arguments. Please see __preserve_none calling convention for tail calling without additional stack overhead.
171+
- Other compiler optimizations must be enabled.
172+
173+
#### Example
174+
175+
In this sample code, the `[[msvc::musttail]]` attribute applied to the return bar function call forces execution to jump from foo to bar before returning to main, rather than inlining bar into foo or calling bar from foo and returning to foo before returning to main.
176+
177+
```cpp
178+
int bar(int x) {
179+
return x + 1;
180+
}
181+
182+
int foo(int x) {
183+
if(x > 0){
184+
[[msvc::musttail]]
185+
return bar(x);
186+
}
187+
return -1;
188+
}
189+
190+
int main() {
191+
int result = foo(42);
192+
if(result < 0) return -1;
193+
return 0;
194+
}
195+
```
161196
162197
### `[[msvc::noinline]]`
163198

0 commit comments

Comments
 (0)