Merge remote-tracking branch 'origin/stable-2.0'
[bpt/guile.git] / module / system / vm / assembler.scm
1 ;;; Guile RTL assembler
2
3 ;;; Copyright (C) 2001, 2009, 2010, 2012, 2013 Free Software Foundation, Inc.
4 ;;;
5 ;;; This library is free software; you can redistribute it and/or
6 ;;; modify it under the terms of the GNU Lesser General Public
7 ;;; License as published by the Free Software Foundation; either
8 ;;; version 3 of the License, or (at your option) any later version.
9 ;;;
10 ;;; This library is distributed in the hope that it will be useful,
11 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;; Lesser General Public License for more details.
14 ;;;
15 ;;; You should have received a copy of the GNU Lesser General Public
16 ;;; License along with this library; if not, write to the Free Software
17 ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 ;;; Commentary:
20 ;;;
21 ;;; This module implements an assembler that creates an ELF image from
22 ;;; RTL assembly and macro-assembly. The input can be given in
23 ;;; s-expression form, like ((OP ARG ...) ...). Internally there is a
24 ;;; procedural interface, the emit-OP procedures, but that is not
25 ;;; currently exported.
26 ;;;
27 ;;; "Primitive instructions" correspond to RTL VM operations.
28 ;;; Assemblers for primitive instructions are generated programmatically
29 ;;; from (rtl-instruction-list), which itself is derived from the VM
30 ;;; sources. There are also "macro-instructions" like "label" or
31 ;;; "load-constant" that expand to 0 or more primitive instructions.
32 ;;;
33 ;;; The assembler also handles some higher-level tasks, like creating
34 ;;; the symbol table, other metadata sections, creating a constant table
35 ;;; for the whole compilation unit, and writing the dynamic section of
36 ;;; the ELF file along with the appropriate initialization routines.
37 ;;;
38 ;;; Most compilers will want to use the trio of make-assembler,
39 ;;; emit-text, and link-assembly. That will result in the creation of
40 ;;; an ELF image as a bytevector, which can then be loaded using
41 ;;; load-thunk-from-memory, or written to disk as a .go file.
42 ;;;
43 ;;; Code:
44
45 (define-module (system vm assembler)
46 #:use-module (system base target)
47 #:use-module (system vm instruction)
48 #:use-module (system vm elf)
49 #:use-module (system vm linker)
50 #:use-module (system vm objcode)
51 #:use-module (rnrs bytevectors)
52 #:use-module (ice-9 vlist)
53 #:use-module (ice-9 match)
54 #:use-module (srfi srfi-1)
55 #:use-module (srfi srfi-4)
56 #:use-module (srfi srfi-9)
57 #:use-module (srfi srfi-11)
58 #:export (make-assembler
59 emit-text
60 link-assembly
61 assemble-program))
62
63
64 \f
65
66 ;;; RTL code consists of 32-bit units, often subdivided in some way.
67 ;;; These helpers create one 32-bit unit from multiple components.
68
69 (define-syntax-rule (pack-u8-u24 x y)
70 (logior x (ash y 8)))
71
72 (define-syntax-rule (pack-u8-s24 x y)
73 (logior x (ash (cond
74 ((< 0 (- y) #x800000)
75 (+ y #x1000000))
76 ((<= 0 y #xffffff)
77 y)
78 (else (error "out of range" y)))
79 8)))
80
81 (define-syntax-rule (pack-u1-u7-u24 x y z)
82 (logior x (ash y 1) (ash z 8)))
83
84 (define-syntax-rule (pack-u8-u12-u12 x y z)
85 (logior x (ash y 8) (ash z 20)))
86
87 (define-syntax-rule (pack-u8-u8-u16 x y z)
88 (logior x (ash y 8) (ash z 16)))
89
90 (define-syntax-rule (pack-u8-u8-u8-u8 x y z w)
91 (logior x (ash y 8) (ash z 16) (ash w 24)))
92
93 (define-syntax pack-flags
94 (syntax-rules ()
95 ;; Add clauses as needed.
96 ((pack-flags f1 f2) (logior (if f1 (ash 1 0) 0)
97 (if f2 (ash 2 0) 0)))))
98
99 ;;; Helpers to read and write 32-bit units in a buffer.
100
101 (define-syntax-rule (u32-ref buf n)
102 (bytevector-u32-native-ref buf (* n 4)))
103
104 (define-syntax-rule (u32-set! buf n val)
105 (bytevector-u32-native-set! buf (* n 4) val))
106
107 (define-syntax-rule (s32-ref buf n)
108 (bytevector-s32-native-ref buf (* n 4)))
109
110 (define-syntax-rule (s32-set! buf n val)
111 (bytevector-s32-native-set! buf (* n 4) val))
112
113
114 \f
115
116 ;;; A <meta> entry collects metadata for one procedure. Procedures are
117 ;;; written as contiguous ranges of RTL code.
118 ;;;
119 (define-syntax-rule (assert-match arg pattern kind)
120 (let ((x arg))
121 (unless (match x (pattern #t) (_ #f))
122 (error (string-append "expected " kind) x))))
123
124 (define-record-type <meta>
125 (%make-meta label properties low-pc high-pc arities)
126 meta?
127 (label meta-label)
128 (properties meta-properties set-meta-properties!)
129 (low-pc meta-low-pc)
130 (high-pc meta-high-pc set-meta-high-pc!)
131 (arities meta-arities set-meta-arities!))
132
133 (define (make-meta label properties low-pc)
134 (assert-match label (? symbol?) "symbol")
135 (assert-match properties (((? symbol?) . _) ...) "alist with symbolic keys")
136 (%make-meta label properties low-pc #f '()))
137
138 (define (meta-name meta)
139 (assq-ref (meta-properties meta) 'name))
140
141 ;; Metadata for one <lambda-case>.
142 (define-record-type <arity>
143 (make-arity req opt rest kw-indices allow-other-keys?
144 low-pc high-pc)
145 arity?
146 (req arity-req)
147 (opt arity-opt)
148 (rest arity-rest)
149 (kw-indices arity-kw-indices)
150 (allow-other-keys? arity-allow-other-keys?)
151 (low-pc arity-low-pc)
152 (high-pc arity-high-pc set-arity-high-pc!))
153
154 (define-syntax *block-size* (identifier-syntax 32))
155
156 ;;; An assembler collects all of the words emitted during assembly, and
157 ;;; also maintains ancillary information such as the constant table, a
158 ;;; relocation list, and so on.
159 ;;;
160 ;;; RTL code consists of 32-bit units. We emit RTL code using native
161 ;;; endianness. If we're targeting a foreign endianness, we byte-swap
162 ;;; the bytevector as a whole instead of conditionalizing each access.
163 ;;;
164 (define-record-type <asm>
165 (make-asm cur idx start prev written
166 labels relocs
167 word-size endianness
168 constants inits
169 shstrtab next-section-number
170 meta)
171 asm?
172
173 ;; We write RTL code into what is logically a growable vector,
174 ;; implemented as a list of blocks. asm-cur is the current block, and
175 ;; asm-idx is the current index into that block, in 32-bit units.
176 ;;
177 (cur asm-cur set-asm-cur!)
178 (idx asm-idx set-asm-idx!)
179
180 ;; asm-start is an absolute position, indicating the offset of the
181 ;; beginning of an instruction (in u32 units). It is updated after
182 ;; writing all the words for one primitive instruction. It models the
183 ;; position of the instruction pointer during execution, given that
184 ;; the RTL VM updates the IP only at the end of executing the
185 ;; instruction, and is thus useful for computing offsets between two
186 ;; points in a program.
187 ;;
188 (start asm-start set-asm-start!)
189
190 ;; The list of previously written blocks.
191 ;;
192 (prev asm-prev set-asm-prev!)
193
194 ;; The number of u32 words written in asm-prev, which is the same as
195 ;; the offset of the current block.
196 ;;
197 (written asm-written set-asm-written!)
198
199 ;; An alist of symbol -> position pairs, indicating the labels defined
200 ;; in this compilation unit.
201 ;;
202 (labels asm-labels set-asm-labels!)
203
204 ;; A list of relocations needed by the program text. We use an
205 ;; internal representation for relocations, and handle textualn
206 ;; relative relocations in the assembler. Other kinds of relocations
207 ;; are later reified as linker relocations and resolved by the linker.
208 ;;
209 (relocs asm-relocs set-asm-relocs!)
210
211 ;; Target information.
212 ;;
213 (word-size asm-word-size)
214 (endianness asm-endianness)
215
216 ;; The constant table, as a vhash of object -> label. All constants
217 ;; get de-duplicated and written into separate sections -- either the
218 ;; .rodata section, for read-only data, or .data, for constants that
219 ;; need initialization at load-time (like symbols). Constants can
220 ;; depend on other constants (e.g. a symbol depending on a stringbuf),
221 ;; so order in this table is important.
222 ;;
223 (constants asm-constants set-asm-constants!)
224
225 ;; A list of RTL instructions needed to initialize the constants.
226 ;; Will run in a thunk with 2 local variables.
227 ;;
228 (inits asm-inits set-asm-inits!)
229
230 ;; The shstrtab, for section names.
231 ;;
232 (shstrtab asm-shstrtab set-asm-shstrtab!)
233
234 ;; The section number for the next section to be written.
235 ;;
236 (next-section-number asm-next-section-number set-asm-next-section-number!)
237
238 ;; A list of <meta>, corresponding to procedure metadata.
239 ;;
240 (meta asm-meta set-asm-meta!))
241
242 (define-inlinable (fresh-block)
243 (make-u32vector *block-size*))
244
245 (define* (make-assembler #:key (word-size (target-word-size))
246 (endianness (target-endianness)))
247 "Create an assembler for a given target @var{word-size} and
248 @var{endianness}, falling back to appropriate values for the configured
249 target."
250 (make-asm (fresh-block) 0 0 '() 0
251 '() '()
252 word-size endianness
253 vlist-null '()
254 (make-string-table) 1
255 '()))
256
257 (define (intern-section-name! asm string)
258 "Add a string to the section name table (shstrtab)."
259 (string-table-intern! (asm-shstrtab asm) string))
260
261 (define-inlinable (asm-pos asm)
262 "The offset of the next word to be written into the code buffer, in
263 32-bit units."
264 (+ (asm-idx asm) (asm-written asm)))
265
266 (define (allocate-new-block asm)
267 "Close off the current block, and arrange for the next word to be
268 written to a fresh block."
269 (let ((new (fresh-block)))
270 (set-asm-prev! asm (cons (asm-cur asm) (asm-prev asm)))
271 (set-asm-written! asm (asm-pos asm))
272 (set-asm-cur! asm new)
273 (set-asm-idx! asm 0)))
274
275 (define-inlinable (emit asm u32)
276 "Emit one 32-bit word into the instruction stream. Assumes that there
277 is space for the word, and ensures that there is space for the next
278 word."
279 (u32-set! (asm-cur asm) (asm-idx asm) u32)
280 (set-asm-idx! asm (1+ (asm-idx asm)))
281 (if (= (asm-idx asm) *block-size*)
282 (allocate-new-block asm)))
283
284 (define-inlinable (make-reloc type label base word)
285 "Make an internal relocation of type @var{type} referencing symbol
286 @var{label}, @var{word} words after position @var{start}. @var{type}
287 may be x8-s24, indicating a 24-bit relative label reference that can be
288 fixed up by the assembler, or s32, indicating a 32-bit relative
289 reference that needs to be fixed up by the linker."
290 (list type label base word))
291
292 (define-inlinable (reset-asm-start! asm)
293 "Reset the asm-start after writing the words for one instruction."
294 (set-asm-start! asm (asm-pos asm)))
295
296 (define (emit-exported-label asm label)
297 "Define a linker symbol associating @var{label} with the current
298 asm-start."
299 (set-asm-labels! asm (acons label (asm-start asm) (asm-labels asm))))
300
301 (define (record-label-reference asm label)
302 "Record an x8-s24 local label reference. This value will get patched
303 up later by the assembler."
304 (let* ((start (asm-start asm))
305 (pos (asm-pos asm))
306 (reloc (make-reloc 'x8-s24 label start (- pos start))))
307 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
308
309 (define* (record-far-label-reference asm label #:optional (offset 0))
310 "Record an s32 far label reference. This value will get patched up
311 later by the linker."
312 (let* ((start (- (asm-start asm) offset))
313 (pos (asm-pos asm))
314 (reloc (make-reloc 's32 label start (- pos start))))
315 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
316
317
318 \f
319
320 ;;;
321 ;;; Primitive assemblers are defined by expanding `assembler' for each
322 ;;; opcode in `(rtl-instruction-list)'.
323 ;;;
324
325 (eval-when (expand compile load eval)
326 (define (id-append ctx a b)
327 (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b)))))
328
329 (define-syntax assembler
330 (lambda (x)
331 (define-syntax op-case
332 (lambda (x)
333 (syntax-case x ()
334 ((_ asm name ((type arg ...) code ...) clause ...)
335 #`(if (eq? name 'type)
336 (with-syntax (((arg ...) (generate-temporaries #'(arg ...))))
337 #'((arg ...)
338 code ...))
339 (op-case asm name clause ...)))
340 ((_ asm name)
341 #'(error "unmatched name" name)))))
342
343 (define (pack-first-word asm opcode type)
344 (with-syntax ((opcode opcode))
345 (op-case
346 asm type
347 ((U8_X24)
348 (emit asm opcode))
349 ((U8_U24 arg)
350 (emit asm (pack-u8-u24 opcode arg)))
351 ((U8_L24 label)
352 (record-label-reference asm label)
353 (emit asm opcode))
354 ((U8_U8_I16 a imm)
355 (emit asm (pack-u8-u8-u16 opcode a (object-address imm))))
356 ((U8_U12_U12 a b)
357 (emit asm (pack-u8-u12-u12 opcode a b)))
358 ((U8_U8_U8_U8 a b c)
359 (emit asm (pack-u8-u8-u8-u8 opcode a b c))))))
360
361 (define (pack-tail-word asm type)
362 (op-case
363 asm type
364 ((U8_U24 a b)
365 (emit asm (pack-u8-u24 a b)))
366 ((U8_L24 a label)
367 (record-label-reference asm label)
368 (emit asm a))
369 ((U8_U8_I16 a b imm)
370 (emit asm (pack-u8-u8-u16 a b (object-address imm))))
371 ((U8_U12_U12 a b)
372 (emit asm (pack-u8-u12-u12 a b c)))
373 ((U8_U8_U8_U8 a b c d)
374 (emit asm (pack-u8-u8-u8-u8 a b c d)))
375 ((U32 a)
376 (emit asm a))
377 ((I32 imm)
378 (let ((val (object-address imm)))
379 (unless (zero? (ash val -32))
380 (error "FIXME: enable truncation of negative fixnums when cross-compiling"))
381 (emit asm val)))
382 ((A32 imm)
383 (unless (= (asm-word-size asm) 8)
384 (error "make-long-immediate unavailable for this target"))
385 (emit asm (ash (object-address imm) -32))
386 (emit asm (logand (object-address imm) (1- (ash 1 32)))))
387 ((B32))
388 ((N32 label)
389 (record-far-label-reference asm label)
390 (emit asm 0))
391 ((S32 label)
392 (record-far-label-reference asm label)
393 (emit asm 0))
394 ((L32 label)
395 (record-far-label-reference asm label)
396 (emit asm 0))
397 ((LO32 label offset)
398 (record-far-label-reference asm label
399 (* offset (/ (asm-word-size asm) 4)))
400 (emit asm 0))
401 ((X8_U24 a)
402 (emit asm (pack-u8-u24 0 a)))
403 ((X8_U12_U12 a b)
404 (emit asm (pack-u8-u12-u12 0 a b)))
405 ((X8_L24 label)
406 (record-label-reference asm label)
407 (emit asm 0))
408 ((B1_X7_L24 a label)
409 (record-label-reference asm label)
410 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
411 ((B1_U7_L24 a b label)
412 (record-label-reference asm label)
413 (emit asm (pack-u1-u7-u24 (if a 1 0) b 0)))
414 ((B1_X31 a)
415 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
416 ((B1_X7_U24 a b)
417 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))))
418
419 (syntax-case x ()
420 ((_ name opcode word0 word* ...)
421 (with-syntax ((((formal0 ...)
422 code0 ...)
423 (pack-first-word #'asm
424 (syntax->datum #'opcode)
425 (syntax->datum #'word0)))
426 ((((formal* ...)
427 code* ...) ...)
428 (map (lambda (word) (pack-tail-word #'asm word))
429 (syntax->datum #'(word* ...)))))
430 #'(lambda (asm formal0 ... formal* ... ...)
431 (unless (asm? asm) (error "not an asm"))
432 code0 ...
433 code* ... ...
434 (reset-asm-start! asm)))))))
435
436 (define assemblers (make-hash-table))
437
438 (define-syntax define-assembler
439 (lambda (x)
440 (syntax-case x ()
441 ((_ name opcode kind arg ...)
442 (with-syntax ((emit (id-append #'name #'emit- #'name)))
443 #'(define emit
444 (let ((emit (assembler name opcode arg ...)))
445 (hashq-set! assemblers 'name emit)
446 emit)))))))
447
448 (define-syntax visit-opcodes
449 (lambda (x)
450 (syntax-case x ()
451 ((visit-opcodes macro arg ...)
452 (with-syntax (((inst ...)
453 (map (lambda (x) (datum->syntax #'macro x))
454 (rtl-instruction-list))))
455 #'(begin
456 (macro arg ... . inst)
457 ...))))))
458
459 (visit-opcodes define-assembler)
460
461 (define (emit-text asm instructions)
462 "Assemble @var{instructions} using the assembler @var{asm}.
463 @var{instructions} is a sequence of RTL instructions, expressed as a
464 list of lists. This procedure can be called many times before calling
465 @code{link-assembly}."
466 (for-each (lambda (inst)
467 (apply (or (hashq-ref assemblers (car inst))
468 (error 'bad-instruction inst))
469 asm
470 (cdr inst)))
471 instructions))
472
473 \f
474
475 ;;;
476 ;;; The constant table records a topologically sorted set of literal
477 ;;; constants used by a program. For example, a pair uses its car and
478 ;;; cdr, a string uses its stringbuf, etc.
479 ;;;
480 ;;; Some things we want to add to the constant table are not actually
481 ;;; Scheme objects: for example, stringbufs, cache cells for toplevel
482 ;;; references, or cache cells for non-closure procedures. For these we
483 ;;; define special record types and add instances of those record types
484 ;;; to the table.
485 ;;;
486
487 (define-inlinable (immediate? x)
488 "Return @code{#t} if @var{x} is immediate, and @code{#f} otherwise."
489 (not (zero? (logand (object-address x) 6))))
490
491 (define-record-type <stringbuf>
492 (make-stringbuf string)
493 stringbuf?
494 (string stringbuf-string))
495
496 (define-record-type <static-procedure>
497 (make-static-procedure code)
498 static-procedure?
499 (code static-procedure-code))
500
501 (define-record-type <cache-cell>
502 (make-cache-cell scope key)
503 cache-cell?
504 (scope cache-cell-scope)
505 (key cache-cell-key))
506
507 (define (statically-allocatable? x)
508 "Return @code{#t} if a non-immediate constant can be allocated
509 statically, and @code{#f} if it would need some kind of runtime
510 allocation."
511 (or (pair? x) (vector? x) (string? x) (stringbuf? x) (static-procedure? x)))
512
513 (define (intern-constant asm obj)
514 "Add an object to the constant table, and return a label that can be
515 used to reference it. If the object is already present in the constant
516 table, its existing label is used directly."
517 (define (recur obj)
518 (intern-constant asm obj))
519 (define (field dst n obj)
520 (let ((src (recur obj)))
521 (if src
522 (list (if (statically-allocatable? obj)
523 `(make-non-immediate 1 ,src)
524 `(static-ref 1 ,src))
525 `(static-set! 1 ,dst ,n))
526 '())))
527 (define (intern obj label)
528 (cond
529 ((pair? obj)
530 (append (field label 0 (car obj))
531 (field label 1 (cdr obj))))
532 ((vector? obj)
533 (let lp ((i 0) (inits '()))
534 (if (< i (vector-length obj))
535 (lp (1+ i)
536 (append-reverse (field label (1+ i) (vector-ref obj i))
537 inits))
538 (reverse inits))))
539 ((stringbuf? obj) '())
540 ((static-procedure? obj)
541 `((make-non-immediate 1 ,label)
542 (link-procedure! 1 ,(static-procedure-code obj))))
543 ((cache-cell? obj) '())
544 ((symbol? obj)
545 `((make-non-immediate 1 ,(recur (symbol->string obj)))
546 (string->symbol 1 1)
547 (static-set! 1 ,label 0)))
548 ((string? obj)
549 `((make-non-immediate 1 ,(recur (make-stringbuf obj)))
550 (static-set! 1 ,label 1)))
551 ((keyword? obj)
552 `((static-ref 1 ,(recur (keyword->symbol obj)))
553 (symbol->keyword 1 1)
554 (static-set! 1 ,label 0)))
555 ((number? obj)
556 `((make-non-immediate 1 ,(recur (number->string obj)))
557 (string->number 1 1)
558 (static-set! 1 ,label 0)))
559 (else
560 (error "don't know how to intern" obj))))
561 (cond
562 ((immediate? obj) #f)
563 ((vhash-assoc obj (asm-constants asm)) => cdr)
564 (else
565 ;; Note that calling intern may mutate asm-constants and
566 ;; asm-constant-inits.
567 (let* ((label (gensym "constant"))
568 (inits (intern obj label)))
569 (set-asm-constants! asm (vhash-cons obj label (asm-constants asm)))
570 (set-asm-inits! asm (append-reverse inits (asm-inits asm)))
571 label))))
572
573 (define (intern-non-immediate asm obj)
574 "Intern a non-immediate into the constant table, and return its
575 label."
576 (when (immediate? obj)
577 (error "expected a non-immediate" obj))
578 (intern-constant asm obj))
579
580 (define (intern-cache-cell asm scope key)
581 "Intern a cache cell into the constant table, and return its label.
582 If there is already a cache cell with the given scope and key, it is
583 returned instead."
584 (intern-constant asm (make-cache-cell scope key)))
585
586 ;; Return the label of the cell that holds the module for a scope.
587 (define (intern-module-cache-cell asm scope)
588 "Intern a cache cell for a module, and return its label."
589 (intern-cache-cell asm scope #t))
590
591
592 \f
593
594 ;;;
595 ;;; Macro assemblers bridge the gap between primitive instructions and
596 ;;; some higher-level operations.
597 ;;;
598
599 (define-syntax define-macro-assembler
600 (lambda (x)
601 (syntax-case x ()
602 ((_ (name arg ...) body body* ...)
603 (with-syntax ((emit (id-append #'name #'emit- #'name)))
604 #'(define emit
605 (let ((emit (lambda (arg ...) body body* ...)))
606 (hashq-set! assemblers 'name emit)
607 emit)))))))
608
609 (define-macro-assembler (load-constant asm dst obj)
610 (cond
611 ((immediate? obj)
612 (let ((bits (object-address obj)))
613 (cond
614 ((and (< dst 256) (zero? (ash bits -16)))
615 (emit-make-short-immediate asm dst obj))
616 ((zero? (ash bits -32))
617 (emit-make-long-immediate asm dst obj))
618 (else
619 (emit-make-long-long-immediate asm dst obj)))))
620 ((statically-allocatable? obj)
621 (emit-make-non-immediate asm dst (intern-non-immediate asm obj)))
622 (else
623 (emit-static-ref asm dst (intern-non-immediate asm obj)))))
624
625 (define-macro-assembler (load-static-procedure asm dst label)
626 (let ((loc (intern-constant asm (make-static-procedure label))))
627 (emit-make-non-immediate asm dst loc)))
628
629 (define-macro-assembler (begin-program asm label properties)
630 (emit-label asm label)
631 (let ((meta (make-meta label properties (asm-start asm))))
632 (set-asm-meta! asm (cons meta (asm-meta asm)))))
633
634 (define-macro-assembler (end-program asm)
635 (let ((meta (car (asm-meta asm))))
636 (set-meta-high-pc! meta (asm-start asm))
637 (set-meta-arities! meta (reverse (meta-arities meta)))))
638
639 (define-macro-assembler (begin-standard-arity asm req nlocals alternate)
640 (emit-begin-opt-arity asm req '() #f nlocals alternate))
641
642 (define-macro-assembler (begin-opt-arity asm req opt rest nlocals alternate)
643 (emit-begin-kw-arity asm req opt rest '() #f nlocals alternate))
644
645 (define-macro-assembler (begin-kw-arity asm req opt rest kw-indices
646 allow-other-keys? nlocals alternate)
647 (assert-match req ((? symbol?) ...) "list of symbols")
648 (assert-match opt ((? symbol?) ...) "list of symbols")
649 (assert-match rest (or #f (? symbol?)) "#f or symbol")
650 (assert-match kw-indices (((? symbol?) . (? integer?)) ...)
651 "alist of symbol -> integer")
652 (assert-match allow-other-keys? (? boolean?) "boolean")
653 (assert-match nlocals (? integer?) "integer")
654 (assert-match alternate (or #f (? symbol?)) "#f or symbol")
655 (let* ((meta (car (asm-meta asm)))
656 (arity (make-arity req opt rest kw-indices allow-other-keys?
657 (asm-start asm) #f))
658 ;; The procedure itself is in slot 0, in the standard calling
659 ;; convention. For procedure prologues, nreq includes the
660 ;; procedure, so here we add 1.
661 (nreq (1+ (length req)))
662 (nopt (length opt))
663 (rest? (->bool rest)))
664 (set-meta-arities! meta (cons arity (meta-arities meta)))
665 (cond
666 ((or allow-other-keys? (pair? kw-indices))
667 (emit-kw-prelude asm nreq nopt rest? kw-indices allow-other-keys?
668 nlocals alternate))
669 ((or rest? (pair? opt))
670 (emit-opt-prelude asm nreq nopt rest? nlocals alternate))
671 (else
672 (emit-standard-prelude asm nreq nlocals alternate)))))
673
674 (define-macro-assembler (end-arity asm)
675 (let ((arity (car (meta-arities (car (asm-meta asm))))))
676 (set-arity-high-pc! arity (asm-start asm))))
677
678 (define-macro-assembler (standard-prelude asm nreq nlocals alternate)
679 (cond
680 (alternate
681 (emit-br-if-nargs-ne asm nreq alternate)
682 (emit-alloc-frame asm nlocals))
683 ((and (< nreq (ash 1 12)) (< (- nlocals nreq) (ash 1 12)))
684 (emit-assert-nargs-ee/locals asm nreq (- nlocals nreq)))
685 (else
686 (emit-assert-nargs-ee asm nreq)
687 (emit-alloc-frame asm nlocals))))
688
689 (define-macro-assembler (opt-prelude asm nreq nopt rest? nlocals alternate)
690 (if alternate
691 (emit-br-if-nargs-lt asm nreq alternate)
692 (emit-assert-nargs-ge asm nreq))
693 (cond
694 (rest?
695 (emit-bind-rest asm (+ nreq nopt)))
696 (alternate
697 (emit-br-if-nargs-gt asm (+ nreq nopt) alternate))
698 (else
699 (emit-assert-nargs-le asm (+ nreq nopt))))
700 (emit-alloc-frame asm nlocals))
701
702 (define-macro-assembler (kw-prelude asm nreq nopt rest? kw-indices
703 allow-other-keys? nlocals alternate)
704 (if alternate
705 (emit-br-if-nargs-lt asm nreq alternate)
706 (emit-assert-nargs-ge asm nreq))
707 (let ((ntotal (fold (lambda (kw ntotal)
708 (match kw
709 (((? keyword?) . idx)
710 (max (1+ idx) ntotal))))
711 (+ nreq nopt) kw-indices)))
712 ;; FIXME: port 581f410f
713 (emit-bind-kwargs asm nreq
714 (pack-flags allow-other-keys? rest?)
715 (+ nreq nopt)
716 ntotal
717 kw-indices)
718 (emit-alloc-frame asm nlocals)))
719
720 (define-macro-assembler (label asm sym)
721 (set-asm-labels! asm (acons sym (asm-start asm) (asm-labels asm))))
722
723 (define-macro-assembler (cache-current-module! asm module scope)
724 (let ((mod-label (intern-module-cache-cell asm scope)))
725 (emit-static-set! asm module mod-label 0)))
726
727 (define-macro-assembler (cached-toplevel-box asm dst scope sym bound?)
728 (let ((sym-label (intern-non-immediate asm sym))
729 (mod-label (intern-module-cache-cell asm scope))
730 (cell-label (intern-cache-cell asm scope sym)))
731 (emit-toplevel-box asm dst cell-label mod-label sym-label bound?)))
732
733 (define-macro-assembler (cached-module-box asm dst module-name sym public? bound?)
734 (let* ((sym-label (intern-non-immediate asm sym))
735 (key (cons public? module-name))
736 (mod-name-label (intern-constant asm key))
737 (cell-label (intern-cache-cell asm key sym)))
738 (emit-module-box asm dst cell-label mod-name-label sym-label bound?)))
739
740
741 \f
742
743 ;;;
744 ;;; Helper for linking objects.
745 ;;;
746
747 (define (make-object asm name bv relocs labels . kwargs)
748 "Make a linker object. This helper handles interning the name in the
749 shstrtab, assigning the size, allocating a fresh index, and defining a
750 corresponding linker symbol for the start of the section."
751 (let ((name-idx (intern-section-name! asm (symbol->string name)))
752 (index (asm-next-section-number asm)))
753 (set-asm-next-section-number! asm (1+ index))
754 (make-linker-object (apply make-elf-section
755 #:index index
756 #:name name-idx
757 #:size (bytevector-length bv)
758 kwargs)
759 bv relocs
760 (cons (make-linker-symbol name 0) labels))))
761
762
763 \f
764
765 ;;;
766 ;;; Linking the constant table. This code is somewhat intertwingled
767 ;;; with the intern-constant code above, as that procedure also
768 ;;; residualizes instructions to initialize constants at load time.
769 ;;;
770
771 (define (write-immediate asm buf pos x)
772 (let ((val (object-address x))
773 (endianness (asm-endianness asm)))
774 (case (asm-word-size asm)
775 ((4) (bytevector-u32-set! buf pos val endianness))
776 ((8) (bytevector-u64-set! buf pos val endianness))
777 (else (error "bad word size" asm)))))
778
779 (define (emit-init-constants asm)
780 "If there is writable data that needs initialization at runtime, emit
781 a procedure to do that and return its label. Otherwise return
782 @code{#f}."
783 (let ((inits (asm-inits asm)))
784 (and (not (null? inits))
785 (let ((label (gensym "init-constants")))
786 (emit-text asm
787 `((begin-program ,label ())
788 (assert-nargs-ee/locals 1 1)
789 ,@(reverse inits)
790 (load-constant 1 ,*unspecified*)
791 (return 1)
792 (end-program)))
793 label))))
794
795 (define (link-data asm data name)
796 "Link the static data for a program into the @var{name} section (which
797 should be .data or .rodata), and return the resulting linker object.
798 @var{data} should be a vhash mapping objects to labels."
799 (define (align address alignment)
800 (+ address
801 (modulo (- alignment (modulo address alignment)) alignment)))
802
803 (define tc7-vector 13)
804 (define tc7-narrow-stringbuf 39)
805 (define tc7-wide-stringbuf (+ 39 #x400))
806 (define tc7-ro-string (+ 21 #x200))
807 (define tc7-rtl-program 69)
808
809 (let ((word-size (asm-word-size asm))
810 (endianness (asm-endianness asm)))
811 (define (byte-length x)
812 (cond
813 ((stringbuf? x)
814 (let ((x (stringbuf-string x)))
815 (+ (* 2 word-size)
816 (case (string-bytes-per-char x)
817 ((1) (1+ (string-length x)))
818 ((4) (* (1+ (string-length x)) 4))
819 (else (error "bad string bytes per char" x))))))
820 ((static-procedure? x)
821 (* 2 word-size))
822 ((string? x)
823 (* 4 word-size))
824 ((pair? x)
825 (* 2 word-size))
826 ((vector? x)
827 (* (1+ (vector-length x)) word-size))
828 (else
829 word-size)))
830
831 (define (write-constant-reference buf pos x)
832 ;; The asm-inits will fix up any reference to a non-immediate.
833 (write-immediate asm buf pos (if (immediate? x) x #f)))
834
835 (define (write buf pos obj)
836 (cond
837 ((stringbuf? obj)
838 (let* ((x (stringbuf-string obj))
839 (len (string-length x))
840 (tag (if (= (string-bytes-per-char x) 1)
841 tc7-narrow-stringbuf
842 tc7-wide-stringbuf)))
843 (case word-size
844 ((4)
845 (bytevector-u32-set! buf pos tag endianness)
846 (bytevector-u32-set! buf (+ pos 4) len endianness))
847 ((8)
848 (bytevector-u64-set! buf pos tag endianness)
849 (bytevector-u64-set! buf (+ pos 8) len endianness))
850 (else
851 (error "bad word size" asm)))
852 (let ((pos (+ pos (* word-size 2))))
853 (case (string-bytes-per-char x)
854 ((1)
855 (let lp ((i 0))
856 (if (< i len)
857 (let ((u8 (char->integer (string-ref x i))))
858 (bytevector-u8-set! buf (+ pos i) u8)
859 (lp (1+ i)))
860 (bytevector-u8-set! buf (+ pos i) 0))))
861 ((4)
862 (let lp ((i 0))
863 (if (< i len)
864 (let ((u32 (char->integer (string-ref x i))))
865 (bytevector-u32-set! buf (+ pos (* i 4)) u32 endianness)
866 (lp (1+ i)))
867 (bytevector-u32-set! buf (+ pos (* i 4)) 0 endianness))))
868 (else (error "bad string bytes per char" x))))))
869
870 ((static-procedure? obj)
871 (case word-size
872 ((4)
873 (bytevector-u32-set! buf pos tc7-rtl-program endianness)
874 (bytevector-u32-set! buf (+ pos 4) 0 endianness))
875 ((8)
876 (bytevector-u64-set! buf pos tc7-rtl-program endianness)
877 (bytevector-u64-set! buf (+ pos 8) 0 endianness))
878 (else (error "bad word size"))))
879
880 ((cache-cell? obj)
881 (write-immediate asm buf pos #f))
882
883 ((string? obj)
884 (let ((tag (logior tc7-ro-string (ash (string-length obj) 8))))
885 (case word-size
886 ((4)
887 (bytevector-u32-set! buf pos tc7-ro-string endianness)
888 (write-immediate asm buf (+ pos 4) #f) ; stringbuf
889 (bytevector-u32-set! buf (+ pos 8) 0 endianness)
890 (bytevector-u32-set! buf (+ pos 12) (string-length obj) endianness))
891 ((8)
892 (bytevector-u64-set! buf pos tc7-ro-string endianness)
893 (write-immediate asm buf (+ pos 8) #f) ; stringbuf
894 (bytevector-u64-set! buf (+ pos 16) 0 endianness)
895 (bytevector-u64-set! buf (+ pos 24) (string-length obj) endianness))
896 (else (error "bad word size")))))
897
898 ((pair? obj)
899 (write-constant-reference buf pos (car obj))
900 (write-constant-reference buf (+ pos word-size) (cdr obj)))
901
902 ((vector? obj)
903 (let* ((len (vector-length obj))
904 (tag (logior tc7-vector (ash len 8))))
905 (case word-size
906 ((4) (bytevector-u32-set! buf pos tag endianness))
907 ((8) (bytevector-u64-set! buf pos tag endianness))
908 (else (error "bad word size")))
909 (let lp ((i 0))
910 (when (< i (vector-length obj))
911 (let ((pos (+ pos word-size (* i word-size)))
912 (elt (vector-ref obj i)))
913 (write-constant-reference buf pos elt)
914 (lp (1+ i)))))))
915
916 ((symbol? obj)
917 (write-immediate asm buf pos #f))
918
919 ((keyword? obj)
920 (write-immediate asm buf pos #f))
921
922 ((number? obj)
923 (write-immediate asm buf pos #f))
924
925 (else
926 (error "unrecognized object" obj))))
927
928 (cond
929 ((vlist-null? data) #f)
930 (else
931 (let* ((byte-len (vhash-fold (lambda (k v len)
932 (+ (byte-length k) (align len 8)))
933 0 data))
934 (buf (make-bytevector byte-len 0)))
935 (let lp ((i 0) (pos 0) (labels '()))
936 (if (< i (vlist-length data))
937 (let* ((pair (vlist-ref data i))
938 (obj (car pair))
939 (obj-label (cdr pair)))
940 (write buf pos obj)
941 (lp (1+ i)
942 (align (+ (byte-length obj) pos) 8)
943 (cons (make-linker-symbol obj-label pos) labels)))
944 (make-object asm name buf '() labels))))))))
945
946 (define (link-constants asm)
947 "Link sections to hold constants needed by the program text emitted
948 using @var{asm}.
949
950 Returns three values: an object for the .rodata section, an object for
951 the .data section, and a label for an initialization procedure. Any of
952 these may be @code{#f}."
953 (define (shareable? x)
954 (cond
955 ((stringbuf? x) #t)
956 ((pair? x)
957 (and (immediate? (car x)) (immediate? (cdr x))))
958 ((vector? x)
959 (let lp ((i 0))
960 (or (= i (vector-length x))
961 (and (immediate? (vector-ref x i))
962 (lp (1+ i))))))
963 (else #f)))
964 (let* ((constants (asm-constants asm))
965 (len (vlist-length constants)))
966 (let lp ((i 0)
967 (ro vlist-null)
968 (rw vlist-null))
969 (if (= i len)
970 (values (link-data asm ro '.rodata)
971 (link-data asm rw '.data)
972 (emit-init-constants asm))
973 (let ((pair (vlist-ref constants i)))
974 (if (shareable? (car pair))
975 (lp (1+ i) (vhash-consq (car pair) (cdr pair) ro) rw)
976 (lp (1+ i) ro (vhash-consq (car pair) (cdr pair) rw))))))))
977
978 \f
979
980 ;;;
981 ;;; Linking program text.
982 ;;;
983
984 (define (process-relocs buf relocs labels)
985 "Patch up internal x8-s24 relocations, and any s32 relocations that
986 reference symbols in the text section. Return a list of linker
987 relocations for references to symbols defined outside the text section."
988 (fold
989 (lambda (reloc tail)
990 (match reloc
991 ((type label base word)
992 (let ((abs (assq-ref labels label))
993 (dst (+ base word)))
994 (case type
995 ((s32)
996 (if abs
997 (let ((rel (- abs base)))
998 (s32-set! buf dst rel)
999 tail)
1000 (cons (make-linker-reloc 'rel32/4 (* dst 4) word label)
1001 tail)))
1002 ((x8-s24)
1003 (unless abs
1004 (error "unbound near relocation" reloc))
1005 (let ((rel (- abs base))
1006 (u32 (u32-ref buf dst)))
1007 (u32-set! buf dst (pack-u8-s24 (logand u32 #xff) rel))
1008 tail))
1009 (else (error "bad relocation kind" reloc)))))))
1010 '()
1011 relocs))
1012
1013 (define (process-labels labels)
1014 "Define linker symbols for the label-offset pairs in @var{labels}.
1015 The offsets are expected to be expressed in words."
1016 (map (lambda (pair)
1017 (make-linker-symbol (car pair) (* (cdr pair) 4)))
1018 labels))
1019
1020 (define (swap-bytes! buf)
1021 "Patch up the text buffer @var{buf}, swapping the endianness of each
1022 32-bit unit."
1023 (unless (zero? (modulo (bytevector-length buf) 4))
1024 (error "unexpected length"))
1025 (let ((byte-len (bytevector-length buf)))
1026 (let lp ((pos 0))
1027 (unless (= pos byte-len)
1028 (bytevector-u32-set!
1029 buf pos
1030 (bytevector-u32-ref buf pos (endianness big))
1031 (endianness little))
1032 (lp (+ pos 4))))))
1033
1034 (define (link-text-object asm)
1035 "Link the .rtl-text section, swapping the endianness of the bytes if
1036 needed."
1037 (let ((buf (make-u32vector (asm-pos asm))))
1038 (let lp ((pos 0) (prev (reverse (asm-prev asm))))
1039 (if (null? prev)
1040 (let ((byte-size (* (asm-idx asm) 4)))
1041 (bytevector-copy! (asm-cur asm) 0 buf pos byte-size)
1042 (unless (eq? (asm-endianness asm) (native-endianness))
1043 (swap-bytes! buf))
1044 (make-object asm '.rtl-text
1045 buf
1046 (process-relocs buf (asm-relocs asm)
1047 (asm-labels asm))
1048 (process-labels (asm-labels asm))))
1049 (let ((len (* *block-size* 4)))
1050 (bytevector-copy! (car prev) 0 buf pos len)
1051 (lp (+ pos len) (cdr prev)))))))
1052
1053
1054 \f
1055
1056 ;;;
1057 ;;; Linking other sections of the ELF file, like the dynamic segment,
1058 ;;; the symbol table, etc.
1059 ;;;
1060
1061 (define (link-dynamic-section asm text rw rw-init)
1062 "Link the dynamic section for an ELF image with RTL text, given the
1063 writable data section @var{rw} needing fixup from the procedure with
1064 label @var{rw-init}. @var{rw-init} may be false. If @var{rw} is true,
1065 it will be added to the GC roots at runtime."
1066 (define-syntax-rule (emit-dynamic-section word-size %set-uword! reloc-type)
1067 (let* ((endianness (asm-endianness asm))
1068 (bv (make-bytevector (* word-size (if rw (if rw-init 12 10) 6)) 0))
1069 (set-uword!
1070 (lambda (i uword)
1071 (%set-uword! bv (* i word-size) uword endianness)))
1072 (relocs '())
1073 (set-label!
1074 (lambda (i label)
1075 (set! relocs (cons (make-linker-reloc 'reloc-type
1076 (* i word-size) 0 label)
1077 relocs))
1078 (%set-uword! bv (* i word-size) 0 endianness))))
1079 (set-uword! 0 DT_GUILE_RTL_VERSION)
1080 (set-uword! 1 #x02020000)
1081 (set-uword! 2 DT_GUILE_ENTRY)
1082 (set-label! 3 '.rtl-text)
1083 (cond
1084 (rw
1085 ;; Add roots to GC.
1086 (set-uword! 4 DT_GUILE_GC_ROOT)
1087 (set-label! 5 '.data)
1088 (set-uword! 6 DT_GUILE_GC_ROOT_SZ)
1089 (set-uword! 7 (bytevector-length (linker-object-bv rw)))
1090 (cond
1091 (rw-init
1092 (set-uword! 8 DT_INIT) ; constants
1093 (set-label! 9 rw-init)
1094 (set-uword! 10 DT_NULL)
1095 (set-uword! 11 0))
1096 (else
1097 (set-uword! 8 DT_NULL)
1098 (set-uword! 9 0))))
1099 (else
1100 (set-uword! 4 DT_NULL)
1101 (set-uword! 5 0)))
1102 (make-object asm '.dynamic bv relocs '()
1103 #:type SHT_DYNAMIC #:flags SHF_ALLOC)))
1104 (case (asm-word-size asm)
1105 ((4) (emit-dynamic-section 4 bytevector-u32-set! abs32/1))
1106 ((8) (emit-dynamic-section 8 bytevector-u64-set! abs64/1))
1107 (else (error "bad word size" asm))))
1108
1109 (define (link-shstrtab asm)
1110 "Link the string table for the section headers."
1111 (intern-section-name! asm ".shstrtab")
1112 (make-object asm '.shstrtab
1113 (link-string-table! (asm-shstrtab asm))
1114 '() '()
1115 #:type SHT_STRTAB #:flags 0))
1116
1117 (define (link-symtab text-section asm)
1118 (let* ((endianness (asm-endianness asm))
1119 (word-size (asm-word-size asm))
1120 (size (elf-symbol-len word-size))
1121 (meta (reverse (asm-meta asm)))
1122 (n (length meta))
1123 (strtab (make-string-table))
1124 (bv (make-bytevector (* n size) 0)))
1125 (define (intern-string! name)
1126 (string-table-intern! strtab (if name (symbol->string name) "")))
1127 (for-each
1128 (lambda (meta n)
1129 (let ((name (intern-string! (meta-name meta))))
1130 (write-elf-symbol bv (* n size) endianness word-size
1131 (make-elf-symbol
1132 #:name name
1133 ;; Symbol value and size are measured in
1134 ;; bytes, not u32s.
1135 #:value (* 4 (meta-low-pc meta))
1136 #:size (* 4 (- (meta-high-pc meta)
1137 (meta-low-pc meta)))
1138 #:type STT_FUNC
1139 #:visibility STV_HIDDEN
1140 #:shndx (elf-section-index text-section)))))
1141 meta (iota n))
1142 (let ((strtab (make-object asm '.strtab
1143 (link-string-table! strtab)
1144 '() '()
1145 #:type SHT_STRTAB #:flags 0)))
1146 (values (make-object asm '.symtab
1147 bv
1148 '() '()
1149 #:type SHT_SYMTAB #:flags 0 #:entsize size
1150 #:link (elf-section-index
1151 (linker-object-section strtab)))
1152 strtab))))
1153
1154 ;;; The .guile.arities section describes the arities that a function can
1155 ;;; have. It is in two parts: a sorted array of headers describing
1156 ;;; basic arities, and an array of links out to a string table (and in
1157 ;;; the case of keyword arguments, to the data section) for argument
1158 ;;; names. The whole thing is prefixed by a uint32 indicating the
1159 ;;; offset of the end of the headers array.
1160 ;;;
1161 ;;; The arity headers array is a packed array of structures of the form:
1162 ;;;
1163 ;;; struct arity_header {
1164 ;;; uint32_t low_pc;
1165 ;;; uint32_t high_pc;
1166 ;;; uint32_t offset;
1167 ;;; uint32_t flags;
1168 ;;; uint32_t nreq;
1169 ;;; uint32_t nopt;
1170 ;;; }
1171 ;;;
1172 ;;; All of the offsets and addresses are 32 bits. We can expand in the
1173 ;;; future to use 64-bit offsets if appropriate, but there are other
1174 ;;; aspects of RTL that constrain us to a total image that fits in 32
1175 ;;; bits, so for the moment we'll simplify the problem space.
1176 ;;;
1177 ;;; The following flags values are defined:
1178 ;;;
1179 ;;; #x1: has-rest?
1180 ;;; #x2: allow-other-keys?
1181 ;;; #x4: has-keyword-args?
1182 ;;; #x8: is-case-lambda?
1183 ;;;
1184 ;;; Functions with a single arity specify their number of required and
1185 ;;; optional arguments in nreq and nopt, and do not have the
1186 ;;; is-case-lambda? flag set. Their "offset" member links to an array
1187 ;;; of pointers into the associated .guile.arities.strtab string table,
1188 ;;; identifying the argument names. This offset is relative to the
1189 ;;; start of the .guile.arities section. Links for required arguments
1190 ;;; are first, in order, as uint32 values. Next follow the optionals,
1191 ;;; then the rest link if has-rest? is set, then a link to the "keyword
1192 ;;; indices" literal if has-keyword-args? is set. Unlike the other
1193 ;;; links, the kw-indices link points into the data section, and is
1194 ;;; relative to the ELF image as a whole.
1195 ;;;
1196 ;;; Functions with no arities have no arities information present in the
1197 ;;; .guile.arities section.
1198 ;;;
1199 ;;; Functions with multiple arities are preceded by a header with
1200 ;;; is-case-lambda? set. All other fields are 0, except low-pc and
1201 ;;; high-pc which should be the bounds of the whole function. Headers
1202 ;;; for the individual arities follow. In this way the whole headers
1203 ;;; array is sorted in increasing low-pc order, and case-lambda clauses
1204 ;;; are contained within the [low-pc, high-pc] of the case-lambda
1205 ;;; header.
1206
1207 ;; Length of the prefix to the arities section, in bytes.
1208 (define arities-prefix-len 4)
1209
1210 ;; Length of an arity header, in bytes.
1211 (define arity-header-len (* 6 4))
1212
1213 ;; The offset of "offset" within arity header, in bytes.
1214 (define arity-header-offset-offset (* 2 4))
1215
1216 (define-syntax-rule (pack-arity-flags has-rest? allow-other-keys?
1217 has-keyword-args? is-case-lambda?)
1218 (logior (if has-rest? (ash 1 0) 0)
1219 (if allow-other-keys? (ash 1 1) 0)
1220 (if has-keyword-args? (ash 1 2) 0)
1221 (if is-case-lambda? (ash 1 3) 0)))
1222
1223 (define (meta-arities-size meta)
1224 (define (lambda-size arity)
1225 (+ arity-header-len
1226 (* 4 ;; name pointers
1227 (+ (length (arity-req arity))
1228 (length (arity-opt arity))
1229 (if (arity-rest arity) 1 0)
1230 (if (pair? (arity-kw-indices arity)) 1 0)))))
1231 (define (case-lambda-size arities)
1232 (fold +
1233 arity-header-len ;; case-lambda header
1234 (map lambda-size arities))) ;; the cases
1235 (match (meta-arities meta)
1236 (() 0)
1237 ((arity) (lambda-size arity))
1238 (arities (case-lambda-size arities))))
1239
1240 (define (write-arity-headers metas bv endianness)
1241 (define (write-arity-header* pos low-pc high-pc flags nreq nopt)
1242 (bytevector-u32-set! bv pos low-pc endianness)
1243 (bytevector-u32-set! bv (+ pos 4) high-pc endianness)
1244 (bytevector-u32-set! bv (+ pos 8) 0 endianness) ; offset
1245 (bytevector-u32-set! bv (+ pos 12) flags endianness)
1246 (bytevector-u32-set! bv (+ pos 16) nreq endianness)
1247 (bytevector-u32-set! bv (+ pos 20) nopt endianness))
1248 (define (write-arity-header pos arity)
1249 (write-arity-header* pos (arity-low-pc arity)
1250 (arity-high-pc arity)
1251 (pack-arity-flags (arity-rest arity)
1252 (arity-allow-other-keys? arity)
1253 (pair? (arity-kw-indices arity))
1254 #f)
1255 (length (arity-req arity))
1256 (length (arity-opt arity))))
1257 (let lp ((metas metas) (pos arities-prefix-len) (offsets '()))
1258 (match metas
1259 (()
1260 ;; Fill in the prefix.
1261 (bytevector-u32-set! bv 0 pos endianness)
1262 (values pos (reverse offsets)))
1263 ((meta . metas)
1264 (match (meta-arities meta)
1265 (() (lp metas pos offsets))
1266 ((arity)
1267 (write-arity-header pos arity)
1268 (lp metas
1269 (+ pos arity-header-len)
1270 (acons arity (+ pos arity-header-offset-offset) offsets)))
1271 (arities
1272 ;; Write a case-lambda header, then individual arities.
1273 ;; The case-lambda header's offset link is 0.
1274 (write-arity-header* pos (meta-low-pc meta) (meta-high-pc meta)
1275 (pack-arity-flags #f #f #f #t) 0 0)
1276 (let lp* ((arities arities) (pos (+ pos arity-header-len))
1277 (offsets offsets))
1278 (match arities
1279 (() (lp metas pos offsets))
1280 ((arity . arities)
1281 (write-arity-header pos arity)
1282 (lp* arities
1283 (+ pos arity-header-len)
1284 (acons arity
1285 (+ pos arity-header-offset-offset)
1286 offsets)))))))))))
1287
1288 (define (write-arity-links asm bv pos arity-offset-pairs strtab)
1289 (define (write-symbol sym pos)
1290 (bytevector-u32-set! bv pos
1291 (string-table-intern! strtab (symbol->string sym))
1292 (asm-endianness asm))
1293 (+ pos 4))
1294 (define (write-kw-indices pos kw-indices)
1295 ;; FIXME: Assert that kw-indices is already interned.
1296 (make-linker-reloc 'abs32/1 pos 0
1297 (intern-constant asm kw-indices)))
1298 (let lp ((pos pos) (pairs arity-offset-pairs) (relocs '()))
1299 (match pairs
1300 (()
1301 (unless (= pos (bytevector-length bv))
1302 (error "expected to fully fill the bytevector"
1303 pos (bytevector-length bv)))
1304 relocs)
1305 (((arity . offset) . pairs)
1306 (bytevector-u32-set! bv offset pos (asm-endianness asm))
1307 (let ((pos (fold write-symbol
1308 pos
1309 (append (arity-req arity)
1310 (arity-opt arity)
1311 (cond
1312 ((arity-rest arity) => list)
1313 (else '()))))))
1314 (match (arity-kw-indices arity)
1315 (() (lp pos pairs relocs))
1316 (kw-indices
1317 (lp (+ pos 4)
1318 pairs
1319 (cons (write-kw-indices pos kw-indices) relocs)))))))))
1320
1321 (define (link-arities asm)
1322 (let* ((endianness (asm-endianness asm))
1323 (metas (reverse (asm-meta asm)))
1324 (size (fold (lambda (meta size)
1325 (+ size (meta-arities-size meta)))
1326 arities-prefix-len
1327 metas))
1328 (strtab (make-string-table))
1329 (bv (make-bytevector size 0)))
1330 (let ((kw-indices-relocs
1331 (call-with-values
1332 (lambda ()
1333 (write-arity-headers metas bv endianness))
1334 (lambda (pos arity-offset-pairs)
1335 (write-arity-links asm bv pos arity-offset-pairs strtab)))))
1336 (let ((strtab (make-object asm '.guile.arities.strtab
1337 (link-string-table! strtab)
1338 '() '()
1339 #:type SHT_STRTAB #:flags 0)))
1340 (values (make-object asm '.guile.arities
1341 bv
1342 kw-indices-relocs '()
1343 #:type SHT_PROGBITS #:flags 0
1344 #:link (elf-section-index
1345 (linker-object-section strtab)))
1346 strtab)))))
1347
1348 ;;;
1349 ;;; The .guile.docstrs section is a packed, sorted array of (pc, str)
1350 ;;; values. Pc and str are both 32 bits wide. (Either could change to
1351 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1352 ;;; entry to a program, relative to the start of the text section, and
1353 ;;; str is an index into the associated .guile.docstrs.strtab string
1354 ;;; table section.
1355 ;;;
1356
1357 ;; The size of a docstrs entry, in bytes.
1358 (define docstr-size 8)
1359
1360 (define (link-docstrs asm)
1361 (define (find-docstrings)
1362 (filter-map (lambda (meta)
1363 (define (is-documentation? pair)
1364 (eq? (car pair) 'documentation))
1365 (let* ((props (meta-properties meta))
1366 (tail (find-tail is-documentation? props)))
1367 (and tail
1368 (not (find-tail is-documentation? (cdr tail)))
1369 (string? (cdar tail))
1370 (cons (meta-low-pc meta) (cdar tail)))))
1371 (reverse (asm-meta asm))))
1372 (let* ((endianness (asm-endianness asm))
1373 (docstrings (find-docstrings))
1374 (strtab (make-string-table))
1375 (bv (make-bytevector (* (length docstrings) docstr-size) 0)))
1376 (fold (lambda (pair pos)
1377 (match pair
1378 ((pc . string)
1379 (bytevector-u32-set! bv pos pc endianness)
1380 (bytevector-u32-set! bv (+ pos 4)
1381 (string-table-intern! strtab string)
1382 endianness)
1383 (+ pos docstr-size))))
1384 0
1385 docstrings)
1386 (let ((strtab (make-object asm '.guile.docstrs.strtab
1387 (link-string-table! strtab)
1388 '() '()
1389 #:type SHT_STRTAB #:flags 0)))
1390 (values (make-object asm '.guile.docstrs
1391 bv
1392 '() '()
1393 #:type SHT_PROGBITS #:flags 0
1394 #:link (elf-section-index
1395 (linker-object-section strtab)))
1396 strtab))))
1397
1398 ;;;
1399 ;;; The .guile.procprops section is a packed, sorted array of (pc, addr)
1400 ;;; values. Pc and addr are both 32 bits wide. (Either could change to
1401 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1402 ;;; entry to a program, relative to the start of the text section, and
1403 ;;; addr is the address of the associated properties alist, relative to
1404 ;;; the start of the ELF image.
1405 ;;;
1406 ;;; Since procedure properties are stored in the data sections, we need
1407 ;;; to link the procedures property section first. (Note that this
1408 ;;; constraint does not apply to the arities section, which may
1409 ;;; reference the data sections via the kw-indices literal, because
1410 ;;; assembling the text section already makes sure that the kw-indices
1411 ;;; are interned.)
1412 ;;;
1413
1414 ;; The size of a procprops entry, in bytes.
1415 (define procprops-size 8)
1416
1417 (define (link-procprops asm)
1418 (define (assoc-remove-one alist key value-pred)
1419 (match alist
1420 (() '())
1421 ((((? (lambda (x) (eq? x key))) . value) . alist)
1422 (if (value-pred value)
1423 alist
1424 (acons key value alist)))
1425 (((k . v) . alist)
1426 (acons k v (assoc-remove-one alist key value-pred)))))
1427 (define (props-without-name-or-docstring meta)
1428 (assoc-remove-one
1429 (assoc-remove-one (meta-properties meta) 'name (lambda (x) #t))
1430 'documentation
1431 string?))
1432 (define (find-procprops)
1433 (filter-map (lambda (meta)
1434 (let ((props (props-without-name-or-docstring meta)))
1435 (and (pair? props)
1436 (cons (meta-low-pc meta) props))))
1437 (reverse (asm-meta asm))))
1438 (let* ((endianness (asm-endianness asm))
1439 (procprops (find-procprops))
1440 (bv (make-bytevector (* (length procprops) procprops-size) 0)))
1441 (let lp ((procprops procprops) (pos 0) (relocs '()))
1442 (match procprops
1443 (()
1444 (make-object asm '.guile.procprops
1445 bv
1446 relocs '()
1447 #:type SHT_PROGBITS #:flags 0))
1448 (((pc . props) . procprops)
1449 (bytevector-u32-set! bv pos pc endianness)
1450 (lp procprops
1451 (+ pos procprops-size)
1452 (cons (make-linker-reloc 'abs32/1 (+ pos 4) 0
1453 (intern-constant asm props))
1454 relocs)))))))
1455
1456 (define (link-objects asm)
1457 (let*-values (;; Link procprops before constants, because it probably
1458 ;; interns more constants.
1459 ((procprops) (link-procprops asm))
1460 ((ro rw rw-init) (link-constants asm))
1461 ;; Link text object after constants, so that the
1462 ;; constants initializer gets included.
1463 ((text) (link-text-object asm))
1464 ((dt) (link-dynamic-section asm text rw rw-init))
1465 ((symtab strtab) (link-symtab (linker-object-section text) asm))
1466 ((arities arities-strtab) (link-arities asm))
1467 ((docstrs docstrs-strtab) (link-docstrs asm))
1468 ;; This needs to be linked last, because linking other
1469 ;; sections adds entries to the string table.
1470 ((shstrtab) (link-shstrtab asm)))
1471 (filter identity
1472 (list text ro rw dt symtab strtab arities arities-strtab
1473 docstrs docstrs-strtab procprops shstrtab))))
1474
1475
1476 \f
1477
1478 ;;;
1479 ;;; High-level public interfaces.
1480 ;;;
1481
1482 (define* (link-assembly asm #:key (page-aligned? #t))
1483 "Produce an ELF image from the code and data emitted into @var{asm}.
1484 The result is a bytevector, by default linked so that read-only and
1485 writable data are on separate pages. Pass @code{#:page-aligned? #f} to
1486 disable this behavior."
1487 (link-elf (link-objects asm) #:page-aligned? page-aligned?))
1488
1489 (define (assemble-program instructions)
1490 "Take the sequence of instructions @var{instructions}, assemble them
1491 into RTL code, link an image, and load that image from memory. Returns
1492 a procedure."
1493 (let ((asm (make-assembler)))
1494 (emit-text asm instructions)
1495 (load-thunk-from-memory (link-assembly asm #:page-aligned? #f))))