Tcl Source Code

View Ticket
Login
Ticket UUID: 716b427f76f8f97a8d9a06043903c53bb2b592c2
Title: Suboptimal bytecode for $a[unset a]
Type: Bug Created on: 2017-05-30 15:11:23
Submitter: avl42 Assigned to: dgp
Subsystem: 47. Bytecode Compiler Severity: Minor
Priority: 5 Medium Last modified: 2017-06-07 17:36:05
Status: Closed Closed by: dgp
Resolution: Fixed Closed on: 2017-06-07 17:36:05
Version: trunk (8.7)
Description:
Two samples:
  proc foo {a} { upvar 1 $a b;unset a }
  proc foo {a} { upvar 1 $a[unset a] b }

starting with commit fc9ed1e751180816384d569101950c1f8c4582ad (on dgp-string-cat) the the second one slows down noticeably.


Unrelated to the particular commit (i.e already before it) apparently sub-optimal bytecode is generated:
    (##) unsetScalar 1 %v2      # var "a"
    (##) push1 1        # ""
    (##) strcat 2
If that could be avoided, then performance of strcat would play less of a role.
User Comments:
sebres added on 2017-05-30 16:35:07:

Indeed it is pretty reproduceable (almost 2 times slower):

% timerate -calibrate {}
% proc foo {a} { upvar 1 $a[unset a] b }
% timerate {foo x}
0.535961 µs/# 1715950 # 1865807 #/sec 919.682 nett-ms

If I recompile it with change "#if 1" as "#if 0" (from [fc9ed1e751180816384d569101950c1f8c4582ad]):

% timerate -calibrate {}
% proc foo {a} { upvar 1 $a[unset a] b }
% timerate {foo x}
0.333065 µs/# 2635747 # 3002417 #/sec 877.875 nett-ms


sebres added on 2017-05-31 08:32:00:

fixed within [a87280b6d46ed4ae]: optimizes several simplest cases, including patterns like "$v[unset v]", "$v[set v {}]" etc.


dgp added on 2017-05-31 13:16:38:
No!

Please don't do this.

Let the trunk be a place to refactor in peace.

sebres added on 2017-05-31 16:28:42:
@dgp Can you please define your statement more precisely as "No / don't touch"...

I mean: 
Either I should create a branch (and you resp. another high-ranking one merge it later)?
Or I should leave the regression untouched?
Or I had made broken somewhat?

I would not tutor you, just in the world of open source the good practice is not "don't do it" but "you could do it correct so and/or so". 
At least much more productive, IMHO.

dgp added on 2017-06-01 16:30:14:
Agree that was inadequate. I had only a fleeting moment,
but I wanted to at least record dissent before the train
got too many miles away from the station.

The dgp-string-cat branch was one of several efforts to
route string operations through a single implementation
where before there had been multiple duplicate implementations,
each with its own quirky set of bugs or inefficiencies.
There are several more that still need doing. (StringMatch !)

Tcl strings are unexpectedly complex beasts with at least
3 intreps to deal with.  It's really a much better idea to
implement each string operation only once and get it right.
This also paves the way to explore wholesale replacement of
the current complex beast with some other ones, without the
need to grep through the whole codebase seeking all N
implementations of string concatenation.

Attaching some optimizations to just one caller of
TclStringCatObjv() looks like the first step in
reversing that refactoring course, so I reacted in protest.

I also protest the expectation that in a branch dedicated
to alpha explorations, we have to remain slaves to the
absolute best performance.  That's a recipe for sticking
in local optima of implementation and missing the chance
to incrementally move to radically better approaches.

I've had similar objections to other performance-chasing
on trunk based on things like Tcl_ObjType-probing where
the sort of encapsulations that make effective refactoring
possible get broken for the sake of sub-microsecond differences.
It's polishing a statue before it even takes its form.

That said, performance is important, and that's why I asked
this ticket be opened so that we would address this problem
in time.

Looking a bit longer and more carefully now, I think an
adaptation of this will be fine.  I'll take a stab at it
as I shift the branches around.

I will note that it's a known assertion that (opnd >= 2)
so much of the added code covers cases that cannot happen.
I'll make that clear in my edits.

sebres added on 2017-06-01 19:23:43:
+1. 

Don't forget that this thing (how I implemented it) may save the internal representation of resulting object, thus it is more what this patch doing in the reality (I mean the following execution steps, that will stop to resolve again the varname, the command, the lists/dicts etc.).

That was the reason, why I did it. And it is already in my performance-branch for 8.6 also (just to note).

dgp added on 2017-06-05 20:05:54:
Please take a look at alternative solution on the
branch bug-716b427f76 .

This is an attempt to optimize the "only one argument
is non-empty" case in TclStringCatObjv() so that all
the string concat operations benefit, not just one
bytecode.

My crude measurements suggest it is an improvement, but
review from those with finer tools is welcome.

sebres added on 2017-06-06 08:40:07:

Looks pretty good.

I made small amend in [eac4656f1e], then the test-cases show the same performance (marginal deviation compared to trunk, because of the extra call of function, there is visible only on very slow mashines with small cpu-cache).

I would suggest to merge it. Thanks.


sebres added on 2017-06-06 09:34:32:

since [c30066298d9965ba] I see no deviation anymore as regards performance of the simplest cases.


dgp added on 2017-06-06 13:16:42:
Merged the improvements to TclStringCatObjv().

Re-opened and re-titled ticket so that the
improvements to the bytecode itself can still
be pursued.

dgp added on 2017-06-06 14:23:10:
The optimizer is not optimizing this case
because it thinks it is a "TargetAddress".

Still trying to find out why it thinks that.

dgp added on 2017-06-06 16:41:50:
This is tied into the machinery for restarting
after some bytecode execution bumps the compile
epoch.  At that point the start of the next
command has to be found so that direct eval, or
recompilation, can take place at that point.
The bytecode considers that potential restart
point as a TargetAddress.

Problem here is that calculation is not in fact
pointing to the next command, but at the first
bytecode following the current command, which
is not a command at all, but the concat operation
to form a word out of substituted pieces.  Repairing
this seems to be a moderately sophisticated
upgrade of the optimizer at least.

Worse, it may be tied in to an actual bug where
the compile epoch bump during substitution doesn't
take effect on the command for which the substitution
is being done.  See

https://core.tcl.tk/tcl/tktview/9a2bc209faf87b2f156d1971447f59e294184f9e

dgp added on 2017-06-06 19:56:48:
Here is why Tcl's optimizer is correct that it
cannot optimize those instructions to no-ops
(at least absent some deep and fundamental changes
to the bytecode execution engine):

Define two variables to report different outcomes:

% set v wut?
wut?
% set v1 yay!
yay!

Define a self-modifying proc and examine its bytecode:

% proc demo a {proc unset x {return 1}; upvar 1 $a[unset a] b; puts $b}
% tcl::unsupported::disassemble proc demo
ByteCode 0x2519c60, refCt 1, epoch 18, interp 0x24b75b0 (epoch 18)
  Source "proc unset x {return 1}; upvar 1 $a[unset a] b; puts $b"
  Cmds 4, src 55, inst 59, litObjs 7, aux 0, stkDepth 4, code/src 0.00
  Proc 0x255c9a0, refCt 1, args 1, compiled locals 2
      slot 0, scalar, arg, "a"
      slot 1, scalar, "b"
  Commands 4:
      1: pc 0-10, src 0-22        2: pc 11-51, src 25-45
      3: pc 24-40, src 36-42        4: pc 52-57, src 48-54
  Command 1: "proc unset x {return 1}..."
    (0) push1 0         # "proc"
    (2) push1 1         # "unset"
    (4) push1 2         # "x"
    (6) push1 3         # "return 1"
    (8) invokeStk1 4 
    (10) pop 
  Command 2: "upvar 1 $a[unset a] b..."
    (11) startCommand +40 1     # next cmd at pc 51, 1 cmds start here
    (20) push1 4        # "1"
    (22) loadScalar1 %v0        # var "a"
  Command 3: "unset a..."
    (24) startCommand +17 1     # next cmd at pc 41, 1 cmds start here
    (33) unsetScalar 1 %v0      # var "a"
    (39) push1 5        # ""
    (41) strcat 2 
    (43) upvar %v1      # var "b"
    (48) pop 
    (49) push1 5        # ""
    (51) pop 
  Command 4: "puts $b"
    (52) push1 6        # "puts"
    (54) loadScalar1 %v1        # var "b"
    (56) invokeStk1 2 
    (58) done 

Note that pc 24-40 are the bytecode of the [unset a].
It was produced by compiling the original meaning of [::unset].
However, at run time when that bytecode is reached,
[::unset] has a new definition. The "startCommand" instruction
detects this and effectively overwrites pc 24-40 with a new
set of bytecode:

push "unset a"
evalStk

This makes the bytecode do a proper Tcl evaluation, but
then it returns to pc 41 to continue operations from
there.

Now, if we allowed some optimizer to turn pc 39-42
into no-ops, then after the replacement and recovery
to pc 41, we'd have a no-op instead of a proper strcat
to attach the "1" returned by the replacement [unset]
to the varname, and we'd link to the wrong caller variable.

So we run it and see proper functioning:

% demo v
yay!

Given how all the pieces currently fit together and function
this is an optimization we cannot do.

But! But! If we just... and ... 

Yes, by all means take a stab at it, and seek out the
proper boundaries of reform that might let us make the
optimization; just know it's not a simple matter.

ferrieux added on 2017-06-06 21:02:19:
> But! But! If we just... and ... 
> Yes, by all means take a stab at it, and seek out the
> proper boundaries of reform that might let us make the
> optimization

For someone who hasn't been following this in detail, but still has an idea of what "compile epoch" and "dominant case" mean, this sounds like we're sacrificing the speed of 99.9% of use cases for the occasional Munchhausen code finding it funny to grab its own boot straps.

Is there really no way to somehow turn the compilation epoch into some kind of dependency graph so that (1) in the normal case no-ops are generated, with appropriate markers and (2) in the rare catastrophic event of someone reinventing the quark and the gluon, the affected proc bodies get deoptimized at the marked places ?

dgp added on 2017-06-07 17:36:05:
I did not say there is "no way". I explicitly invite
interested people to find the way. Find the boundaries
of how much has to change to make the optimization
possible.

What I am saying is that there's more to it than
twisting a couple of knobs, or some other simple
approach you might guess first seeing the issue.

My first assumption: no one tried to optimize this
sequence before.  FALSE. It's right there in tclOptimize.c.

Second assumption: the finding blocking the optimization
is in error. FALSE. If you don't re-invent how compile epoch
recovery is done, the blocking is appropriate to account for it.

To get what's desired, there's an effort of more than a few hours
involved to get it done, and I'm backing away from that, and
recording for others what I learned so they can go forward 
with eyes open and the start of a map.  The rewards may very
well be worth it to someone who can devote the effort.