llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Optimize pass struct by value to tail call

Open davidbolvansky opened this issue 8 years ago • 5 comments

Bugzilla Link 38862
Resolution FIXED
Resolved on Oct 08, 2018 12:02
Version trunk
OS Windows NT
CC @topperc,@efriedma-quic,@fhahn,@gregbedwell,@rnk,@rlougher,@rotateright

Extended Description

struct A { int x[64]; };

void structByValue(A s);

void callStructByValue(A s) { structByValue(s); }

Clang: callStructByValue(A): # @​callStructByValue(A) sub rsp, 264 lea rsi, [rsp + 272] mov ecx, 32 mov rdi, rsp rep movsq call structByValue(A) add rsp, 264 ret

GCC: callStructByValue(A): jmp structByValue(A)

If I change code to: struct A { int *x; };

Clang tail calls it too.

davidbolvansky avatar Sep 07 '18 07:09 davidbolvansky

Fixed by r343986.

rlougher avatar Oct 08 '18 19:10 rlougher

I think we should just throw this under the header of "byval is terrible, defer this work until we have better solutions for passing structs by value in LLVM".

rnk avatar Sep 17 '18 20:09 rnk

I think you're looking at the problem from the wrong angle; consider the following variant of your testcase:

struct A { int x[64]; }; void structByValue(A s); void callStructByValue(A *s) { structByValue(*s); }

It should be legal to mark the call to structByValue "tail". LangRef says that "tail" implies "the callee does not access allocas from the caller"; byval should be fine because the copy happens in the caller, not the callee. (Of course, we can't actually emit a tail-call on x86 unless the code is using GuaranteedTailCallOpt, but that's a separate issue.)

efriedma-quic avatar Sep 17 '18 19:09 efriedma-quic

Somehow Tracker.AllocaUsers.count(CI) is 1. And then we bail out..

if (!IsNoTail && Escaped == UNESCAPED && !Tracker.AllocaUsers.count(CI)) { DeferredTails.push_back(CI); } else { AllCallsAreTailCalls = false; }

It is added here

AllocaDerivedValueTracker Tracker; for (Argument &Arg : F.args()) { Arg.dump(); if (Arg.hasByValAttr()) Tracker.walk(&Arg);

davidbolvansky avatar Sep 17 '18 13:09 davidbolvansky

Generated IR: define dso_local void @​_Z17callStructByValue1A(%struct.A* byval nocapture readonly align 8){ call void @​_Z13structByValue1A(%struct.A* byval nonnull align 8 %0) ret void }

We miss transformation to tail call.

define dso_local void @​_Z17callStructByValue1A(%struct.A* byval nocapture readonly align 8) { tail call void @​_Z13structByValue1A(%struct.A* byval nonnull align 8 %0) ret void }

We get expected:

callStructByValue(A): jmp structByValue(A)

Godbolt link: https://godbolt.org/z/NfpSLz

davidbolvansky avatar Sep 17 '18 11:09 davidbolvansky