🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.tcl
Article #15

Re: Experiment: inline bytecode for [lrange] with variable indices (written by Claude)

#15
From: et99
Date: Wed, 07 Oct 2026 15:23
269 lines
16246 bytes
Thanks, Ashok.

The push worked. (A correction to my earlier post: my
Fossil username is rocketship98; rocketship88 is my GitHub name.) The
branch is now on core.tcl-lang.org as lrange-inline, check-in 5c9d6b18,
based on trunk a675fa55:

     https://core.tcl-lang.org/tcl/info/5c9d6b18

Some follow-up findings. Claude profiled the call path in its sandbox
with callgrind. These are exact instruction counts, not times, and
nothing in the source was changed.

(I haven't repeated the callgrind runs myself so consider this his
preliminary findings).


-------------------------------------------------------------------

Where the cost of a non-inlined call goes. Inline [lrange] saves
about 690 instructions per call:

   Table 1. [lrange] forms, instructions per call

   form                     invokeStk   listRange   fewer
   lrange $l 1 3                   82          82      0%  (already inline)
   lrange $l $i $j               1718        1027     40%
   lrange $l $i end              2064        1369     34%
   lrange $l 1 end-$n            3246        2557     21%

   Table 2. Where the 694 saved instructions per call go
   (lrange $l $i $j)

   evaluator trampoline (EvalObjvCore, TclNRRunCallbacks,
     TclNREvalObjv, NRCommand and others)                      299
   invokeStk instruction + re-entering the bytecode loop       127
   interpreter result handling                                  82
   extra object allocation and thread-data lookups              76
   Tcl_LrangeObjCmd's own argument handling                     66
   command lookup (Tcl_GetCommandFromObj)                       31
   other small items                                            13
   total                                                       694

So the command lookup is not the problem: the name is a literal object
with a cached lookup, and it is only 31 instructions. The cost is the
machinery around the call, and every non-inlined command and every proc
call pays it.



(here Claude and I took a look at what I suggested might be something that
could be done for heavy math compute code to avoid the invokeStk entirely)




The math functions show the same thing. All 58 commands in
::tcl::mathfunc compile as push "tcl::mathfunc::NAME" followed by
invokeStk, including with constant arguments. None are inlined.
[expr {abs($x)}] compiles to:

     push "tcl::mathfunc::abs"; loadScalar x; invokeStk 2;
     tryCvtToNumeric

To estimate what an inline abs could achieve before anyone writes one,
Claude used the assembler ([tcl::unsupported::assemble]) to write
variants of abs directly in TAL, and counted each variant with
callgrind. The rows are:

   - "load x; nop" is a probable floor. It loads the value and does no
     work, so no real abs bytecode can beat it.
   - "load x; uminus" and "load x; uplus" are existing instructions that
     do the kind of work an abs would: uminus allocates a new number (as
     abs must for a negative value), and uplus checks that the value is
     numeric. They approximate what a real abs bytecode might cost.
   - "call, as expr emits it" is the real thing, including the final
     tryCvtToNumeric.
   - The last two rows (marked *) are variants without that final
     instruction, or built by hand from existing instructions
     (load x; dup; push 0; lt; jumpFalse; uminus). They work today with
     no C changes, but they are not exactly equivalent to expr; see the
     note below.

x = 7 takes the non-negative path (abs returns its argument); x = -5
takes the negative one (abs creates a new number).

   Table 3. abs, instructions per call

   variant                                    x = 7    x = -5
   load x; nop            (floor, no work)       74        74
   load x; uminus                               218       218
   load x; uplus                                252       252
   call, as expr emits it (with
     tryCvtToNumeric)                          1075      1069
   call, without that final instruction *       861      1013
   hand-written in TAL *                        298       447

Note on the final instruction. tryCvtToNumeric is not redundant. It
gives the result the canonical string form of its value: with it,
expr {abs($x)} returns 16 for x = 0x10, 7 for x = 0007 and 100.0 for
x = 1e2; without it, the same call returns the argument unchanged. It
costs 56 instructions when abs creates a new number, but 214 when abs
returns its argument, since the shared object has to be copied to drop
the old string form. So an inline abs has to normalize its result in
the same way, which is why the rows marked * understate the cost of an
exact replacement.

Table 4 repeats the comparison for a few other functions, through the
normal expr route. The "by hand" figures are approximate equivalents
written as plain expr operators. They don't treat -0.0 or mixed
integer/double arguments in exactly the same way, so read them as a
guide, not a precise ratio. The functions with no equivalent (int,
sqrt, sin) cost about the same as the others, so for them nearly all
of it is call overhead.

   Table 4. expr function calls vs hand-written equivalents
   (x = -5, y = 3)

   expression              call    by hand
   abs($x)                 1069        512
   max($x,$y)              1263        504
   double($x)              1030        438
   int($x)                 1073          -
   sqrt($y)                1045          -
   sin($y)                 1167          -

Only about 110 of the roughly 1070 instructions for abs are the abs
work itself. The existing unary instructions (uminus, uplus), which also
produce normalized numbers, cost 220 to 250, so a dedicated abs
bytecode would probably land around 250: about 4 times fewer
instructions per call. That is an estimate, since no such opcode exists
yet, and it is per call, not for a whole program. Functions that do real
work, such as sin, would gain less in proportion, because the libm call
remains.

If invokeStk itself can't be made cheaper, the next best thing is to
avoid it where possible: more inline compile routines (what the
lrange branch does), and bytecodes for the common math functions (abs,
int, double, round, min, max, sqrt, sin, cos and so on), emitted by the
expression compiler with a guard so that redefining a function in
tcl::mathfunc still takes effect. Together with TIP 760 (making
[assemble] public), such bytecodes could also be used directly from
assembler code in heavy numeric procs.

An alternative that avoids the redefinition question is opt-in names
for the fast versions, for example absx or cosx (the naming is open),
which expr would compile straight to the bytecodes, while the ordinary
names keep their current behavior. Transparent inlining helps existing
code, and opt-in names are simpler and safer. Either one is a small,
bounded change per function, similar in size to the listRange change.
I haven't built any of this: the numbers above are measurements of the
current code plus estimates.

Eric



On 10/7/2026 6:14 AM, Ashok wrote:
> You should have access now. Please retry.
> 
> 
> On 10/7/2026 12:37 PM, et99 wrote:
>>
>> Ashok,
>>
>> Thanks for the encouragement. I've created an account on
>> core.tcl-lang.org (username: rocketship88) and have the change
>> committed locally on a Fossil branch called lrange-inline, based on
>> trunk check-in a675fa55 (2026-10-05). I can't push it yet because I
>> don't have write permission.
>>
>> Could someone grant me rights to push it, or tell me who to ask? Or, if
>> you'd rather not, a diff made by Fossil (trunk vs. the branch) is here:
>>
>>      https://github.com/rocketship88/lrange-inline/blob/main/lrange.diff
>>
>> It touches 8 files under generic/ and tests/. The rest of the experiment
>> (README, benchmark script, the base files and the changed ones as
>> side-by-side commits) is at:
>>
>>      https://github.com/rocketship88/lrange-inline
>>
>> As in my first post, the code and tests were written by Claude and I
>> reviewed, built and tested them locally. The tests pass on my builds.
>>
>>
>> Claude writes:
>>
>> Ashok asked whether I looked at [string range]. I did, but only after he
>> asked, so it had no part in how I wrote the code. Having read it now, the two
>> are very similar: both have an immediate form for literal indices and a
>> three-value form for the rest.
>>
>> As for why [lrange] was never done that way, a comment above
>> TclCompileLrangeCmd says "We only bother because we needed the opcode anyway
>> for lassign." So listRangeImm was added for lassign, and compiling [lrange]
>> with literal indices came along as a side benefit. The non-literal case
>> doesn't seem to have been considered.
>>
>> As for optimizing invokeStk, I haven't tried. It is a much bigger and riskier
>> change than this one, because that path leaves the bytecode loop through
>> TclNREvalObjv. We measured about 44 ns of call overhead on the faster of our
>> machines. If the core team is interested, I'd start by profiling that path
>> with callgrind, with no code change, and see where the time goes.
>>
>>
>>
>>
>> -Eric
>>
>>
>> On 10/6/2026 8:23 PM, Ashok wrote:
>>> Certainly worth pursuing I think. My knowledge of the Tcl byte code is mostly based on cargo culting (blush) so creating a branch in the Tcl repository so more knowledgeable folks can take a look is worthwhile. I'm not sure everyone reads c.l.t.
>>>
>>> As an aside, I'm a bit surprised that this was not already compiled. The string range command is very similar to lrange and afaict that compiles in much the same fashion as your patch for lrange with support for non-literal arguments (which leads me to wonder if Claude might have used it as the basis for what it produced). Not sure why lrange was not implemented the same way.
>>>
>>> On a different topic, I wonder if you could ask Claude to optimize invokeStk* bytecode implementation. I wonder if it is something that needs to be inherently slower because the additional work involved or if there is scope there for improvement.
>>>
>>> /Ashok
>>>
>>> On 10/7/2026 6:49 AM, et99 wrote:
>>>> Hi all:
>>>>
>>>> A note first: in the last few months my Claude account (a Pro subscription, not the free tier) has gained the ability to build and run code in its own Linux sandbox. Before that, Claude could only hand me code and I had to do all the testing on my own machine. I don't know whether this is just my account or a general rollout.
>>>>
>>>> This experiment started as a side effect of a tool Claude and I wrote to scan every proc in every package of a Magicsplat install, looking for bytecode problems. I extended it to count which commands are called through the command table (invokeStk) instead of being compiled inline. Most of what came up does real work per call (format, regsub, lsort, ...), so call overhead is a small part of the cost. The one cheap command that stood out was [lrange] with a non- literal index: [lrange $l 1 3] already compiles to listRangeImm, but [lrange $l $i $j] and [lrange $l 1 end-$n] fall back to a full command call.
>>>>
>>>> I asked Claude (Anthropic's AI assistant), working in its sandbox with access to the GitHub mirror of the Tcl source, to add a new listRange instruction that always takes exactly three values from the stack: the list and both indices. It took about 20 minutes to get a complete patch with tests, after many build and test runs in the sandbox, including AddressSanitizer, Tcl's memory-debug build and the TCL_COMPILE_DEBUG build. I copied the changed files into my own tree, built, and ran the tests and a benchmark on two of my machines. Claude ran the same benchmark in its sandbox, which is the third column below.
>>>>
>>>> Base: Tcl main, commit 78dedf7 (2026-10-05, GitHub mirror).
>>>>
>>>> What changed (66 lines of C added, 16 removed; 161 lines of tests added):
>>>>
>>>>    generic/tclCompile.h       +1         new opcode INST_LIST_RANGE
>>>>    generic/tclCompile.c       +7         instruction table entry
>>>>    generic/tclExecute.c       +34        the instruction
>>>>    generic/tclCompCmdsGR.c    +23 -16   compile non-literal indices to it
>>>>    generic/tclAssembly.c      +1         tcl::unsupported::assemble can use it
>>>>    tests/lrange.test          +85        lrange-6.1 .. 6.14
>>>>    tests/compile.test         +38        compile-22.1 .. 22.5
>>>>    tests/assemble.test        +38        assemble-7.47 .. 7.50
>>>>
>>>> The instruction does what Tcl_LrangeObjCmd does, in the same order, so error messages and error precedence are the same as for the command. A test compares the compiled form against the command for 6 lists and 20 index forms each way, with no differences.
>>>>
>>>> Tests: the full suite gives 509,285 tests (23 more than before), the same 8 failures before and after (httpProxy.test, which needs network access). disassemble and getbytecode show the new instruction.
>>>>
>>>> Timing (ns per call, 10-element list, best of 7, before -> after):
>>>>
>>>>                            machine 1    machine 2   Claude's sandbox
>>>>    lrange $l $i $j         193 -> 126   117 -> 72   152 -> 98
>>>>    lrange $l $i end        232 -> 165   130 -> 93   172 -> 123
>>>>    lrange $l 1 end-$n      368 -> 291   200 -> 161  270 -> 212
>>>>    lrange $l 1 3 (literal)  38 -> 39     24 -> 23    32 -> 34
>>>>
>>>> The sandbox is a small shared VM, so its numbers are noisier than mine. The literal case compiles to identical bytecode in both builds, and its difference changes direction between machines, so I take it to be build- layout noise. The end-$n gain is smaller because the string "end-N" is still built and parsed on every call.
>>>>
>>>> Limits: Linux only. I have not built it on Windows or macOS, so MSVC has not seen it. I have not tried an integer fast path for end-$n.
>>>>
>>>> I am posting this as a data point more than as a proposal. If anyone on the core team thinks it is worth a ticket, I will file one with the patch. The patch, the test results and the benchmark script are here: https://github.com/rocketship88/lrange-inline .
>>>>
>>>> On a side note, I have also found the same assistant good at drafting documentation for my own projects, especially when using the AI to build the projects. It needs a human to check the facts, but it makes a decent first draft. The Readme at github was also written by Claude.
>>>>
>>>> Eric
>>>>
>>>
>>
> 
Technical Details
Message-ID: <11a5o4r$3052a$1@dont-email.me>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
References: <11a46mp$2f14b$1@dont-email.me> <11a4dvk$2gi5g$1@dont-email.me> <11a4r4g$2kn80$1@dont-email.me> <11a5gj2$2t0qj$1@dont-email.me>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
From: et99 <et99@rocketship1.me>
Newsgroups: comp.lang.tcl
Subject: Re: Experiment: inline bytecode for [lrange] with variable indices
 (written by Claude)
Date: Wed, 7 Oct 2026 08:23:05 -0700
Organization: A noiseless patient Spider
Lines: 269
Message-ID: <11a5o4r$3052a$1@dont-email.me>
References: <11a46mp$2f14b$1@dont-email.me> <11a4dvk$2gi5g$1@dont-email.me>
 <11a4r4g$2kn80$1@dont-email.me> <11a5gj2$2t0qj$1@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Date: Wed, 07 Oct 2026 15:23:08 +0000 (UTC)
Injection-Info: dont-email.me;
	logging-data="3150922"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX186i6EI6Rm1fV2hM4LD1Tt3"; posting-host="c368b75c749776c669dd453f26deb3d8"
User-Agent: Mozilla Thunderbird
Cancel-Lock: sha1:IQGx4x9vKhtpxQNLQxVMuTHS8Eg= sha256:Lqq2QmCy0NwUGjGzHex3/5rK4o6IE4FmIZbbTq0SCg0=
	sha1:bYFLa0/CiGuWUiJRItNoBcnVBC0= sha256:tGSuFXtb2Zl3dct5gtNQ29osmyHTNgxxIjEzk7nmdaY=
In-Reply-To: <11a5gj2$2t0qj$1@dont-email.me>
Content-Language: en-US