raz / commit 28e62ecd

commit
28e62ecdfa5f67aa0736b881dc2f78d85217be24
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
a5915c27
Step 9e: a profiler in Rt

With RAZ_PROFILE set, Rt's body has SIGPROF come every millisecond of
the program's time (setitimer ITIMER_PROF; SA_RESTART so system calls
go on); onProf notes the interrupted rip, in any thread. exit stops
the timer and says, by the procedures and places tables of 9d, the ten
procedures and the ten places that took most of the samples, as shares.
test/check.sh profiles test/list/Busy.raz and wants Busy.spin first.
doc/book/PLAN.md, committed by mistake with 9d, is untracked again.

patch · log

7 files changed, +141 -109

PLAN.md (history) modified +1 -1

@@ -156,7 +156,7 @@
156156 under way, each with its variables by name and value, from
157157 tables the compiler writes; `Rt.trace` gives the same on
158158 demand.
159-- [ ] 9e. A profiler in `Rt`: a program run with `RAZ_PROFILE` set
159+- [x] 9e. A profiler in `Rt`: a program run with `RAZ_PROFILE` set
160160 samples where it is, and at its end says which procedures and
161161 lines took the time.
162162 - [ ] 10. `doc/compiler.md`, README, the report's version and the

README.md (history) modified +4 -0

@@ -103,6 +103,10 @@
103103
104104 `Rt.trace` says the same at any time.
105105
106+A program run with `RAZ_PROFILE` set in its environment is sampled
107+every millisecond of its time; at its end it says which procedures, and
108+which places in the source, took the most of it.
109+
106110 `raz run Main.raz a b` compiles the same way, then runs the program
107111 with the arguments `a b`, writing no file: its output and exit status
108112 are the command's.

doc/book/PLAN.md deleted +0 -106

@@ -1,106 +0,0 @@
1-# Stage: the book "Compiling Raz"
2-
3-This is the owner's go-ahead for a new stage: a book, "Compiling Raz",
4-explaining how the raz compiler works. Follow CLAUDE.md's way of working:
5-one commit per step, push it, then stop for review. Don't change the
6-language or the compiler for the book's sake. If the book exposes a bug
7-or a clumsy spot, report it rather than fixing it.
8-
9-## Read first
10-- CLAUDE.md, doc/raz.md (the report), doc/compiler.md, README.md.
11-- src/*.pas, the whole compiler (about 5,000 lines), and enough of lib/
12- (Rt, Heap, Mem, Thread, Sys) to explain the runtime.
13-- The tiza skill, for drawings.
14-
15-## The reader
16-A working programmer: not good at Pascal, little knowledge of compilers.
17-- Assume they roughly know registers, the stack and memory. Explain only
18- what raz does with them (frames, calling convention, layout).
19-- Introduce compiler ideas (tokens, grammar, generating code while
20- parsing, symbol tables) briefly and in friendly terms where they first
21- appear.
22-- Teach just enough Pascal to read the compiler: one early chapter, then
23- more as features come up. Teach enough raz the same way.
24-- Keep the two languages visibly apart: ```raz and ```pascal code blocks,
25- and say which one is on screen.
26-- Don't explain formats that can be looked up. ELF gets a page on what
27- raz writes and why, plus a pointer to the spec.
28-- Target 40-50k words.
29-
30-## Tone
31-Like Learn You a Haskell and Starting FORTH: tiny steps, talking straight
32-to the reader, every idea shown at once on a real example, drawings that
33-carry meaning. Warm, with an occasional dry aside. Never a joke per
34-paragraph; humor is seasoning. Plain, short sentences.
35-
36-## Mascot: Razmataz
37-A small, very serious creature with a flashy name, which suits a frugal
38-compiler (razzmatazz minus one z).
39-- Its motto, "once is enough", plays on "raz" meaning "one" or "once" in
40- Polish and Russian. Check that the compiler really works in one pass
41- before leaning on this; if it doesn't, find the honest version of the
42- joke.
43-- Razmataz appears in tiza drawings: eating characters in the scanner,
44- stacking boxes in frames, throwing unused code overboard in linking.
45-
46-## Structure
47-Build up gradually, not unit by unit:
48-1. Introduction and a whirlwind tour: compile `exit 42` (or the smallest
49- real program) through every stage, shallowly.
50-2. Enough Pascal (and raz) to follow along.
51-3. One chapter per language feature, followed through scanner, parser,
52- symbols, code generator and machine code: variables and expressions,
53- control flow, procedures and frames, records and arrays, pointers and
54- the heap, strings, modules, defer, C interop, threads.
55-4. Closing chapters: x64 encoding, link (tree shaking, layout), elf,
56- speed (how it reaches 400k lines a second), and where to go next.
57-
58-Refine this order in the outline (step 1).
59-
60-## Format and tooling
61-- Markdown in doc/book/: NN-slug.md per chapter, plus metadata.yaml
62- (title, author Luis, cover). It must read well as plain text.
63-- `make book` builds build/compiling-raz.epub with pandoc. If pandoc gets
64- installed locally, update the desktop guide (see the global
65- CLAUDE.md).
66-- Drawings: .tiza source and a rendered PNG, both committed (CI has no
67- tiza). Every image has a caption that stands on its own in plain text.
68- Use ASCII art in code blocks for diagrams that are really structure
69- (frames, memory layout); those read the same in both formats.
70-- Disassembly is cleaned up: instructions only, the raz source line
71- beside them as a comment, and bytes only where the bytes are the point.
72- Show raw objdump output once, early, next to the cleaned version, and
73- say how to get it.
74-- A checker, written in raz alongside tools/Doc.raz (reuse what exists),
75- run by `make check`. It must:
76- - compile and run every raz example marked as runnable and compare the
77- expected output written in the book;
78- - confirm every quoted Pascal excerpt still matches src/, quoted by
79- unit and routine name, never by line number;
80- - regenerate or verify the cleaned disassembly.
81- The goal: when the compiler changes, `make check` fails rather than
82- the book going quietly wrong.
83-- CI (.github/workflows/): on a push to main that touches doc/book/**,
84- src/** or lib/**, build the epub and replace the file on a standing
85- prerelease tagged `book` (gh release upload --clobber), so the owner
86- has a fixed URL to open on an iPad. Tagged releases also attach that
87- version's epub.
88-
89-## Steps (each one is a commit, then stop for review)
90-1. The outline: doc/book/OUTLINE.md, chapter by chapter, with what each
91- one teaches, its running example, and the drawings planned.
92-2. The tooling: doc/book/ skeleton, `make book`, the checker in
93- `make check`, the CI job. One placeholder chapter proves the pipeline
94- end to end.
95-3. Razmataz's design sheet (tiza) and one sample chapter, the procedures
96- and frames one, to set tone and depth.
97-4. Then one chapter per step, in order.
98-
99-doc/compiler.md stays as it is: the short guide for people changing the
100-compiler. The book can point to it but never replaces it.
101-
102-## Left to the tooling step
103-- How the checker marks runnable examples and quoted excerpts inside
104- Markdown.
105-- Whether the cleaned disassembly comes from the compiler's own line
106- information (`make gdb` suggests it has some) or from objdump.

doc/compiler.md (history) modified +5 -1

@@ -504,7 +504,11 @@
504504 place with the highest address up to the one it has. Then it follows
505505 the chain of frames, each `rbp` pointing at its caller's, and says
506506 each call under way and its variables (`calls`); `Rt.trace` does the
507-same on demand. A thread's first frame has `rbp` zero, which ends it. Its signal
507+same on demand. A thread's first frame has `rbp` zero, which ends it.
508+With `RAZ_PROFILE` set, `Rt`'s body has the kernel send SIGPROF every
509+millisecond of the program's time (`setitimer`); `onProf` notes the
510+address it interrupted, and `exit` has `profile` say which procedures
511+and places those fell in, by the same tables. Its signal
508512 handlers, set in its body, run on a stack of their own, so that they
509513 can tell a stack overflow, and leave by returning to the faulting
510514 instruction with the handler reset, so that the signal ends the

lib/Rt.raz (history) modified +107 -1

@@ -5,7 +5,9 @@
55 The compiler finds fail, exit, cExit and places by these names.
66 After a failed check or a signal, and on demand with trace, Rt says
77 the calls under way and their variables, from the frames' chain of
8- rbp and the compiler's tables in places.
8+ rbp and the compiler's tables in places. A program run with
9+ RAZ_PROFILE set is sampled every millisecond of its time, and at its
10+ end Rt says which procedures and places in the source took it.
911 The handlers are Linux's on x86-64, set by system calls: what the
1012 kernel hands them is laid out as it is there. *)
1113 module Rt;
@@ -18,6 +20,13 @@
1820 SigSegv = 11;
1921 Low = 10000H; (* no address below this is ever mapped *)
2022 Digits = "0123456789abcdef";
23+ SigProf = 27;
24+ (* SA_SIGINFO, SA_ONSTACK, SA_RESTORER and SA_RESTART, so that a
25+ system call a sample interrupts goes on *)
26+ ProfFlags = 4H + 8000000H + 4000000H + 10000000H;
27+ MaxSamples = 100000;
28+ MaxProcs = 8192;
29+ MaxPlaces = 65536;
2130 (* SA_SIGINFO, SA_ONSTACK, SA_RESTORER and SA_RESETHAND *)
2231 Flags = 4H + 8000000H + 4000000H + 80000000H;
2332
@@ -56,6 +65,14 @@
5665 act: Action;
5766 alt: Stack;
5867 altStack: [16384]U8; (* where the handlers run, even when the stack is full *)
68+ (* the profile: where the program was at each sample, and how many
69+ samples fell in each procedure and at each place *)
70+ samples: [MaxSamples]UINT;
71+ numSamples: INT;
72+ profiling: BOOL;
73+ procCount: [MaxProcs]INT;
74+ placeCount: [MaxPlaces]INT;
75+ timerv: [4]INT; (* setitimer's interval and value *)
5976
6077 (* Registers p to run when the program ends by exit. *)
6178 proc atExit*(p: proc): ERROR;
@@ -65,6 +82,8 @@
6582 INC(numAtExit);
6683 return nil;
6784 end;
85+
86+proc profile; forward;
6887
6988 (* Runs the procedures registered with atExit, the last first, then
7089 ends the program with status: through C's exit in a program that
@@ -79,6 +98,7 @@
7998 p := atExits[numAtExit];
8099 p();
81100 end;
101+ if profiling then profile; end;
82102 if cExit # nil then cExit(I32(status)); end;
83103 Sys.exit(status);
84104 end;
@@ -383,10 +403,96 @@
383403 calls(ip, bp, why # "a stack overflow");
384404 end;
385405
406+(* SIGPROF, every millisecond the program runs, in any of its threads:
407+ notes where it was *)
408+proc onProf(_sig: INT; _info, ctx: ^U8);
409+var n: INT; q: ^UINT;
386410 begin
411+ n := XADD(ADR(numSamples), 1);
412+ q := ^UINT(ctx + 168); (* uc_mcontext's rip *)
413+ if n < MaxSamples then samples[n] := q^; end;
414+end;
415+
416+(* The index of the place the code at address a comes from, or -1 *)
417+proc placeAt(a: UINT): INT;
418+var p: ^Place; i, best: INT;
419+begin
420+ best := -1;
421+ p := ^Place(places + 5);
422+ for i := 0 to places[0] - 1 do
423+ if (UINT(p[i].at) <= a) and ((best < 0) or (p[i].at > p[best].at)) then best := i; end;
424+ end;
425+ return best;
426+end;
427+
428+(* Says the ten that took most of count's n samples, by name *)
429+proc top(count: []INT; n: INT; byPlace: BOOL);
430+var i, k, best: INT; p: ^Proc; q: ^Place;
431+begin
432+ p := ^Proc(^U8(places + 5) + 16 * places[0]);
433+ q := ^Place(places + 5);
434+ for k := 1 to 10 do
435+ best := 0;
436+ for i := 1 to LEN(count) - 1 do
437+ if count[i] > count[best] then best := i; end;
438+ end;
439+ if count[best] = 0 then return; end;
440+ i := count[best] * 100 div n;
441+ if i < 10 then put(" "); elsif i < 100 then put(" "); else put(" "); end;
442+ putInt(i);
443+ put("% ");
444+ if byPlace then
445+ putStr(names() + INT(q[best].path));
446+ put(":"); putInt(INT(q[best].line));
447+ put(":"); putInt(INT(q[best].col));
448+ else putStr(names() + INT(p[best].name));
449+ end;
450+ say;
451+ count[best] := 0;
452+ end;
453+end;
454+
455+(* At the end of a profiled run: which procedures, and which places in
456+ the source, took the time, as shares of the samples *)
457+proc profile;
458+var t: [4]INT; i, n, k: INT; p: ^Proc;
459+begin
460+ t := [0, 0, 0, 0];
461+ SYSCALL(38, 2, ADR(t), 0); (* setitimer(ITIMER_PROF): no more *)
462+ profiling := false;
463+ n := numSamples;
464+ if n > MaxSamples then n := MaxSamples; end;
465+ if (places = nil) or (n = 0) then return; end;
466+ for i := 0 to n - 1 do
467+ p := procAt(samples[i]);
468+ if p # nil then
469+ k := (p - ^Proc(^U8(places + 5) + 16 * places[0]));
470+ if k < MaxProcs then INC(procCount[k]); end;
471+ end;
472+ k := placeAt(samples[i]);
473+ if (k >= 0) and (k < MaxPlaces) then INC(placeCount[k]); end;
474+ end;
475+ put("profile: ");
476+ putInt(n);
477+ put(" samples of a millisecond");
478+ say;
479+ top(procCount[0..places[3]], n, false);
480+ put("by place:");
481+ say;
482+ top(placeCount[0..places[0]], n, true);
483+end;
484+
485+begin
387486 alt := {sp: ADR(altStack[0]), size: LEN(altStack)};
388487 SYSCALL(131, ADR(alt), 0); (* sigaltstack *)
389488 act := {handler: onSignal, flags: Flags, restorer: sigReturn};
390489 SYSCALL(13, SigSegv, ADR(act), 0, 8); (* rt_sigaction *)
391490 SYSCALL(13, SigFpe, ADR(act), 0, 8);
491+ if LEN(Sys.env("RAZ_PROFILE")) > 0 then
492+ act := {handler: onProf, flags: ProfFlags, restorer: sigReturn};
493+ SYSCALL(13, SigProf, ADR(act), 0, 8);
494+ timerv := [0, 1000, 0, 1000]; (* every millisecond, from one on *)
495+ SYSCALL(38, 2, ADR(timerv), 0); (* setitimer(ITIMER_PROF) *)
496+ profiling := true;
497+ end;
392498 end Rt.

test/check.sh (history) modified +6 -0

@@ -94,9 +94,15 @@
9494 pass=$((pass + 1))
9595 fi
9696 done
97+# RAZ_PROFILE: a profiled run says which procedure took its time
98+$raz -o $out/Busy test/list/Busy.raz
99+if RAZ_PROFILE=1 $out/Busy 2>&1 >/dev/null | sed -n 2p | grep -q 'Busy.spin$'; then pass=$((pass + 1))
100+else echo "FAIL RAZ_PROFILE: Busy.spin isn't first"; fail=$((fail + 1)); fi
101+
97102 # raz -S: test/list/X.raz lists as X.expect
98103 for f in test/list/*.raz; do
99104 want=test/list/$(basename $f .raz).expect
105+ [ -f $want ] || continue
100106 if $raz -S $f 2>&1 | cmp -s $want -; then pass=$((pass + 1))
101107 else echo "FAIL raz -S $f"; $raz -S $f 2>&1 | diff $want - | head; fail=$((fail + 1)); fi
102108 done

test/list/Busy.raz (history) added +18 -0

@@ -0,0 +1,18 @@
1+module Busy;
2+(* Profiled by test/check.sh, with RAZ_PROFILE set: spin takes nearly
3+ all its time. Not listed, having no .expect. *)
4+import Out;
5+
6+proc spin(n: I64): I64;
7+var i, s: I64;
8+begin
9+ for i := 1 to n do s := s + i * i mod 7; end;
10+ return s;
11+end;
12+
13+proc main*;
14+begin
15+ Out.int(spin(100000000)); Out.ln;
16+end;
17+
18+end Busy.