| | @@ -0,0 +1,351 @@ |
| 1 | +# Reading the jed compiler |
| 2 | + |
| 3 | +The compiler is eight files of Free Pascal, under 5,000 lines of code. |
| 4 | +This guide walks through them in the order they are best read: from the |
| 5 | +characters of a source file to the bytes of an executable. It assumes |
| 6 | +you know the language from `doc/jed.md`, and enough x86-64 to read a |
| 7 | +disassembly. |
| 8 | + |
| 9 | +| File | Lines | Code | What | |
| 10 | +|---|---|---|---| |
| 11 | +| `src/scan.pas` | 548 | 471 | Symbols, literals, comments, error messages | |
| 12 | +| `src/sym.pas` | 508 | 422 | Types, objects, scopes, layout | |
| 13 | +| `src/x64.pas` | 680 | 546 | Code buffer, chunks, fixups, line notes, instruction encoder | |
| 14 | +| `src/gen.pas` | 1,414 | 1,240 | Items: loading, storing, copying, frames, calls | |
| 15 | +| `src/parse.pas` | 1,816 | 1,685 | Declarations, statements, expressions, built-ins | |
| 16 | +| `src/link.pas` | 131 | 95 | Tree shaking, layout, patching | |
| 17 | +| `src/elf.pas` | 425 | 351 | Static and dynamic ELF, symbol table, line numbers | |
| 18 | +| `src/jed.pas` | 191 | 151 | The command line, the entry points | |
| 19 | + |
| 20 | +Every file opens with a comment that says what it is, what it depends |
| 21 | +on and what it leaves out. Read those first; they are the map. |
| 22 | + |
| 23 | +## The shape of it |
| 24 | + |
| 25 | +There is one pass and no tree. The parser reads a construct and, in |
| 26 | +the same breath, has the code generator emit its machine code. Nothing |
| 27 | +is kept to be looked at again, except the declarations, which live in |
| 28 | +the symbol table for as long as the compiler runs. |
| 29 | + |
| 30 | +The code generator is a stack machine through `rax`. An expression's |
| 31 | +value is computed into `rax`; when a second operand has to be computed, |
| 32 | +the first is pushed, and popped into `rcx` when both are ready. No |
| 33 | +register is ever allocated, so there is no register allocator, and |
| 34 | +every access the program writes is one instruction, in the order |
| 35 | +written. That is also why `VOLATILE` costs the compiler nothing: it |
| 36 | +never does anything clever to begin with. |
| 37 | + |
| 38 | +The output is a set of *chunks*: one for each procedure, each module |
| 39 | +variable, each string. Code refers to other chunks through *fixups*, |
| 40 | +which aren't resolved until the end. When everything is compiled, the |
| 41 | +linker marks the chunks the entry point can reach, gives each an |
| 42 | +address, patches the fixups, and the ELF writer puts them in a file. |
| 43 | +Whatever nothing reaches never makes it into the executable. |
| 44 | + |
| 45 | +All modules are compiled in one run, from source: there are no object |
| 46 | +files, no symbol files, and nothing to keep up to date. |
| 47 | + |
| 48 | +## Following one program |
| 49 | + |
| 50 | +`jed Hello.jed` does this: |
| 51 | + |
| 52 | +1. `jed.pas` reads the command line and calls `CompileMain` |
| 53 | + (`parse.pas`). |
| 54 | +2. `CompileMain` imports `Rt` first, since every program needs it, and |
| 55 | + then compiles `Hello.jed` with `CompileFile`. |
| 56 | +3. `CompileFile` opens the file in the scanner and parses the module. |
| 57 | + At `import Out;` it calls `ImportModule`, which finds `Out.jed` and |
| 58 | + compiles it there and then, saving and restoring the scanner and the |
| 59 | + scopes around it. So modules are finished in an order where each |
| 60 | + comes after those it imports; that is the order their bodies run. |
| 61 | +4. Each procedure becomes a chunk of code; `Out.str("hello, world\n")` |
| 62 | + becomes a string chunk, a call, and a fixup to `Out.str`'s chunk. |
| 63 | +5. Back in `jed.pas`, `Use` marks the modules the program uses; the |
| 64 | + entry point, `_start`, is written as one more chunk: save `argc` and |
| 65 | + `argv`, call every used module's body, call `main`, call `Rt.exit`. |
| 66 | +6. `WriteElf` (`elf.pas`) has `link.pas` mark what `_start` reaches, |
| 67 | + place it and patch it, then writes headers, code, data, symbols and |
| 68 | + line numbers. |
| 69 | + |
| 70 | +## A procedure, compiled |
| 71 | + |
| 72 | +``` |
| 73 | +proc scale(a, b: I64): I64; |
| 74 | +begin |
| 75 | + return a + b * 2; |
| 76 | +end; |
| 77 | +``` |
| 78 | + |
| 79 | +comes out as this (from `objdump -d -M intel`): |
| 80 | + |
| 81 | +``` |
| 82 | +push rbp ; EnterBody: the frame |
| 83 | +mov rbp,rsp |
| 84 | +sub rsp,0x10 ; its size, patched in by EndProc |
| 85 | +mov r10,0xfffffffffffffffe ; zero the frame, a quadword at a |
| 86 | +xor eax,eax ; time, r10 counting up to zero |
| 87 | +mov QWORD PTR [rbp+r10*8+0x0],rax |
| 88 | +add r10,0x1 |
| 89 | +jne <back to the mov> |
| 90 | +mov QWORD PTR [rbp-0x8],rdi ; the parameters, into their slots |
| 91 | +mov QWORD PTR [rbp-0x10],rsi |
| 92 | +mov rax,QWORD PTR [rbp-0x8] ; a |
| 93 | +push rax ; kept while b * 2 is computed |
| 94 | +mov rax,QWORD PTR [rbp-0x10] ; b |
| 95 | +push rax ; kept while 2 is read |
| 96 | +pop rax |
| 97 | +mov ecx,0x2 ; the constant goes straight to rcx |
| 98 | +imul rax,rcx |
| 99 | +mov rcx,rax |
| 100 | +pop rax ; a again |
| 101 | +add rax,rcx |
| 102 | +jmp <leave> ; return |
| 103 | +xor eax,eax ; running off the end returns zero |
| 104 | +movq xmm0,rax |
| 105 | +leave |
| 106 | +ret |
| 107 | +``` |
| 108 | + |
| 109 | +Every line of it can be traced to a routine in `gen.pas`; the pushes |
| 110 | +and pops are `Op1` and `Op2`, the frame `EnterBody` and `EndProc`. It |
| 111 | +is not fast code. It is code whose every instruction you can account |
| 112 | +for, which is the point. |
| 113 | + |
| 114 | +## scan.pas: the scanner |
| 115 | + |
| 116 | +The scanner turns bytes into symbols (`TSym`). The current symbol is in |
| 117 | +`tok`, with its value in `ival` (integers and characters), `rval` |
| 118 | +(reals), `id` (identifiers) or `sbuf` and `slen` (strings, already |
| 119 | +decoded). |
| 120 | + |
| 121 | +Read `Next` first: it skips white space and comments (`Comment`, which |
| 122 | +counts nesting), then dispatches on the first character. `Number` |
| 123 | +handles decimal, `0FFH`-style hexadecimal and reals; `LitChar` handles |
| 124 | +one character of a literal, escapes included. |
| 125 | + |
| 126 | +Identifiers are *interned*: `Intern` puts each distinct name once in a |
| 127 | +pool and hands back a small integer, so every later comparison of names |
| 128 | +is a comparison of integers. The reserved words are interned first, in |
| 129 | +the order of `TSym`, so a name's number tells at once whether it is a |
| 130 | +reserved word. |
| 131 | + |
| 132 | +Source is UTF-8, checked by `Utf8` wherever a byte above 127 appears: |
| 133 | +in strings, characters and comments. Anywhere else it is an error. |
| 134 | + |
| 135 | +Errors go through `Mark`, which prints `file:line:column` (the column |
| 136 | +counted in characters, by `Column`) and stops. There is no recovery: |
| 137 | +the first error ends the compilation. `SaveScan` and `RestoreScan` keep |
| 138 | +the scanner's state while an imported module is compiled. |
| 139 | + |
| 140 | +## sym.pas: types, objects and scopes |
| 141 | + |
| 142 | +Two records hold everything the compiler knows about a program. |
| 143 | + |
| 144 | +`TType` is a type. Its `form` says what kind (`fInt`, `fPtr`, `fArray`, |
| 145 | +`fRecord`, `fVariant`, `fProc`, and so on), and the other fields mean |
| 146 | +what that form needs: `base` is what a pointer points at, an array or |
| 147 | +slice holds, or a procedure returns; `fields` lists a record's fields, |
| 148 | +a variant's cases, a procedure's parameters; `len` counts an array's |
| 149 | +elements. `size` and `align` are worked out when the type is built, by |
| 150 | +the C rules. `obj` is the declaration that named the type, if any. |
| 151 | + |
| 152 | +`TObj` is anything a name can stand for: a constant, type, variable, |
| 153 | +procedure, module, field, variant case or built-in (`cls`). Where it |
| 154 | +lives is decided here too: a module variable's chunk, a local's frame |
| 155 | +offset in `val`, a procedure's chunk. |
| 156 | + |
| 157 | +Scopes are numbers. The universe is 0; each module, procedure, record |
| 158 | +and match arm gets a new one from `NewScope`. All objects of all scopes |
| 159 | +sit in one open-addressed hash table, keyed by scope and name: `Find` |
| 160 | +looks in one scope, `Lookup` in each open scope from the innermost out. |
| 161 | +A lookup costs the same however big a program grows, which matters at |
| 162 | +a million lines a second. |
| 163 | + |
| 164 | +`Same` and `Alike` decide whether two types are the same: one |
| 165 | +declaration for named types, built alike otherwise. `Fingerprint` |
| 166 | +hashes what a declaration exports, for the check that a module's files |
| 167 | +for different targets agree. The universe, the basic types and built-in |
| 168 | +procedures, is set up in the unit's `initialization`. |
| 169 | + |
| 170 | +## x64.pas: machine code |
| 171 | + |
| 172 | +Code is written into one growing buffer, `code`, with `pc` its length; |
| 173 | +strings go to `rodata`. A chunk (`TChunk`) records its section, where |
| 174 | +its bytes start, how many, and the fixups it makes. `BeginChunk` and |
| 175 | +`EndChunk` bracket a procedure; `SetData` and `SetBss` make data |
| 176 | +chunks. |
| 177 | + |
| 178 | +A *fixup* (`TFixup`) is a 32-bit field in the code that will hold the |
| 179 | +distance to another chunk: a call's target, or a rip-relative address. |
| 180 | +`AddFixup` records one; `link.pas` fills them in. |
| 181 | + |
| 182 | +Jumps within a procedure don't wait for the linker. A label not yet |
| 183 | +placed is a chain of the jumps to it, each jump's 32-bit field holding |
| 184 | +the position of the one before (`Jmp`, `Jcc`); `FixLink` walks the |
| 185 | +chain and patches each once the label's position is known. This is the |
| 186 | +trick from Wirth's compilers, and it means a label is one integer. |
| 187 | + |
| 188 | +The encoder is `OpM` and `OpR`: a prefix, the REX byte, the opcode, the |
| 189 | +ModRM and SIB bytes and the displacement, for a register and a memory |
| 190 | +operand (`TMem`) or two registers. Everything else (`MovRR`, `Load`, |
| 191 | +`Store`, `Alu`, `Sse`, ...) is a line or two that calls them with the |
| 192 | +right opcode. Only the instructions the code generator uses are here. |
| 193 | +`test/enctest.pas` emits one of each for `objdump` to check. |
| 194 | + |
| 195 | +Two more things live here because they are tied to code positions: |
| 196 | +`NoteLine` records which source line the code from `pc` on belongs to, |
| 197 | +for gdb; `ExternChunk` makes, once per C symbol, the quadword the |
| 198 | +dynamic loader will fill with that symbol's address. |
| 199 | + |
| 200 | +## gen.pas: the code generator |
| 201 | + |
| 202 | +This is the heart, and the file to read slowly. |
| 203 | + |
| 204 | +An operand is an *item* (`TItem`), as in Wirth's compilers. Its `mode` |
| 205 | +says what it is now: |
| 206 | + |
| 207 | +- `mConst`: a value known to the compiler, in `val`; |
| 208 | +- `mVar`: a variable at an address the code can name: relative to |
| 209 | + `rbp` (`bFrame`), to a chunk (`bGlobal`), to a register (`bReg`), to |
| 210 | + an address pushed on the stack (`bStack`), or kept in a frame slot |
| 211 | + (`bSlot`); plus `off`; |
| 212 | +- `mReg`: a value in `rax`; `mStack`: a value pushed on the stack; |
| 213 | +- `mProc`, `mType`, `mStr`, and a few more the parser needs. |
| 214 | + |
| 215 | +Three routines move items towards the machine. `Value` brings a value |
| 216 | +into `rax`, loading it with the one instruction its size needs. |
| 217 | +`Address` brings a variable's address into a register. `Save` pushes |
| 218 | +whatever an item has in a register, so that another expression can be |
| 219 | +computed; the item remembers that it's on the stack. Read these three, |
| 220 | +then `MemOf`, which turns an `mVar` into an x64 memory operand, popping |
| 221 | +its address first if it was pushed. |
| 222 | + |
| 223 | +Expressions: `Op1` is called when the parser has seen an operator and |
| 224 | +its left operand, `Op2` when it has the right one. `Op1` saves the left |
| 225 | +operand (or, for `and` and `or`, emits the test that skips the right |
| 226 | +one). `Op2` checks the types, folds constants (`FoldInt`, `FoldReal`), |
| 227 | +and otherwise puts the left operand in `rax`, the right in `rcx`, and |
| 228 | +emits the operation. Narrow integers are brought back to their width |
| 229 | +after each operation (`Norm`), which is how `U8` arithmetic wraps. |
| 230 | + |
| 231 | +Variables: `Deref`, `Field`, `Index` and `Slice` turn an item for a |
| 232 | +variable into an item for part of it, mostly by adding to `off`. |
| 233 | +`Index` and `Slice` emit the bounds checks; `Check` jumps over a call |
| 234 | +to `Rt.fail` with the file and line when the check holds. |
| 235 | + |
| 236 | +Assignment and conversion: `Coerce` makes a value fit the type it's |
| 237 | +going to, or reports that it can't; it's where a string literal becomes |
| 238 | +a slice, an array a slice, an untyped constant a typed one. `Assign` |
| 239 | +stores, copying records and arrays with `rep movsb`. `Convert` is the |
| 240 | +written conversion, `T(x)`. |
| 241 | + |
| 242 | +Calls: `BeginCall`, then `PassArg` for each argument, then `EndCall`. |
| 243 | +Each argument is computed into a frame slot of its own, left to right; |
| 244 | +only in `EndCall` are they loaded into the registers System V wants, |
| 245 | +and the stack aligned for the call. A record passed by value goes as |
| 246 | +the address of a copy; one returned comes back through a hidden pointer |
| 247 | +in `rdi`, as C's structs do, and so do several results. |
| 248 | + |
| 249 | +Frames: `BeginProc` gives the parameters their slots; `EnterBody` |
| 250 | +writes the prologue, including the loop that zeroes the frame; |
| 251 | +`EndProc` writes the epilogue and patches the frame's size in. Within |
| 252 | +a statement, scratch space comes from `AllocTemp` and is given back by |
| 253 | +`ReleaseTemps`; `AllocPerm` reserves space for the whole procedure. |
| 254 | + |
| 255 | +## parse.pas: the parser |
| 256 | + |
| 257 | +A recursive descent parser, one routine for each rule of the grammar in |
| 258 | +the report, calling `gen.pas` as it goes. |
| 259 | + |
| 260 | +Start with expressions, bottom up: `Factor`, `Term`, `SimpleExpr`, |
| 261 | +`Expression`. Then `Designator`, which reads a name and what follows |
| 262 | +it: `.field`, `^`, `[i]`, `[lo..hi]`, a call, a conversion. Each step |
| 263 | +calls the matching routine in `gen.pas` on the item it has. The |
| 264 | +`want` parameter carries the type an expression must have, where it is |
| 265 | +known, so that `[1, 2, 3]`, `{x: 1}` and `{red}` know what to build. |
| 266 | + |
| 267 | +Then statements: `Statement` dispatches; `IfStatement`, |
| 268 | +`WhileStatement`, `ForStatement` and `MatchStatement` emit their jumps |
| 269 | +with `x64.pas`'s labels. `Defer` is worth reading: a deferred statement |
| 270 | +is compiled where it stands, as a little subroutine of the procedure |
| 271 | +that the code jumps over, and `RunDefers` emits a call to it at every |
| 272 | +way out of its statement list: the end, `return` and `break`. |
| 273 | + |
| 274 | +Then declarations: `Declarations` reads `const`, `type`, `var`, `proc` |
| 275 | +and `extern`. `ProcDecl` handles forward declarations, code procedures |
| 276 | +(`CodeBody`, which just copies the bytes) and bodies (`Body`). |
| 277 | +`ParseType` and its helpers (`RecordType`, `VariantType`, `Signature`, |
| 278 | +`EnumType`) build `TType`s. |
| 279 | + |
| 280 | +Last, modules, at the end of the file. `CompileFile` reads one module. |
| 281 | +`ImportModule` finds a module's file, trying the target's names first, |
| 282 | +and compiles it if it isn't yet; `CheckSiblings` then reads the files |
| 283 | +for other targets beside it, declarations only, and `CompareIface` |
| 284 | +holds them to the same exports by their fingerprints. A generic module |
| 285 | +is compiled once per distinct list of arguments: `ParseArgs` reads |
| 286 | +them at the import, `Params` binds them to the module's parameters, and |
| 287 | +`IsModule` decides whether an instance already exists. |
| 288 | + |
| 289 | +The built-in procedures are in `Builtin` (and `New_`, `Atomic`): each |
| 290 | +parses its own arguments, since `SIZE` takes a type and `INC` a |
| 291 | +variable. |
| 292 | + |
| 293 | +## link.pas: tree shaking and layout |
| 294 | + |
| 295 | +`MarkLive` starts from the entry chunk and follows fixups, marking each |
| 296 | +chunk it reaches; nothing else goes into the executable. `LinkAll` |
| 297 | +places the live chunks section by section (`Place`), each at its |
| 298 | +alignment, then copies their bytes into the images of text and rodata, |
| 299 | +patching every fixup with the distance from the end of its field to its |
| 300 | +target. |
| 301 | + |
| 302 | +The layout is chosen so the file can be mapped as it lies: text just |
| 303 | +after the headers, rodata on the next page, then a writable page that |
| 304 | +begins with the dynamic loader's table (in a program that uses C) and |
| 305 | +goes on as bss. |
| 306 | + |
| 307 | +## elf.pas: the executable |
| 308 | + |
| 309 | +`WriteElf` writes the ELF header, the program headers, the text and |
| 310 | +rodata images, and then what isn't loaded: section headers, a symbol |
| 311 | +table with every live procedure and variable by `Module.name`, and the |
| 312 | +line table. |
| 313 | + |
| 314 | +A program that uses C is linked dynamically, in the least way the |
| 315 | +loader accepts: an interpreter header naming the loader; a dynamic |
| 316 | +section naming the libraries; and, for each C symbol the program uses, |
| 317 | +a symbol and a `GLOB_DAT` relocation that has the loader write the |
| 318 | +symbol's address into the quadword `ExternChunk` made. Code calls C |
| 319 | +through that quadword. There is no PLT and no lazy binding. |
| 320 | +`SizeTables` and `PutTables` lay these out in the room `link.pas` left |
| 321 | +at the end of rodata. |
| 322 | + |
| 323 | +Line numbers are DWARF 4: `PutDebug` writes a line table with one |
| 324 | +sequence per procedure, from the notes `NoteLine` made, and the single |
| 325 | +compile unit gdb needs to find it. There are no types or variables in |
| 326 | +it; gdb can stop at a line and show where it is, not print a variable. |
| 327 | + |
| 328 | +## jed.pas: the command line |
| 329 | + |
| 330 | +`jed.pas` parses the arguments, calls `CompileMain`, and works out what |
| 331 | +the program uses: `Use` marks the modules imported from the main module |
| 332 | +and `Rt`; `UsesC` decides whether the program is dynamic, refusing one |
| 333 | +that both uses C and has a module saying `link static`. Then it writes |
| 334 | +the entry point. A static program starts at `_start` itself. A dynamic |
| 335 | +one starts at a `_start` that calls `__libc_start_main` the way C's own |
| 336 | +start-up does, which sets C up and calls back a `main` that runs the |
| 337 | +module bodies and the program's `main`. |
| 338 | + |
| 339 | +## Where to start changing it |
| 340 | + |
| 341 | +- **A built-in procedure:** an entry in `sym.pas`'s universe, a case in |
| 342 | + `Builtin` in `parse.pas`, and the code, in `gen.pas` or right there. |
| 343 | +- **An instruction:** a routine in `x64.pas` built on `OpM` or `OpR`, |
| 344 | + and a line in `test/enctest.pas` to check its encoding. |
| 345 | +- **A statement:** a reserved word in `scan.pas` (in `TSym` and `Words`, |
| 346 | + in the same order), a case in `Statement`, and a routine beside the |
| 347 | + others. |
| 348 | +- **A check that fails:** `Check` in `gen.pas`, and the message in |
| 349 | + `lib/Rt.jed`'s `fail`. |
| 350 | + |
| 351 | +After any change: `make check`, `make bench`, `make loc`. |