Tweak arities debugging representation
[bpt/guile.git] / module / system / vm / assembler.scm
1 ;;; Guile bytecode assembler
2
3 ;;; Copyright (C) 2001, 2009, 2010, 2012, 2013, 2014 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 ;;; bytecode 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 VM operations. Assemblers
28 ;;; for primitive instructions are generated programmatically from
29 ;;; (instruction-list), which itself is derived from the VM sources.
30 ;;; There are also "macro-instructions" like "label" or "load-constant"
31 ;;; 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 dwarf)
48 #:use-module (system vm elf)
49 #:use-module (system vm linker)
50 #:use-module (language bytecode)
51 #:use-module (rnrs bytevectors)
52 #:use-module (ice-9 binary-ports)
53 #:use-module (ice-9 vlist)
54 #:use-module (ice-9 match)
55 #:use-module (srfi srfi-1)
56 #:use-module (srfi srfi-4)
57 #:use-module (srfi srfi-9)
58 #:use-module (srfi srfi-11)
59 #:export (make-assembler
60 emit-text
61 link-assembly))
62
63
64 \f
65
66 ;;; Bytecode consists of 32-bit units, often subdivided in some way.
67 ;;; These helpers create one 32-bit unit from multiple components.
68
69 (define-inlinable (pack-u8-u24 x y)
70 (unless (<= 0 x 255)
71 (error "out of range" x))
72 (logior x (ash y 8)))
73
74 (define-inlinable (pack-u8-s24 x y)
75 (unless (<= 0 x 255)
76 (error "out of range" x))
77 (logior x (ash (cond
78 ((< 0 (- y) #x800000)
79 (+ y #x1000000))
80 ((<= 0 y #xffffff)
81 y)
82 (else (error "out of range" y)))
83 8)))
84
85 (define-inlinable (pack-u1-u7-u24 x y z)
86 (unless (<= 0 x 1)
87 (error "out of range" x))
88 (unless (<= 0 y 127)
89 (error "out of range" y))
90 (logior x (ash y 1) (ash z 8)))
91
92 (define-inlinable (pack-u8-u12-u12 x y z)
93 (unless (<= 0 x 255)
94 (error "out of range" x))
95 (unless (<= 0 y 4095)
96 (error "out of range" y))
97 (logior x (ash y 8) (ash z 20)))
98
99 (define-inlinable (pack-u8-u8-u16 x y z)
100 (unless (<= 0 x 255)
101 (error "out of range" x))
102 (unless (<= 0 y 255)
103 (error "out of range" y))
104 (logior x (ash y 8) (ash z 16)))
105
106 (define-inlinable (pack-u8-u8-u8-u8 x y z w)
107 (unless (<= 0 x 255)
108 (error "out of range" x))
109 (unless (<= 0 y 255)
110 (error "out of range" y))
111 (unless (<= 0 z 255)
112 (error "out of range" z))
113 (logior x (ash y 8) (ash z 16) (ash w 24)))
114
115 (define-syntax pack-flags
116 (syntax-rules ()
117 ;; Add clauses as needed.
118 ((pack-flags f1 f2) (logior (if f1 (ash 1 0) 0)
119 (if f2 (ash 2 0) 0)))))
120
121 ;;; Helpers to read and write 32-bit units in a buffer.
122
123 (define-syntax-rule (u32-ref buf n)
124 (bytevector-u32-native-ref buf (* n 4)))
125
126 (define-syntax-rule (u32-set! buf n val)
127 (bytevector-u32-native-set! buf (* n 4) val))
128
129 (define-syntax-rule (s32-ref buf n)
130 (bytevector-s32-native-ref buf (* n 4)))
131
132 (define-syntax-rule (s32-set! buf n val)
133 (bytevector-s32-native-set! buf (* n 4) val))
134
135
136 \f
137
138 ;;; A <meta> entry collects metadata for one procedure. Procedures are
139 ;;; written as contiguous ranges of bytecode.
140 ;;;
141 (define-syntax-rule (assert-match arg pattern kind)
142 (let ((x arg))
143 (unless (match x (pattern #t) (_ #f))
144 (error (string-append "expected " kind) x))))
145
146 (define-record-type <meta>
147 (%make-meta label properties low-pc high-pc arities)
148 meta?
149 (label meta-label)
150 (properties meta-properties set-meta-properties!)
151 (low-pc meta-low-pc)
152 (high-pc meta-high-pc set-meta-high-pc!)
153 (arities meta-arities set-meta-arities!))
154
155 (define (make-meta label properties low-pc)
156 (assert-match label (or (? exact-integer?) (? symbol?)) "symbol")
157 (assert-match properties (((? symbol?) . _) ...) "alist with symbolic keys")
158 (%make-meta label properties low-pc #f '()))
159
160 (define (meta-name meta)
161 (assq-ref (meta-properties meta) 'name))
162
163 ;; Metadata for one <lambda-case>.
164 (define-record-type <arity>
165 (make-arity req opt rest kw-indices allow-other-keys?
166 low-pc high-pc definitions)
167 arity?
168 (req arity-req)
169 (opt arity-opt)
170 (rest arity-rest)
171 (kw-indices arity-kw-indices)
172 (allow-other-keys? arity-allow-other-keys?)
173 (low-pc arity-low-pc)
174 (high-pc arity-high-pc set-arity-high-pc!)
175 (definitions arity-definitions set-arity-definitions!))
176
177 (define-syntax *block-size* (identifier-syntax 32))
178
179 ;;; An assembler collects all of the words emitted during assembly, and
180 ;;; also maintains ancillary information such as the constant table, a
181 ;;; relocation list, and so on.
182 ;;;
183 ;;; Bytecode consists of 32-bit units. We emit bytecode using native
184 ;;; endianness. If we're targeting a foreign endianness, we byte-swap
185 ;;; the bytevector as a whole instead of conditionalizing each access.
186 ;;;
187 (define-record-type <asm>
188 (make-asm cur idx start prev written
189 labels relocs
190 word-size endianness
191 constants inits
192 shstrtab next-section-number
193 meta sources
194 dead-slot-maps)
195 asm?
196
197 ;; We write bytecode into what is logically a growable vector,
198 ;; implemented as a list of blocks. asm-cur is the current block, and
199 ;; asm-idx is the current index into that block, in 32-bit units.
200 ;;
201 (cur asm-cur set-asm-cur!)
202 (idx asm-idx set-asm-idx!)
203
204 ;; asm-start is an absolute position, indicating the offset of the
205 ;; beginning of an instruction (in u32 units). It is updated after
206 ;; writing all the words for one primitive instruction. It models the
207 ;; position of the instruction pointer during execution, given that
208 ;; the VM updates the IP only at the end of executing the instruction,
209 ;; and is thus useful for computing offsets between two points in a
210 ;; program.
211 ;;
212 (start asm-start set-asm-start!)
213
214 ;; The list of previously written blocks.
215 ;;
216 (prev asm-prev set-asm-prev!)
217
218 ;; The number of u32 words written in asm-prev, which is the same as
219 ;; the offset of the current block.
220 ;;
221 (written asm-written set-asm-written!)
222
223 ;; An alist of symbol -> position pairs, indicating the labels defined
224 ;; in this compilation unit.
225 ;;
226 (labels asm-labels set-asm-labels!)
227
228 ;; A list of relocations needed by the program text. We use an
229 ;; internal representation for relocations, and handle textualn
230 ;; relative relocations in the assembler. Other kinds of relocations
231 ;; are later reified as linker relocations and resolved by the linker.
232 ;;
233 (relocs asm-relocs set-asm-relocs!)
234
235 ;; Target information.
236 ;;
237 (word-size asm-word-size)
238 (endianness asm-endianness)
239
240 ;; The constant table, as a vhash of object -> label. All constants
241 ;; get de-duplicated and written into separate sections -- either the
242 ;; .rodata section, for read-only data, or .data, for constants that
243 ;; need initialization at load-time (like symbols). Constants can
244 ;; depend on other constants (e.g. a symbol depending on a stringbuf),
245 ;; so order in this table is important.
246 ;;
247 (constants asm-constants set-asm-constants!)
248
249 ;; A list of instructions needed to initialize the constants. Will
250 ;; run in a thunk with 2 local variables.
251 ;;
252 (inits asm-inits set-asm-inits!)
253
254 ;; The shstrtab, for section names.
255 ;;
256 (shstrtab asm-shstrtab set-asm-shstrtab!)
257
258 ;; The section number for the next section to be written.
259 ;;
260 (next-section-number asm-next-section-number set-asm-next-section-number!)
261
262 ;; A list of <meta>, corresponding to procedure metadata.
263 ;;
264 (meta asm-meta set-asm-meta!)
265
266 ;; A list of (pos . source) pairs, indicating source information. POS
267 ;; is relative to the beginning of the text section, and SOURCE is in
268 ;; the same format that source-properties returns.
269 ;;
270 (sources asm-sources set-asm-sources!)
271
272 ;; A list of (pos . dead-slot-map) pairs, indicating dead slot maps.
273 ;; POS is relative to the beginning of the text section.
274 ;; DEAD-SLOT-MAP is a bitfield of slots that are dead at call sites,
275 ;; as an integer.
276 ;;
277 (dead-slot-maps asm-dead-slot-maps set-asm-dead-slot-maps!))
278
279 (define-inlinable (fresh-block)
280 (make-u32vector *block-size*))
281
282 (define* (make-assembler #:key (word-size (target-word-size))
283 (endianness (target-endianness)))
284 "Create an assembler for a given target @var{word-size} and
285 @var{endianness}, falling back to appropriate values for the configured
286 target."
287 (make-asm (fresh-block) 0 0 '() 0
288 (make-hash-table) '()
289 word-size endianness
290 vlist-null '()
291 (make-string-table) 1
292 '() '() '()))
293
294 (define (intern-section-name! asm string)
295 "Add a string to the section name table (shstrtab)."
296 (string-table-intern! (asm-shstrtab asm) string))
297
298 (define-inlinable (asm-pos asm)
299 "The offset of the next word to be written into the code buffer, in
300 32-bit units."
301 (+ (asm-idx asm) (asm-written asm)))
302
303 (define (allocate-new-block asm)
304 "Close off the current block, and arrange for the next word to be
305 written to a fresh block."
306 (let ((new (fresh-block)))
307 (set-asm-prev! asm (cons (asm-cur asm) (asm-prev asm)))
308 (set-asm-written! asm (asm-pos asm))
309 (set-asm-cur! asm new)
310 (set-asm-idx! asm 0)))
311
312 (define-inlinable (emit asm u32)
313 "Emit one 32-bit word into the instruction stream. Assumes that there
314 is space for the word, and ensures that there is space for the next
315 word."
316 (u32-set! (asm-cur asm) (asm-idx asm) u32)
317 (set-asm-idx! asm (1+ (asm-idx asm)))
318 (if (= (asm-idx asm) *block-size*)
319 (allocate-new-block asm)))
320
321 (define-inlinable (make-reloc type label base word)
322 "Make an internal relocation of type @var{type} referencing symbol
323 @var{label}, @var{word} words after position @var{start}. @var{type}
324 may be x8-s24, indicating a 24-bit relative label reference that can be
325 fixed up by the assembler, or s32, indicating a 32-bit relative
326 reference that needs to be fixed up by the linker."
327 (list type label base word))
328
329 (define-inlinable (reset-asm-start! asm)
330 "Reset the asm-start after writing the words for one instruction."
331 (set-asm-start! asm (asm-pos asm)))
332
333 (define (record-label-reference asm label)
334 "Record an x8-s24 local label reference. This value will get patched
335 up later by the assembler."
336 (let* ((start (asm-start asm))
337 (pos (asm-pos asm))
338 (reloc (make-reloc 'x8-s24 label start (- pos start))))
339 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
340
341 (define* (record-far-label-reference asm label #:optional (offset 0))
342 "Record an s32 far label reference. This value will get patched up
343 later by the linker."
344 (let* ((start (- (asm-start asm) offset))
345 (pos (asm-pos asm))
346 (reloc (make-reloc 's32 label start (- pos start))))
347 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
348
349
350 \f
351
352 ;;;
353 ;;; Primitive assemblers are defined by expanding `assembler' for each
354 ;;; opcode in `(instruction-list)'.
355 ;;;
356
357 (eval-when (expand compile load eval)
358 (define (id-append ctx a b)
359 (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b)))))
360
361 (define-syntax assembler
362 (lambda (x)
363 (define-syntax op-case
364 (lambda (x)
365 (syntax-case x ()
366 ((_ asm name ((type arg ...) code ...) clause ...)
367 #`(if (eq? name 'type)
368 (with-syntax (((arg ...) (generate-temporaries #'(arg ...))))
369 #'((arg ...)
370 code ...))
371 (op-case asm name clause ...)))
372 ((_ asm name)
373 #'(error "unmatched name" name)))))
374
375 (define (pack-first-word asm opcode type)
376 (with-syntax ((opcode opcode))
377 (op-case
378 asm type
379 ((U8_X24)
380 (emit asm opcode))
381 ((U8_U24 arg)
382 (emit asm (pack-u8-u24 opcode arg)))
383 ((U8_L24 label)
384 (record-label-reference asm label)
385 (emit asm opcode))
386 ((U8_U8_I16 a imm)
387 (emit asm (pack-u8-u8-u16 opcode a (object-address imm))))
388 ((U8_U12_U12 a b)
389 (emit asm (pack-u8-u12-u12 opcode a b)))
390 ((U8_U8_U8_U8 a b c)
391 (emit asm (pack-u8-u8-u8-u8 opcode a b c))))))
392
393 (define (pack-tail-word asm type)
394 (op-case
395 asm type
396 ((U8_U24 a b)
397 (emit asm (pack-u8-u24 a b)))
398 ((U8_L24 a label)
399 (record-label-reference asm label)
400 (emit asm a))
401 ((U8_U8_I16 a b imm)
402 (emit asm (pack-u8-u8-u16 a b (object-address imm))))
403 ((U8_U12_U12 a b)
404 (emit asm (pack-u8-u12-u12 a b c)))
405 ((U8_U8_U8_U8 a b c d)
406 (emit asm (pack-u8-u8-u8-u8 a b c d)))
407 ((U32 a)
408 (emit asm a))
409 ((I32 imm)
410 (let ((val (object-address imm)))
411 (unless (zero? (ash val -32))
412 (error "FIXME: enable truncation of negative fixnums when cross-compiling"))
413 (emit asm val)))
414 ((A32 imm)
415 (unless (= (asm-word-size asm) 8)
416 (error "make-long-immediate unavailable for this target"))
417 (emit asm (ash (object-address imm) -32))
418 (emit asm (logand (object-address imm) (1- (ash 1 32)))))
419 ((B32))
420 ((N32 label)
421 (record-far-label-reference asm label)
422 (emit asm 0))
423 ((S32 label)
424 (record-far-label-reference asm label)
425 (emit asm 0))
426 ((L32 label)
427 (record-far-label-reference asm label)
428 (emit asm 0))
429 ((LO32 label offset)
430 (record-far-label-reference asm label
431 (* offset (/ (asm-word-size asm) 4)))
432 (emit asm 0))
433 ((X8_U24 a)
434 (emit asm (pack-u8-u24 0 a)))
435 ((X8_U12_U12 a b)
436 (emit asm (pack-u8-u12-u12 0 a b)))
437 ((X8_L24 label)
438 (record-label-reference asm label)
439 (emit asm 0))
440 ((B1_X7_L24 a label)
441 (record-label-reference asm label)
442 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
443 ((B1_U7_L24 a b label)
444 (record-label-reference asm label)
445 (emit asm (pack-u1-u7-u24 (if a 1 0) b 0)))
446 ((B1_X31 a)
447 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
448 ((B1_X7_U24 a b)
449 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))))
450
451 (syntax-case x ()
452 ((_ name opcode word0 word* ...)
453 (with-syntax ((((formal0 ...)
454 code0 ...)
455 (pack-first-word #'asm
456 (syntax->datum #'opcode)
457 (syntax->datum #'word0)))
458 ((((formal* ...)
459 code* ...) ...)
460 (map (lambda (word) (pack-tail-word #'asm word))
461 (syntax->datum #'(word* ...)))))
462 #'(lambda (asm formal0 ... formal* ... ...)
463 (unless (asm? asm) (error "not an asm"))
464 code0 ...
465 code* ... ...
466 (reset-asm-start! asm)))))))
467
468 (define assemblers (make-hash-table))
469
470 (define-syntax define-assembler
471 (lambda (x)
472 (syntax-case x ()
473 ((_ name opcode kind arg ...)
474 (with-syntax ((emit (id-append #'name #'emit- #'name)))
475 #'(begin
476 (define emit
477 (let ((emit (assembler name opcode arg ...)))
478 (hashq-set! assemblers 'name emit)
479 emit))
480 (export emit)))))))
481
482 (define-syntax visit-opcodes
483 (lambda (x)
484 (syntax-case x ()
485 ((visit-opcodes macro arg ...)
486 (with-syntax (((inst ...)
487 (map (lambda (x) (datum->syntax #'macro x))
488 (instruction-list))))
489 #'(begin
490 (macro arg ... . inst)
491 ...))))))
492
493 (visit-opcodes define-assembler)
494
495 (define (emit-text asm instructions)
496 "Assemble @var{instructions} using the assembler @var{asm}.
497 @var{instructions} is a sequence of instructions, expressed as a list of
498 lists. This procedure can be called many times before calling
499 @code{link-assembly}."
500 (for-each (lambda (inst)
501 (apply (or (hashq-ref assemblers (car inst))
502 (error 'bad-instruction inst))
503 asm
504 (cdr inst)))
505 instructions))
506
507 \f
508
509 ;;;
510 ;;; The constant table records a topologically sorted set of literal
511 ;;; constants used by a program. For example, a pair uses its car and
512 ;;; cdr, a string uses its stringbuf, etc.
513 ;;;
514 ;;; Some things we want to add to the constant table are not actually
515 ;;; Scheme objects: for example, stringbufs, cache cells for toplevel
516 ;;; references, or cache cells for non-closure procedures. For these we
517 ;;; define special record types and add instances of those record types
518 ;;; to the table.
519 ;;;
520
521 (define-inlinable (immediate? x)
522 "Return @code{#t} if @var{x} is immediate, and @code{#f} otherwise."
523 (not (zero? (logand (object-address x) 6))))
524
525 (define-record-type <stringbuf>
526 (make-stringbuf string)
527 stringbuf?
528 (string stringbuf-string))
529
530 (define-record-type <static-procedure>
531 (make-static-procedure code)
532 static-procedure?
533 (code static-procedure-code))
534
535 (define-record-type <uniform-vector-backing-store>
536 (make-uniform-vector-backing-store bytes element-size)
537 uniform-vector-backing-store?
538 (bytes uniform-vector-backing-store-bytes)
539 (element-size uniform-vector-backing-store-element-size))
540
541 (define-record-type <cache-cell>
542 (make-cache-cell scope key)
543 cache-cell?
544 (scope cache-cell-scope)
545 (key cache-cell-key))
546
547 (define (simple-vector? obj)
548 (and (vector? obj)
549 (equal? (array-shape obj) (list (list 0 (1- (vector-length obj)))))))
550
551 (define (simple-uniform-vector? obj)
552 (and (array? obj)
553 (symbol? (array-type obj))
554 (equal? (array-shape obj) (list (list 0 (1- (array-length obj)))))))
555
556 (define (statically-allocatable? x)
557 "Return @code{#t} if a non-immediate constant can be allocated
558 statically, and @code{#f} if it would need some kind of runtime
559 allocation."
560 (or (pair? x) (string? x) (stringbuf? x) (static-procedure? x) (array? x)))
561
562 (define (intern-constant asm obj)
563 "Add an object to the constant table, and return a label that can be
564 used to reference it. If the object is already present in the constant
565 table, its existing label is used directly."
566 (define (recur obj)
567 (intern-constant asm obj))
568 (define (field dst n obj)
569 (let ((src (recur obj)))
570 (if src
571 (if (statically-allocatable? obj)
572 `((static-patch! ,dst ,n ,src))
573 `((static-ref 1 ,src)
574 (static-set! 1 ,dst ,n)))
575 '())))
576 (define (intern obj label)
577 (cond
578 ((pair? obj)
579 (append (field label 0 (car obj))
580 (field label 1 (cdr obj))))
581 ((simple-vector? obj)
582 (let lp ((i 0) (inits '()))
583 (if (< i (vector-length obj))
584 (lp (1+ i)
585 (append-reverse (field label (1+ i) (vector-ref obj i))
586 inits))
587 (reverse inits))))
588 ((stringbuf? obj) '())
589 ((static-procedure? obj)
590 `((static-patch! ,label 1 ,(static-procedure-code obj))))
591 ((cache-cell? obj) '())
592 ((symbol? obj)
593 `((make-non-immediate 1 ,(recur (symbol->string obj)))
594 (string->symbol 1 1)
595 (static-set! 1 ,label 0)))
596 ((string? obj)
597 `((static-patch! ,label 1 ,(recur (make-stringbuf obj)))))
598 ((keyword? obj)
599 `((static-ref 1 ,(recur (keyword->symbol obj)))
600 (symbol->keyword 1 1)
601 (static-set! 1 ,label 0)))
602 ((number? obj)
603 `((make-non-immediate 1 ,(recur (number->string obj)))
604 (string->number 1 1)
605 (static-set! 1 ,label 0)))
606 ((uniform-vector-backing-store? obj) '())
607 ((simple-uniform-vector? obj)
608 (let ((width (case (array-type obj)
609 ((vu8 u8 s8) 1)
610 ((u16 s16) 2)
611 ;; Bitvectors are addressed in 32-bit units.
612 ;; Although a complex number is 8 or 16 bytes wide,
613 ;; it should be byteswapped in 4 or 8 byte units.
614 ((u32 s32 f32 c32 b) 4)
615 ((u64 s64 f64 c64) 8)
616 (else
617 (error "unhandled array type" obj)))))
618 `((static-patch! ,label 2
619 ,(recur (make-uniform-vector-backing-store
620 (uniform-array->bytevector obj)
621 width))))))
622 (else
623 (error "don't know how to intern" obj))))
624 (cond
625 ((immediate? obj) #f)
626 ((vhash-assoc obj (asm-constants asm)) => cdr)
627 (else
628 ;; Note that calling intern may mutate asm-constants and
629 ;; asm-constant-inits.
630 (let* ((label (gensym "constant"))
631 (inits (intern obj label)))
632 (set-asm-constants! asm (vhash-cons obj label (asm-constants asm)))
633 (set-asm-inits! asm (append-reverse inits (asm-inits asm)))
634 label))))
635
636 (define (intern-non-immediate asm obj)
637 "Intern a non-immediate into the constant table, and return its
638 label."
639 (when (immediate? obj)
640 (error "expected a non-immediate" obj))
641 (intern-constant asm obj))
642
643 (define (intern-cache-cell asm scope key)
644 "Intern a cache cell into the constant table, and return its label.
645 If there is already a cache cell with the given scope and key, it is
646 returned instead."
647 (intern-constant asm (make-cache-cell scope key)))
648
649 ;; Return the label of the cell that holds the module for a scope.
650 (define (intern-module-cache-cell asm scope)
651 "Intern a cache cell for a module, and return its label."
652 (intern-cache-cell asm scope #t))
653
654
655 \f
656
657 ;;;
658 ;;; Macro assemblers bridge the gap between primitive instructions and
659 ;;; some higher-level operations.
660 ;;;
661
662 (define-syntax define-macro-assembler
663 (lambda (x)
664 (syntax-case x ()
665 ((_ (name arg ...) body body* ...)
666 (with-syntax ((emit (id-append #'name #'emit- #'name)))
667 #'(begin
668 (define emit
669 (let ((emit (lambda (arg ...) body body* ...)))
670 (hashq-set! assemblers 'name emit)
671 emit))
672 (export emit)))))))
673
674 (define-macro-assembler (load-constant asm dst obj)
675 (cond
676 ((immediate? obj)
677 (let ((bits (object-address obj)))
678 (cond
679 ((and (< dst 256) (zero? (ash bits -16)))
680 (emit-make-short-immediate asm dst obj))
681 ((zero? (ash bits -32))
682 (emit-make-long-immediate asm dst obj))
683 (else
684 (emit-make-long-long-immediate asm dst obj)))))
685 ((statically-allocatable? obj)
686 (emit-make-non-immediate asm dst (intern-non-immediate asm obj)))
687 (else
688 (emit-static-ref asm dst (intern-non-immediate asm obj)))))
689
690 (define-macro-assembler (load-static-procedure asm dst label)
691 (let ((loc (intern-constant asm (make-static-procedure label))))
692 (emit-make-non-immediate asm dst loc)))
693
694 (define-syntax-rule (define-tc7-macro-assembler name tc7)
695 (define-macro-assembler (name asm slot invert? label)
696 (emit-br-if-tc7 asm slot invert? tc7 label)))
697
698 ;; Keep in sync with tags.h. Part of Guile's ABI. Currently unused
699 ;; macro assemblers are commented out. See also
700 ;; *branching-primcall-arities* in (language cps primitives), the set of
701 ;; macro-instructions in assembly.scm, and
702 ;; disassembler.scm:code-annotation.
703 ;;
704 ;; FIXME: Define all tc7 values in Scheme in one place, derived from
705 ;; tags.h.
706 (define-tc7-macro-assembler br-if-symbol 5)
707 (define-tc7-macro-assembler br-if-variable 7)
708 (define-tc7-macro-assembler br-if-vector 13)
709 ;(define-tc7-macro-assembler br-if-weak-vector 13)
710 (define-tc7-macro-assembler br-if-string 21)
711 ;(define-tc7-macro-assembler br-if-heap-number 23)
712 ;(define-tc7-macro-assembler br-if-stringbuf 39)
713 (define-tc7-macro-assembler br-if-bytevector 77)
714 ;(define-tc7-macro-assembler br-if-pointer 31)
715 ;(define-tc7-macro-assembler br-if-hashtable 29)
716 ;(define-tc7-macro-assembler br-if-fluid 37)
717 ;(define-tc7-macro-assembler br-if-dynamic-state 45)
718 ;(define-tc7-macro-assembler br-if-frame 47)
719 ;(define-tc7-macro-assembler br-if-vm 55)
720 ;(define-tc7-macro-assembler br-if-vm-cont 71)
721 ;(define-tc7-macro-assembler br-if-rtl-program 69)
722 ;(define-tc7-macro-assembler br-if-weak-set 85)
723 ;(define-tc7-macro-assembler br-if-weak-table 87)
724 ;(define-tc7-macro-assembler br-if-array 93)
725 (define-tc7-macro-assembler br-if-bitvector 95)
726 ;(define-tc7-macro-assembler br-if-port 125)
727 ;(define-tc7-macro-assembler br-if-smob 127)
728
729 (define-macro-assembler (begin-program asm label properties)
730 (emit-label asm label)
731 (let ((meta (make-meta label properties (asm-start asm))))
732 (set-asm-meta! asm (cons meta (asm-meta asm)))))
733
734 (define-macro-assembler (end-program asm)
735 (let ((meta (car (asm-meta asm))))
736 (set-meta-high-pc! meta (asm-start asm))
737 (set-meta-arities! meta (reverse (meta-arities meta)))))
738
739 (define-macro-assembler (begin-standard-arity asm req nlocals alternate)
740 (emit-begin-opt-arity asm req '() #f nlocals alternate))
741
742 (define-macro-assembler (begin-opt-arity asm req opt rest nlocals alternate)
743 (emit-begin-kw-arity asm req opt rest '() #f nlocals alternate))
744
745 (define-macro-assembler (begin-kw-arity asm req opt rest kw-indices
746 allow-other-keys? nlocals alternate)
747 (assert-match req ((? symbol?) ...) "list of symbols")
748 (assert-match opt ((? symbol?) ...) "list of symbols")
749 (assert-match rest (or #f (? symbol?)) "#f or symbol")
750 (assert-match kw-indices (((? keyword?) . (? integer?)) ...)
751 "alist of keyword -> integer")
752 (assert-match allow-other-keys? (? boolean?) "boolean")
753 (assert-match nlocals (? integer?) "integer")
754 (assert-match alternate (or #f (? exact-integer?) (? symbol?)) "#f or symbol")
755 (let* ((meta (car (asm-meta asm)))
756 (arity (make-arity req opt rest kw-indices allow-other-keys?
757 (asm-start asm) #f '()))
758 ;; The procedure itself is in slot 0, in the standard calling
759 ;; convention. For procedure prologues, nreq includes the
760 ;; procedure, so here we add 1.
761 (nreq (1+ (length req)))
762 (nopt (length opt))
763 (rest? (->bool rest)))
764 (set-meta-arities! meta (cons arity (meta-arities meta)))
765 (cond
766 ((or allow-other-keys? (pair? kw-indices))
767 (emit-kw-prelude asm nreq nopt rest? kw-indices allow-other-keys?
768 nlocals alternate))
769 ((or rest? (pair? opt))
770 (emit-opt-prelude asm nreq nopt rest? nlocals alternate))
771 (else
772 (emit-standard-prelude asm nreq nlocals alternate)))))
773
774 (define-macro-assembler (end-arity asm)
775 (let ((arity (car (meta-arities (car (asm-meta asm))))))
776 (set-arity-definitions! arity (reverse (arity-definitions arity)))
777 (set-arity-high-pc! arity (asm-start asm))))
778
779 (define-macro-assembler (standard-prelude asm nreq nlocals alternate)
780 (cond
781 (alternate
782 (emit-br-if-nargs-ne asm nreq alternate)
783 (emit-alloc-frame asm nlocals))
784 ((and (< nreq (ash 1 12)) (< (- nlocals nreq) (ash 1 12)))
785 (emit-assert-nargs-ee/locals asm nreq (- nlocals nreq)))
786 (else
787 (emit-assert-nargs-ee asm nreq)
788 (emit-alloc-frame asm nlocals))))
789
790 (define-macro-assembler (opt-prelude asm nreq nopt rest? nlocals alternate)
791 (if alternate
792 (emit-br-if-nargs-lt asm nreq alternate)
793 (emit-assert-nargs-ge asm nreq))
794 (cond
795 (rest?
796 (emit-bind-rest asm (+ nreq nopt)))
797 (alternate
798 (emit-br-if-nargs-gt asm (+ nreq nopt) alternate))
799 (else
800 (emit-assert-nargs-le asm (+ nreq nopt))))
801 (emit-alloc-frame asm nlocals))
802
803 (define-macro-assembler (kw-prelude asm nreq nopt rest? kw-indices
804 allow-other-keys? nlocals alternate)
805 (if alternate
806 (begin
807 (emit-br-if-nargs-lt asm nreq alternate)
808 (unless rest?
809 (emit-br-if-npos-gt asm nreq (+ nreq nopt) alternate)))
810 (emit-assert-nargs-ge asm nreq))
811 (let ((ntotal (fold (lambda (kw ntotal)
812 (match kw
813 (((? keyword?) . idx)
814 (max (1+ idx) ntotal))))
815 (+ nreq nopt) kw-indices)))
816 ;; FIXME: port 581f410f
817 (emit-bind-kwargs asm nreq
818 (pack-flags allow-other-keys? rest?)
819 (+ nreq nopt)
820 ntotal
821 (intern-constant asm kw-indices))
822 (emit-alloc-frame asm nlocals)))
823
824 (define-macro-assembler (label asm sym)
825 (hashq-set! (asm-labels asm) sym (asm-start asm)))
826
827 (define-macro-assembler (source asm source)
828 (set-asm-sources! asm (acons (asm-start asm) source (asm-sources asm))))
829
830 (define-macro-assembler (definition asm name slot)
831 (let* ((arity (car (meta-arities (car (asm-meta asm)))))
832 (def (vector name slot (- (asm-start asm) (arity-low-pc arity)))))
833 (set-arity-definitions! arity (cons def (arity-definitions arity)))))
834
835 (define-macro-assembler (cache-current-module! asm module scope)
836 (let ((mod-label (intern-module-cache-cell asm scope)))
837 (emit-static-set! asm module mod-label 0)))
838
839 (define-macro-assembler (cached-toplevel-box asm dst scope sym bound?)
840 (let ((sym-label (intern-non-immediate asm sym))
841 (mod-label (intern-module-cache-cell asm scope))
842 (cell-label (intern-cache-cell asm scope sym)))
843 (emit-toplevel-box asm dst cell-label mod-label sym-label bound?)))
844
845 (define-macro-assembler (cached-module-box asm dst module-name sym public? bound?)
846 (let* ((sym-label (intern-non-immediate asm sym))
847 (key (cons public? module-name))
848 (mod-name-label (intern-constant asm key))
849 (cell-label (intern-cache-cell asm key sym)))
850 (emit-module-box asm dst cell-label mod-name-label sym-label bound?)))
851
852 (define-macro-assembler (dead-slot-map asm proc-slot dead-slot-map)
853 (unless (zero? dead-slot-map)
854 (set-asm-dead-slot-maps! asm
855 (cons
856 (cons* (asm-start asm) proc-slot dead-slot-map)
857 (asm-dead-slot-maps asm)))))
858
859 \f
860
861 ;;;
862 ;;; Helper for linking objects.
863 ;;;
864
865 (define (make-object asm name bv relocs labels . kwargs)
866 "Make a linker object. This helper handles interning the name in the
867 shstrtab, assigning the size, allocating a fresh index, and defining a
868 corresponding linker symbol for the start of the section."
869 (let ((name-idx (intern-section-name! asm (symbol->string name)))
870 (index (asm-next-section-number asm)))
871 (set-asm-next-section-number! asm (1+ index))
872 (make-linker-object (apply make-elf-section
873 #:index index
874 #:name name-idx
875 #:size (bytevector-length bv)
876 kwargs)
877 bv relocs
878 (cons (make-linker-symbol name 0) labels))))
879
880
881 \f
882
883 ;;;
884 ;;; Linking the constant table. This code is somewhat intertwingled
885 ;;; with the intern-constant code above, as that procedure also
886 ;;; residualizes instructions to initialize constants at load time.
887 ;;;
888
889 (define (write-immediate asm buf pos x)
890 (let ((val (object-address x))
891 (endianness (asm-endianness asm)))
892 (case (asm-word-size asm)
893 ((4) (bytevector-u32-set! buf pos val endianness))
894 ((8) (bytevector-u64-set! buf pos val endianness))
895 (else (error "bad word size" asm)))))
896
897 (define (emit-init-constants asm)
898 "If there is writable data that needs initialization at runtime, emit
899 a procedure to do that and return its label. Otherwise return
900 @code{#f}."
901 (let ((inits (asm-inits asm)))
902 (and (not (null? inits))
903 (let ((label (gensym "init-constants")))
904 (emit-text asm
905 `((begin-program ,label ())
906 (assert-nargs-ee/locals 1 1)
907 ,@(reverse inits)
908 (load-constant 1 ,*unspecified*)
909 (return 1)
910 (end-program)))
911 label))))
912
913 (define (link-data asm data name)
914 "Link the static data for a program into the @var{name} section (which
915 should be .data or .rodata), and return the resulting linker object.
916 @var{data} should be a vhash mapping objects to labels."
917 (define (align address alignment)
918 (+ address
919 (modulo (- alignment (modulo address alignment)) alignment)))
920
921 (define tc7-vector 13)
922 (define stringbuf-shared-flag #x100)
923 (define stringbuf-wide-flag #x400)
924 (define tc7-stringbuf 39)
925 (define tc7-narrow-stringbuf
926 (+ tc7-stringbuf stringbuf-shared-flag))
927 (define tc7-wide-stringbuf
928 (+ tc7-stringbuf stringbuf-shared-flag stringbuf-wide-flag))
929 (define tc7-ro-string (+ 21 #x200))
930 (define tc7-program 69)
931 (define tc7-bytevector 77)
932 (define tc7-bitvector 95)
933
934 (let ((word-size (asm-word-size asm))
935 (endianness (asm-endianness asm)))
936 (define (byte-length x)
937 (cond
938 ((stringbuf? x)
939 (let ((x (stringbuf-string x)))
940 (+ (* 2 word-size)
941 (case (string-bytes-per-char x)
942 ((1) (1+ (string-length x)))
943 ((4) (* (1+ (string-length x)) 4))
944 (else (error "bad string bytes per char" x))))))
945 ((static-procedure? x)
946 (* 2 word-size))
947 ((string? x)
948 (* 4 word-size))
949 ((pair? x)
950 (* 2 word-size))
951 ((simple-vector? x)
952 (* (1+ (vector-length x)) word-size))
953 ((simple-uniform-vector? x)
954 (* 4 word-size))
955 ((uniform-vector-backing-store? x)
956 (bytevector-length (uniform-vector-backing-store-bytes x)))
957 (else
958 word-size)))
959
960 (define (write-constant-reference buf pos x)
961 ;; The asm-inits will fix up any reference to a non-immediate.
962 (write-immediate asm buf pos (if (immediate? x) x #f)))
963
964 (define (write buf pos obj)
965 (cond
966 ((stringbuf? obj)
967 (let* ((x (stringbuf-string obj))
968 (len (string-length x))
969 (tag (if (= (string-bytes-per-char x) 1)
970 tc7-narrow-stringbuf
971 tc7-wide-stringbuf)))
972 (case word-size
973 ((4)
974 (bytevector-u32-set! buf pos tag endianness)
975 (bytevector-u32-set! buf (+ pos 4) len endianness))
976 ((8)
977 (bytevector-u64-set! buf pos tag endianness)
978 (bytevector-u64-set! buf (+ pos 8) len endianness))
979 (else
980 (error "bad word size" asm)))
981 (let ((pos (+ pos (* word-size 2))))
982 (case (string-bytes-per-char x)
983 ((1)
984 (let lp ((i 0))
985 (if (< i len)
986 (let ((u8 (char->integer (string-ref x i))))
987 (bytevector-u8-set! buf (+ pos i) u8)
988 (lp (1+ i)))
989 (bytevector-u8-set! buf (+ pos i) 0))))
990 ((4)
991 (let lp ((i 0))
992 (if (< i len)
993 (let ((u32 (char->integer (string-ref x i))))
994 (bytevector-u32-set! buf (+ pos (* i 4)) u32 endianness)
995 (lp (1+ i)))
996 (bytevector-u32-set! buf (+ pos (* i 4)) 0 endianness))))
997 (else (error "bad string bytes per char" x))))))
998
999 ((static-procedure? obj)
1000 (case word-size
1001 ((4)
1002 (bytevector-u32-set! buf pos tc7-program endianness)
1003 (bytevector-u32-set! buf (+ pos 4) 0 endianness))
1004 ((8)
1005 (bytevector-u64-set! buf pos tc7-program endianness)
1006 (bytevector-u64-set! buf (+ pos 8) 0 endianness))
1007 (else (error "bad word size"))))
1008
1009 ((cache-cell? obj)
1010 (write-immediate asm buf pos #f))
1011
1012 ((string? obj)
1013 (let ((tag (logior tc7-ro-string (ash (string-length obj) 8))))
1014 (case word-size
1015 ((4)
1016 (bytevector-u32-set! buf pos tc7-ro-string endianness)
1017 (write-immediate asm buf (+ pos 4) #f) ; stringbuf
1018 (bytevector-u32-set! buf (+ pos 8) 0 endianness)
1019 (bytevector-u32-set! buf (+ pos 12) (string-length obj) endianness))
1020 ((8)
1021 (bytevector-u64-set! buf pos tc7-ro-string endianness)
1022 (write-immediate asm buf (+ pos 8) #f) ; stringbuf
1023 (bytevector-u64-set! buf (+ pos 16) 0 endianness)
1024 (bytevector-u64-set! buf (+ pos 24) (string-length obj) endianness))
1025 (else (error "bad word size")))))
1026
1027 ((pair? obj)
1028 (write-constant-reference buf pos (car obj))
1029 (write-constant-reference buf (+ pos word-size) (cdr obj)))
1030
1031 ((simple-vector? obj)
1032 (let* ((len (vector-length obj))
1033 (tag (logior tc7-vector (ash len 8))))
1034 (case word-size
1035 ((4) (bytevector-u32-set! buf pos tag endianness))
1036 ((8) (bytevector-u64-set! buf pos tag endianness))
1037 (else (error "bad word size")))
1038 (let lp ((i 0))
1039 (when (< i (vector-length obj))
1040 (let ((pos (+ pos word-size (* i word-size)))
1041 (elt (vector-ref obj i)))
1042 (write-constant-reference buf pos elt)
1043 (lp (1+ i)))))))
1044
1045 ((symbol? obj)
1046 (write-immediate asm buf pos #f))
1047
1048 ((keyword? obj)
1049 (write-immediate asm buf pos #f))
1050
1051 ((number? obj)
1052 (write-immediate asm buf pos #f))
1053
1054 ((simple-uniform-vector? obj)
1055 (let ((tag (if (bitvector? obj)
1056 tc7-bitvector
1057 (let ((type-code (array-type-code obj)))
1058 (logior tc7-bytevector (ash type-code 7))))))
1059 (case word-size
1060 ((4)
1061 (bytevector-u32-set! buf pos tag endianness)
1062 (bytevector-u32-set! buf (+ pos 4)
1063 (if (bitvector? obj)
1064 (bitvector-length obj)
1065 (bytevector-length obj))
1066 endianness) ; length
1067 (bytevector-u32-set! buf (+ pos 8) 0 endianness) ; pointer
1068 (write-immediate asm buf (+ pos 12) #f)) ; owner
1069 ((8)
1070 (bytevector-u64-set! buf pos tag endianness)
1071 (bytevector-u64-set! buf (+ pos 8)
1072 (if (bitvector? obj)
1073 (bitvector-length obj)
1074 (bytevector-length obj))
1075 endianness) ; length
1076 (bytevector-u64-set! buf (+ pos 16) 0 endianness) ; pointer
1077 (write-immediate asm buf (+ pos 24) #f)) ; owner
1078 (else (error "bad word size")))))
1079
1080 ((uniform-vector-backing-store? obj)
1081 (let ((bv (uniform-vector-backing-store-bytes obj)))
1082 (bytevector-copy! bv 0 buf pos (bytevector-length bv))
1083 (unless (or (= 1 (uniform-vector-backing-store-element-size obj))
1084 (eq? endianness (native-endianness)))
1085 ;; Need to swap units of element-size bytes
1086 (error "FIXME: Implement byte order swap"))))
1087
1088 (else
1089 (error "unrecognized object" obj))))
1090
1091 (cond
1092 ((vlist-null? data) #f)
1093 (else
1094 (let* ((byte-len (vhash-fold (lambda (k v len)
1095 (+ (byte-length k) (align len 8)))
1096 0 data))
1097 (buf (make-bytevector byte-len 0)))
1098 (let lp ((i 0) (pos 0) (symbols '()))
1099 (if (< i (vlist-length data))
1100 (let* ((pair (vlist-ref data i))
1101 (obj (car pair))
1102 (obj-label (cdr pair)))
1103 (write buf pos obj)
1104 (lp (1+ i)
1105 (align (+ (byte-length obj) pos) 8)
1106 (cons (make-linker-symbol obj-label pos) symbols)))
1107 (make-object asm name buf '() symbols
1108 #:flags (match name
1109 ('.data (logior SHF_ALLOC SHF_WRITE))
1110 ('.rodata SHF_ALLOC))))))))))
1111
1112 (define (link-constants asm)
1113 "Link sections to hold constants needed by the program text emitted
1114 using @var{asm}.
1115
1116 Returns three values: an object for the .rodata section, an object for
1117 the .data section, and a label for an initialization procedure. Any of
1118 these may be @code{#f}."
1119 (define (shareable? x)
1120 (cond
1121 ((stringbuf? x) #t)
1122 ((pair? x)
1123 (and (immediate? (car x)) (immediate? (cdr x))))
1124 ((simple-vector? x)
1125 (let lp ((i 0))
1126 (or (= i (vector-length x))
1127 (and (immediate? (vector-ref x i))
1128 (lp (1+ i))))))
1129 ((uniform-vector-backing-store? x) #t)
1130 (else #f)))
1131 (let* ((constants (asm-constants asm))
1132 (len (vlist-length constants)))
1133 (let lp ((i 0)
1134 (ro vlist-null)
1135 (rw vlist-null))
1136 (if (= i len)
1137 (values (link-data asm ro '.rodata)
1138 (link-data asm rw '.data)
1139 (emit-init-constants asm))
1140 (let ((pair (vlist-ref constants i)))
1141 (if (shareable? (car pair))
1142 (lp (1+ i) (vhash-consq (car pair) (cdr pair) ro) rw)
1143 (lp (1+ i) ro (vhash-consq (car pair) (cdr pair) rw))))))))
1144
1145 \f
1146
1147 ;;;
1148 ;;; Linking program text.
1149 ;;;
1150
1151 (define (process-relocs buf relocs labels)
1152 "Patch up internal x8-s24 relocations, and any s32 relocations that
1153 reference symbols in the text section. Return a list of linker
1154 relocations for references to symbols defined outside the text section."
1155 (fold
1156 (lambda (reloc tail)
1157 (match reloc
1158 ((type label base word)
1159 (let ((abs (hashq-ref labels label))
1160 (dst (+ base word)))
1161 (case type
1162 ((s32)
1163 (if abs
1164 (let ((rel (- abs base)))
1165 (s32-set! buf dst rel)
1166 tail)
1167 (cons (make-linker-reloc 'rel32/4 (* dst 4) word label)
1168 tail)))
1169 ((x8-s24)
1170 (unless abs
1171 (error "unbound near relocation" reloc))
1172 (let ((rel (- abs base))
1173 (u32 (u32-ref buf dst)))
1174 (u32-set! buf dst (pack-u8-s24 (logand u32 #xff) rel))
1175 tail))
1176 (else (error "bad relocation kind" reloc)))))))
1177 '()
1178 relocs))
1179
1180 (define (process-labels labels)
1181 "Define linker symbols for the label-offset map in @var{labels}.
1182 The offsets are expected to be expressed in words."
1183 (hash-map->list (lambda (label loc)
1184 (make-linker-symbol label (* loc 4)))
1185 labels))
1186
1187 (define (swap-bytes! buf)
1188 "Patch up the text buffer @var{buf}, swapping the endianness of each
1189 32-bit unit."
1190 (unless (zero? (modulo (bytevector-length buf) 4))
1191 (error "unexpected length"))
1192 (let ((byte-len (bytevector-length buf)))
1193 (let lp ((pos 0))
1194 (unless (= pos byte-len)
1195 (bytevector-u32-set!
1196 buf pos
1197 (bytevector-u32-ref buf pos (endianness big))
1198 (endianness little))
1199 (lp (+ pos 4))))))
1200
1201 (define (link-text-object asm)
1202 "Link the .rtl-text section, swapping the endianness of the bytes if
1203 needed."
1204 (let ((buf (make-u32vector (asm-pos asm))))
1205 (let lp ((pos 0) (prev (reverse (asm-prev asm))))
1206 (if (null? prev)
1207 (let ((byte-size (* (asm-idx asm) 4)))
1208 (bytevector-copy! (asm-cur asm) 0 buf pos byte-size)
1209 (unless (eq? (asm-endianness asm) (native-endianness))
1210 (swap-bytes! buf))
1211 (make-object asm '.rtl-text
1212 buf
1213 (process-relocs buf (asm-relocs asm)
1214 (asm-labels asm))
1215 (process-labels (asm-labels asm))))
1216 (let ((len (* *block-size* 4)))
1217 (bytevector-copy! (car prev) 0 buf pos len)
1218 (lp (+ pos len) (cdr prev)))))))
1219
1220
1221 \f
1222
1223 ;;;
1224 ;;; Create the frame maps. These maps are used by GC to identify dead
1225 ;;; slots in pending call frames, to avoid marking them. We only do
1226 ;;; this when frame makes a non-tail call, as that is the common case.
1227 ;;; Only the topmost frame will see a GC at any other point, but we mark
1228 ;;; top frames conservatively as serializing live slot maps at every
1229 ;;; instruction would take up too much space in the object file.
1230 ;;;
1231
1232 ;; The .guile.frame-maps section starts with two packed u32 values: one
1233 ;; indicating the offset of the first byte of the .rtl-text section, and
1234 ;; another indicating the relative offset in bytes of the slots data.
1235 (define frame-maps-prefix-len 8)
1236
1237 ;; Each header is 8 bytes: 4 for the offset from .rtl_text, and 4 for
1238 ;; the offset of the slot map from the beginning of the
1239 ;; .guile.frame-maps section. The length of a frame map depends on the
1240 ;; frame size at the call site, and is not encoded into this section as
1241 ;; it is available at run-time.
1242 (define frame-map-header-len 8)
1243
1244 (define (link-frame-maps asm)
1245 (define (map-byte-length proc-slot)
1246 (ceiling-quotient (- proc-slot 2) 8))
1247 (define (make-frame-maps maps count map-len)
1248 (let* ((endianness (asm-endianness asm))
1249 (header-pos frame-maps-prefix-len)
1250 (map-pos (+ header-pos (* count frame-map-header-len)))
1251 (bv (make-bytevector (+ map-pos map-len) 0)))
1252 (bytevector-u32-set! bv 4 map-pos endianness)
1253 (let lp ((maps maps) (header-pos header-pos) (map-pos map-pos))
1254 (match maps
1255 (()
1256 (make-object asm '.guile.frame-maps bv
1257 (list (make-linker-reloc 'abs32/1 0 0 '.rtl-text))
1258 '() #:type SHT_PROGBITS #:flags SHF_ALLOC))
1259 (((pos proc-slot . map) . maps)
1260 (bytevector-u32-set! bv header-pos (* pos 4) endianness)
1261 (bytevector-u32-set! bv (+ header-pos 4) map-pos endianness)
1262 (let write-bytes ((map-pos map-pos)
1263 (map map)
1264 (byte-length (map-byte-length proc-slot)))
1265 (if (zero? byte-length)
1266 (lp maps (+ header-pos frame-map-header-len) map-pos)
1267 (begin
1268 (bytevector-u8-set! bv map-pos (logand map #xff))
1269 (write-bytes (1+ map-pos) (ash map -8)
1270 (1- byte-length))))))))))
1271 (match (asm-dead-slot-maps asm)
1272 (() #f)
1273 (in
1274 (let lp ((in in) (out '()) (count 0) (map-len 0))
1275 (match in
1276 (() (make-frame-maps out count map-len))
1277 (((and head (pos proc-slot . map)) . in)
1278 (lp in (cons head out)
1279 (1+ count)
1280 (+ (map-byte-length proc-slot) map-len))))))))
1281
1282 \f
1283
1284 ;;;
1285 ;;; Linking other sections of the ELF file, like the dynamic segment,
1286 ;;; the symbol table, etc.
1287 ;;;
1288
1289 ;; FIXME: Define these somewhere central, shared with C.
1290 (define *bytecode-major-version* #x0202)
1291 (define *bytecode-minor-version* 4)
1292
1293 (define (link-dynamic-section asm text rw rw-init frame-maps)
1294 "Link the dynamic section for an ELF image with bytecode @var{text},
1295 given the writable data section @var{rw} needing fixup from the
1296 procedure with label @var{rw-init}. @var{rw-init} may be false. If
1297 @var{rw} is true, it will be added to the GC roots at runtime."
1298 (define-syntax-rule (emit-dynamic-section word-size %set-uword! reloc-type)
1299 (let* ((endianness (asm-endianness asm))
1300 (words 6)
1301 (words (if rw (+ words 4) words))
1302 (words (if rw-init (+ words 2) words))
1303 (words (if frame-maps (+ words 2) words))
1304 (bv (make-bytevector (* word-size words) 0))
1305 (set-uword!
1306 (lambda (i uword)
1307 (%set-uword! bv (* i word-size) uword endianness)))
1308 (relocs '())
1309 (set-label!
1310 (lambda (i label)
1311 (set! relocs (cons (make-linker-reloc 'reloc-type
1312 (* i word-size) 0 label)
1313 relocs))
1314 (%set-uword! bv (* i word-size) 0 endianness))))
1315 (set-uword! 0 DT_GUILE_VM_VERSION)
1316 (set-uword! 1 (logior (ash *bytecode-major-version* 16)
1317 *bytecode-minor-version*))
1318 (set-uword! 2 DT_GUILE_ENTRY)
1319 (set-label! 3 '.rtl-text)
1320 (when rw
1321 ;; Add roots to GC.
1322 (set-uword! 4 DT_GUILE_GC_ROOT)
1323 (set-label! 5 '.data)
1324 (set-uword! 6 DT_GUILE_GC_ROOT_SZ)
1325 (set-uword! 7 (bytevector-length (linker-object-bv rw)))
1326 (when rw-init
1327 (set-uword! 8 DT_INIT) ; constants
1328 (set-label! 9 rw-init)))
1329 (when frame-maps
1330 (set-uword! (- words 4) DT_GUILE_FRAME_MAPS)
1331 (set-label! (- words 3) '.guile.frame-maps))
1332 (set-uword! (- words 2) DT_NULL)
1333 (set-uword! (- words 1) 0)
1334 (make-object asm '.dynamic bv relocs '()
1335 #:type SHT_DYNAMIC #:flags SHF_ALLOC)))
1336 (case (asm-word-size asm)
1337 ((4) (emit-dynamic-section 4 bytevector-u32-set! abs32/1))
1338 ((8) (emit-dynamic-section 8 bytevector-u64-set! abs64/1))
1339 (else (error "bad word size" asm))))
1340
1341 (define (link-shstrtab asm)
1342 "Link the string table for the section headers."
1343 (intern-section-name! asm ".shstrtab")
1344 (make-object asm '.shstrtab
1345 (link-string-table! (asm-shstrtab asm))
1346 '() '()
1347 #:type SHT_STRTAB #:flags 0))
1348
1349 (define (link-symtab text-section asm)
1350 (let* ((endianness (asm-endianness asm))
1351 (word-size (asm-word-size asm))
1352 (size (elf-symbol-len word-size))
1353 (meta (reverse (asm-meta asm)))
1354 (n (length meta))
1355 (strtab (make-string-table))
1356 (bv (make-bytevector (* n size) 0)))
1357 (define (intern-string! name)
1358 (string-table-intern! strtab (if name (symbol->string name) "")))
1359 (for-each
1360 (lambda (meta n)
1361 (let ((name (intern-string! (meta-name meta))))
1362 (write-elf-symbol bv (* n size) endianness word-size
1363 (make-elf-symbol
1364 #:name name
1365 ;; Symbol value and size are measured in
1366 ;; bytes, not u32s.
1367 #:value (* 4 (meta-low-pc meta))
1368 #:size (* 4 (- (meta-high-pc meta)
1369 (meta-low-pc meta)))
1370 #:type STT_FUNC
1371 #:visibility STV_HIDDEN
1372 #:shndx (elf-section-index text-section)))))
1373 meta (iota n))
1374 (let ((strtab (make-object asm '.strtab
1375 (link-string-table! strtab)
1376 '() '()
1377 #:type SHT_STRTAB #:flags 0)))
1378 (values (make-object asm '.symtab
1379 bv
1380 '() '()
1381 #:type SHT_SYMTAB #:flags 0 #:entsize size
1382 #:link (elf-section-index
1383 (linker-object-section strtab)))
1384 strtab))))
1385
1386 ;;; The .guile.arities section describes the arities that a function can
1387 ;;; have. It is in two parts: a sorted array of headers describing
1388 ;;; basic arities, and an array of links out to a string table (and in
1389 ;;; the case of keyword arguments, to the data section) for argument
1390 ;;; names. The whole thing is prefixed by a uint32 indicating the
1391 ;;; offset of the end of the headers array.
1392 ;;;
1393 ;;; The arity headers array is a packed array of structures of the form:
1394 ;;;
1395 ;;; struct arity_header {
1396 ;;; uint32_t low_pc;
1397 ;;; uint32_t high_pc;
1398 ;;; uint32_t offset;
1399 ;;; uint32_t flags;
1400 ;;; uint32_t nreq;
1401 ;;; uint32_t nopt;
1402 ;;; }
1403 ;;;
1404 ;;; All of the offsets and addresses are 32 bits. We can expand in the
1405 ;;; future to use 64-bit offsets if appropriate, but there are other
1406 ;;; aspects of bytecode that constrain us to a total image that fits in
1407 ;;; 32 bits, so for the moment we'll simplify the problem space.
1408 ;;;
1409 ;;; The following flags values are defined:
1410 ;;;
1411 ;;; #x1: has-rest?
1412 ;;; #x2: allow-other-keys?
1413 ;;; #x4: has-keyword-args?
1414 ;;; #x8: is-case-lambda?
1415 ;;; #x10: is-in-case-lambda?
1416 ;;;
1417 ;;; Functions with a single arity specify their number of required and
1418 ;;; optional arguments in nreq and nopt, and do not have the
1419 ;;; is-case-lambda? flag set. Their "offset" member links to an array
1420 ;;; of pointers into the associated .guile.arities.strtab string table,
1421 ;;; identifying the argument names. This offset is relative to the
1422 ;;; start of the .guile.arities section.
1423 ;;;
1424 ;;; If the arity has keyword arguments -- if has-keyword-args? is set in
1425 ;;; the flags -- the first uint32 pointed to by offset encodes a link to
1426 ;;; the "keyword indices" literal, in the data section. Then follow
1427 ;;; links for required arguments are first, in order, as uint32 values.
1428 ;;; Next follow the optionals, then the rest link if has-rest? is set.
1429 ;;; Unlike the other links, the kw-indices link points into the data
1430 ;;; section, and is relative to the ELF image as a whole.
1431 ;;;
1432 ;;; Functions with no arities have no arities information present in the
1433 ;;; .guile.arities section.
1434 ;;;
1435 ;;; Functions with multiple arities are preceded by a header with
1436 ;;; is-case-lambda? set. All other fields are 0, except low-pc and
1437 ;;; high-pc which should be the bounds of the whole function. Headers
1438 ;;; for the individual arities follow, with the is-in-case-lambda? flag
1439 ;;; set. In this way the whole headers array is sorted in increasing
1440 ;;; low-pc order, and case-lambda clauses are contained within the
1441 ;;; [low-pc, high-pc] of the case-lambda header.
1442
1443 ;; Length of the prefix to the arities section, in bytes.
1444 (define arities-prefix-len 4)
1445
1446 ;; Length of an arity header, in bytes.
1447 (define arity-header-len (* 6 4))
1448
1449 ;; The offset of "offset" within arity header, in bytes.
1450 (define arity-header-offset-offset (* 2 4))
1451
1452 (define-syntax-rule (pack-arity-flags has-rest? allow-other-keys?
1453 has-keyword-args? is-case-lambda?
1454 is-in-case-lambda?)
1455 (logior (if has-rest? (ash 1 0) 0)
1456 (if allow-other-keys? (ash 1 1) 0)
1457 (if has-keyword-args? (ash 1 2) 0)
1458 (if is-case-lambda? (ash 1 3) 0)
1459 (if is-in-case-lambda? (ash 1 4) 0)))
1460
1461 (define (meta-arities-size meta)
1462 (define (lambda-size arity)
1463 (+ arity-header-len
1464 (* 4 ;; name pointers
1465 (+ (if (pair? (arity-kw-indices arity)) 1 0)
1466 (length (arity-req arity))
1467 (length (arity-opt arity))
1468 (if (arity-rest arity) 1 0)))))
1469 (define (case-lambda-size arities)
1470 (fold +
1471 arity-header-len ;; case-lambda header
1472 (map lambda-size arities))) ;; the cases
1473 (match (meta-arities meta)
1474 (() 0)
1475 ((arity) (lambda-size arity))
1476 (arities (case-lambda-size arities))))
1477
1478 (define (write-arity-headers metas bv endianness)
1479 (define (write-arity-header* pos low-pc high-pc flags nreq nopt)
1480 (bytevector-u32-set! bv pos (* low-pc 4) endianness)
1481 (bytevector-u32-set! bv (+ pos 4) (* high-pc 4) endianness)
1482 (bytevector-u32-set! bv (+ pos 8) 0 endianness) ; offset
1483 (bytevector-u32-set! bv (+ pos 12) flags endianness)
1484 (bytevector-u32-set! bv (+ pos 16) nreq endianness)
1485 (bytevector-u32-set! bv (+ pos 20) nopt endianness))
1486 (define (write-arity-header pos arity in-case-lambda?)
1487 (write-arity-header* pos (arity-low-pc arity)
1488 (arity-high-pc arity)
1489 (pack-arity-flags (arity-rest arity)
1490 (arity-allow-other-keys? arity)
1491 (pair? (arity-kw-indices arity))
1492 #f
1493 in-case-lambda?)
1494 (length (arity-req arity))
1495 (length (arity-opt arity))))
1496 (let lp ((metas metas) (pos arities-prefix-len) (offsets '()))
1497 (match metas
1498 (()
1499 ;; Fill in the prefix.
1500 (bytevector-u32-set! bv 0 pos endianness)
1501 (values pos (reverse offsets)))
1502 ((meta . metas)
1503 (match (meta-arities meta)
1504 (() (lp metas pos offsets))
1505 ((arity)
1506 (write-arity-header pos arity #f)
1507 (lp metas
1508 (+ pos arity-header-len)
1509 (acons arity (+ pos arity-header-offset-offset) offsets)))
1510 (arities
1511 ;; Write a case-lambda header, then individual arities.
1512 ;; The case-lambda header's offset link is 0.
1513 (write-arity-header* pos (meta-low-pc meta) (meta-high-pc meta)
1514 (pack-arity-flags #f #f #f #t #f) 0 0)
1515 (let lp* ((arities arities) (pos (+ pos arity-header-len))
1516 (offsets offsets))
1517 (match arities
1518 (() (lp metas pos offsets))
1519 ((arity . arities)
1520 (write-arity-header pos arity #t)
1521 (lp* arities
1522 (+ pos arity-header-len)
1523 (acons arity
1524 (+ pos arity-header-offset-offset)
1525 offsets)))))))))))
1526
1527 (define (write-arity-links asm bv pos arity-offset-pairs strtab)
1528 (define (write-symbol sym pos)
1529 (bytevector-u32-set! bv pos
1530 (string-table-intern! strtab (symbol->string sym))
1531 (asm-endianness asm))
1532 (+ pos 4))
1533 (define (write-kw-indices pos kw-indices)
1534 ;; FIXME: Assert that kw-indices is already interned.
1535 (make-linker-reloc 'abs32/1 pos 0
1536 (intern-constant asm kw-indices)))
1537 (let lp ((pos pos) (pairs arity-offset-pairs) (relocs '()))
1538 (match pairs
1539 (()
1540 (unless (= pos (bytevector-length bv))
1541 (error "expected to fully fill the bytevector"
1542 pos (bytevector-length bv)))
1543 relocs)
1544 (((arity . offset) . pairs)
1545 (bytevector-u32-set! bv offset pos (asm-endianness asm))
1546 (call-with-values
1547 (lambda ()
1548 (match (arity-kw-indices arity)
1549 (() (values pos relocs))
1550 (kw-indices
1551 (values (+ pos 4)
1552 (cons (write-kw-indices pos kw-indices) relocs)))))
1553 (lambda (pos relocs)
1554 (lp (fold write-symbol
1555 pos
1556 (append (arity-req arity)
1557 (arity-opt arity)
1558 (cond
1559 ((arity-rest arity) => list)
1560 (else '()))))
1561 pairs
1562 relocs)))))))
1563
1564 (define (link-arities asm)
1565 (let* ((endianness (asm-endianness asm))
1566 (metas (reverse (asm-meta asm)))
1567 (size (fold (lambda (meta size)
1568 (+ size (meta-arities-size meta)))
1569 arities-prefix-len
1570 metas))
1571 (strtab (make-string-table))
1572 (bv (make-bytevector size 0)))
1573 (let ((kw-indices-relocs
1574 (call-with-values
1575 (lambda ()
1576 (write-arity-headers metas bv endianness))
1577 (lambda (pos arity-offset-pairs)
1578 (write-arity-links asm bv pos arity-offset-pairs strtab)))))
1579 (let ((strtab (make-object asm '.guile.arities.strtab
1580 (link-string-table! strtab)
1581 '() '()
1582 #:type SHT_STRTAB #:flags 0)))
1583 (values (make-object asm '.guile.arities
1584 bv
1585 kw-indices-relocs '()
1586 #:type SHT_PROGBITS #:flags 0
1587 #:link (elf-section-index
1588 (linker-object-section strtab)))
1589 strtab)))))
1590
1591 ;;;
1592 ;;; The .guile.docstrs section is a packed, sorted array of (pc, str)
1593 ;;; values. Pc and str are both 32 bits wide. (Either could change to
1594 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1595 ;;; entry to a program, relative to the start of the text section, in
1596 ;;; bytes, and str is an index into the associated .guile.docstrs.strtab
1597 ;;; string table section.
1598 ;;;
1599
1600 ;; The size of a docstrs entry, in bytes.
1601 (define docstr-size 8)
1602
1603 (define (link-docstrs asm)
1604 (define (find-docstrings)
1605 (filter-map (lambda (meta)
1606 (define (is-documentation? pair)
1607 (eq? (car pair) 'documentation))
1608 (let* ((props (meta-properties meta))
1609 (tail (find-tail is-documentation? props)))
1610 (and tail
1611 (not (find-tail is-documentation? (cdr tail)))
1612 (string? (cdar tail))
1613 (cons (* 4 (meta-low-pc meta)) (cdar tail)))))
1614 (reverse (asm-meta asm))))
1615 (let* ((endianness (asm-endianness asm))
1616 (docstrings (find-docstrings))
1617 (strtab (make-string-table))
1618 (bv (make-bytevector (* (length docstrings) docstr-size) 0)))
1619 (fold (lambda (pair pos)
1620 (match pair
1621 ((pc . string)
1622 (bytevector-u32-set! bv pos pc endianness)
1623 (bytevector-u32-set! bv (+ pos 4)
1624 (string-table-intern! strtab string)
1625 endianness)
1626 (+ pos docstr-size))))
1627 0
1628 docstrings)
1629 (let ((strtab (make-object asm '.guile.docstrs.strtab
1630 (link-string-table! strtab)
1631 '() '()
1632 #:type SHT_STRTAB #:flags 0)))
1633 (values (make-object asm '.guile.docstrs
1634 bv
1635 '() '()
1636 #:type SHT_PROGBITS #:flags 0
1637 #:link (elf-section-index
1638 (linker-object-section strtab)))
1639 strtab))))
1640
1641 ;;;
1642 ;;; The .guile.procprops section is a packed, sorted array of (pc, addr)
1643 ;;; values. Pc and addr are both 32 bits wide. (Either could change to
1644 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1645 ;;; entry to a program, relative to the start of the text section, and
1646 ;;; addr is the address of the associated properties alist, relative to
1647 ;;; the start of the ELF image.
1648 ;;;
1649 ;;; Since procedure properties are stored in the data sections, we need
1650 ;;; to link the procedures property section first. (Note that this
1651 ;;; constraint does not apply to the arities section, which may
1652 ;;; reference the data sections via the kw-indices literal, because
1653 ;;; assembling the text section already makes sure that the kw-indices
1654 ;;; are interned.)
1655 ;;;
1656
1657 ;; The size of a procprops entry, in bytes.
1658 (define procprops-size 8)
1659
1660 (define (link-procprops asm)
1661 (define (assoc-remove-one alist key value-pred)
1662 (match alist
1663 (() '())
1664 ((((? (lambda (x) (eq? x key))) . value) . alist)
1665 (if (value-pred value)
1666 alist
1667 (acons key value alist)))
1668 (((k . v) . alist)
1669 (acons k v (assoc-remove-one alist key value-pred)))))
1670 (define (props-without-name-or-docstring meta)
1671 (assoc-remove-one
1672 (assoc-remove-one (meta-properties meta) 'name (lambda (x) #t))
1673 'documentation
1674 string?))
1675 (define (find-procprops)
1676 (filter-map (lambda (meta)
1677 (let ((props (props-without-name-or-docstring meta)))
1678 (and (pair? props)
1679 (cons (* 4 (meta-low-pc meta)) props))))
1680 (reverse (asm-meta asm))))
1681 (let* ((endianness (asm-endianness asm))
1682 (procprops (find-procprops))
1683 (bv (make-bytevector (* (length procprops) procprops-size) 0)))
1684 (let lp ((procprops procprops) (pos 0) (relocs '()))
1685 (match procprops
1686 (()
1687 (make-object asm '.guile.procprops
1688 bv
1689 relocs '()
1690 #:type SHT_PROGBITS #:flags 0))
1691 (((pc . props) . procprops)
1692 (bytevector-u32-set! bv pos pc endianness)
1693 (lp procprops
1694 (+ pos procprops-size)
1695 (cons (make-linker-reloc 'abs32/1 (+ pos 4) 0
1696 (intern-constant asm props))
1697 relocs)))))))
1698
1699 ;;;
1700 ;;; The DWARF .debug_info, .debug_abbrev, .debug_str, and .debug_loc
1701 ;;; sections provide line number and local variable liveness
1702 ;;; information. Their format is defined by the DWARF
1703 ;;; specifications.
1704 ;;;
1705
1706 (define (asm-language asm)
1707 ;; FIXME: Plumb language through to the assembler.
1708 'scheme)
1709
1710 ;; -> 5 values: .debug_info, .debug_abbrev, .debug_str, .debug_loc, .debug_lines
1711 (define (link-debug asm)
1712 (define (put-s8 port val)
1713 (let ((bv (make-bytevector 1)))
1714 (bytevector-s8-set! bv 0 val)
1715 (put-bytevector port bv)))
1716
1717 (define (put-u16 port val)
1718 (let ((bv (make-bytevector 2)))
1719 (bytevector-u16-set! bv 0 val (asm-endianness asm))
1720 (put-bytevector port bv)))
1721
1722 (define (put-u32 port val)
1723 (let ((bv (make-bytevector 4)))
1724 (bytevector-u32-set! bv 0 val (asm-endianness asm))
1725 (put-bytevector port bv)))
1726
1727 (define (put-u64 port val)
1728 (let ((bv (make-bytevector 8)))
1729 (bytevector-u64-set! bv 0 val (asm-endianness asm))
1730 (put-bytevector port bv)))
1731
1732 (define (put-uleb128 port val)
1733 (let lp ((val val))
1734 (let ((next (ash val -7)))
1735 (if (zero? next)
1736 (put-u8 port val)
1737 (begin
1738 (put-u8 port (logior #x80 (logand val #x7f)))
1739 (lp next))))))
1740
1741 (define (put-sleb128 port val)
1742 (let lp ((val val))
1743 (if (<= 0 (+ val 64) 127)
1744 (put-u8 port (logand val #x7f))
1745 (begin
1746 (put-u8 port (logior #x80 (logand val #x7f)))
1747 (lp (ash val -7))))))
1748
1749 (define (port-position port)
1750 (seek port 0 SEEK_CUR))
1751
1752 (define (meta->subprogram-die meta)
1753 `(subprogram
1754 (@ ,@(cond
1755 ((meta-name meta)
1756 => (lambda (name) `((name ,(symbol->string name)))))
1757 (else
1758 '()))
1759 (low-pc ,(meta-label meta))
1760 (high-pc ,(* 4 (- (meta-high-pc meta) (meta-low-pc meta)))))))
1761
1762 (define (make-compile-unit-die asm)
1763 `(compile-unit
1764 (@ (producer ,(string-append "Guile " (version)))
1765 (language ,(asm-language asm))
1766 (low-pc .rtl-text)
1767 (high-pc ,(* 4 (asm-pos asm)))
1768 (stmt-list 0))
1769 ,@(map meta->subprogram-die (reverse (asm-meta asm)))))
1770
1771 (let-values (((die-port get-die-bv) (open-bytevector-output-port))
1772 ((die-relocs) '())
1773 ((abbrev-port get-abbrev-bv) (open-bytevector-output-port))
1774 ;; (tag has-kids? attrs forms) -> code
1775 ((abbrevs) vlist-null)
1776 ((strtab) (make-string-table))
1777 ((line-port get-line-bv) (open-bytevector-output-port))
1778 ((line-relocs) '())
1779 ;; file -> code
1780 ((files) vlist-null))
1781
1782 (define (write-abbrev code tag has-children? attrs forms)
1783 (put-uleb128 abbrev-port code)
1784 (put-uleb128 abbrev-port (tag-name->code tag))
1785 (put-u8 abbrev-port (children-name->code (if has-children? 'yes 'no)))
1786 (for-each (lambda (attr form)
1787 (put-uleb128 abbrev-port (attribute-name->code attr))
1788 (put-uleb128 abbrev-port (form-name->code form)))
1789 attrs forms)
1790 (put-uleb128 abbrev-port 0)
1791 (put-uleb128 abbrev-port 0))
1792
1793 (define (intern-abbrev tag has-children? attrs forms)
1794 (let ((key (list tag has-children? attrs forms)))
1795 (match (vhash-assoc key abbrevs)
1796 ((_ . code) code)
1797 (#f (let ((code (1+ (vlist-length abbrevs))))
1798 (set! abbrevs (vhash-cons key code abbrevs))
1799 (write-abbrev code tag has-children? attrs forms)
1800 code)))))
1801
1802 (define (intern-file file)
1803 (match (vhash-assoc file files)
1804 ((_ . code) code)
1805 (#f (let ((code (1+ (vlist-length files))))
1806 (set! files (vhash-cons file code files))
1807 code))))
1808
1809 (define (write-sources)
1810 ;; Choose line base and line range values that will allow for an
1811 ;; address advance range of 16 words. The special opcode range is
1812 ;; from 10 to 255, so 246 values.
1813 (define base -4)
1814 (define range 15)
1815
1816 (let lp ((sources (asm-sources asm)) (out '()))
1817 (match sources
1818 (((pc . s) . sources)
1819 (let ((file (assq-ref s 'filename))
1820 (line (assq-ref s 'line))
1821 (col (assq-ref s 'column)))
1822 (lp sources
1823 ;; Guile line and column numbers are 0-indexed, but
1824 ;; they are 1-indexed for DWARF.
1825 (cons (list pc
1826 (if file (intern-file file) 0)
1827 (if line (1+ line))
1828 (if col (1+ col)))
1829 out))))
1830 (()
1831 ;; Compilation unit header for .debug_line. We write in
1832 ;; DWARF 2 format because more tools understand it than DWARF
1833 ;; 4, which incompatibly adds another field to this header.
1834
1835 (put-u32 line-port 0) ; Length; will patch later.
1836 (put-u16 line-port 2) ; DWARF 2 format.
1837 (put-u32 line-port 0) ; Prologue length; will patch later.
1838 (put-u8 line-port 4) ; Minimum instruction length: 4 bytes.
1839 (put-u8 line-port 1) ; Default is-stmt: true.
1840
1841 (put-s8 line-port base) ; Line base. See the DWARF standard.
1842 (put-u8 line-port range) ; Line range. See the DWARF standard.
1843 (put-u8 line-port 10) ; Opcode base: the first "special" opcode.
1844
1845 ;; A table of the number of uleb128 arguments taken by each
1846 ;; of the standard opcodes.
1847 (put-u8 line-port 0) ; 1: copy
1848 (put-u8 line-port 1) ; 2: advance-pc
1849 (put-u8 line-port 1) ; 3: advance-line
1850 (put-u8 line-port 1) ; 4: set-file
1851 (put-u8 line-port 1) ; 5: set-column
1852 (put-u8 line-port 0) ; 6: negate-stmt
1853 (put-u8 line-port 0) ; 7: set-basic-block
1854 (put-u8 line-port 0) ; 8: const-add-pc
1855 (put-u8 line-port 1) ; 9: fixed-advance-pc
1856
1857 ;; Include directories, as a zero-terminated sequence of
1858 ;; nul-terminated strings. Nothing, for the moment.
1859 (put-u8 line-port 0)
1860
1861 ;; File table. For each file that contributes to this
1862 ;; compilation unit, a nul-terminated file name string, and a
1863 ;; uleb128 for each of directory the file was found in, the
1864 ;; modification time, and the file's size in bytes. We pass
1865 ;; zero for the latter three fields.
1866 (vlist-fold-right
1867 (lambda (pair seed)
1868 (match pair
1869 ((file . code)
1870 (put-bytevector line-port (string->utf8 file))
1871 (put-u8 line-port 0)
1872 (put-uleb128 line-port 0) ; directory
1873 (put-uleb128 line-port 0) ; mtime
1874 (put-uleb128 line-port 0))) ; size
1875 seed)
1876 #f
1877 files)
1878 (put-u8 line-port 0) ; 0 byte terminating file list.
1879
1880 ;; Patch prologue length.
1881 (let ((offset (port-position line-port)))
1882 (seek line-port 6 SEEK_SET)
1883 (put-u32 line-port (- offset 10))
1884 (seek line-port offset SEEK_SET))
1885
1886 ;; Now write the statement program.
1887 (let ()
1888 (define (extended-op opcode payload-len)
1889 (put-u8 line-port 0) ; extended op
1890 (put-uleb128 line-port (1+ payload-len)) ; payload-len + opcode
1891 (put-uleb128 line-port opcode))
1892 (define (set-address sym)
1893 (define (add-reloc! kind)
1894 (set! line-relocs
1895 (cons (make-linker-reloc kind
1896 (port-position line-port)
1897 0
1898 sym)
1899 line-relocs)))
1900 (match (asm-word-size asm)
1901 (4
1902 (extended-op 2 4)
1903 (add-reloc! 'abs32/1)
1904 (put-u32 line-port 0))
1905 (8
1906 (extended-op 2 8)
1907 (add-reloc! 'abs64/1)
1908 (put-u64 line-port 0))))
1909 (define (end-sequence pc)
1910 (let ((pc-inc (- (asm-pos asm) pc)))
1911 (put-u8 line-port 2) ; advance-pc
1912 (put-uleb128 line-port pc-inc))
1913 (extended-op 1 0))
1914 (define (advance-pc pc-inc line-inc)
1915 (let ((spec (+ (- line-inc base) (* pc-inc range) 10)))
1916 (cond
1917 ((or (< line-inc base) (>= line-inc (+ base range)))
1918 (advance-line line-inc)
1919 (advance-pc pc-inc 0))
1920 ((<= spec 255)
1921 (put-u8 line-port spec))
1922 ((< spec 500)
1923 (put-u8 line-port 8) ; const-advance-pc
1924 (advance-pc (- pc-inc (floor/ (- 255 10) range))
1925 line-inc))
1926 (else
1927 (put-u8 line-port 2) ; advance-pc
1928 (put-uleb128 line-port pc-inc)
1929 (advance-pc 0 line-inc)))))
1930 (define (advance-line inc)
1931 (put-u8 line-port 3)
1932 (put-sleb128 line-port inc))
1933 (define (set-file file)
1934 (put-u8 line-port 4)
1935 (put-uleb128 line-port file))
1936 (define (set-column col)
1937 (put-u8 line-port 5)
1938 (put-uleb128 line-port col))
1939
1940 (set-address '.rtl-text)
1941
1942 (let lp ((in out) (pc 0) (file 1) (line 1) (col 0))
1943 (match in
1944 (()
1945 (when (null? out)
1946 ;; There was no source info in the first place. Set
1947 ;; file register to 0 before adding final row.
1948 (set-file 0))
1949 (end-sequence pc))
1950 (((pc* file* line* col*) . in*)
1951 (cond
1952 ((and (eqv? file file*) (eqv? line line*) (eqv? col col*))
1953 (lp in* pc file line col))
1954 (else
1955 (unless (eqv? col col*)
1956 (set-column col*))
1957 (unless (eqv? file file*)
1958 (set-file file*))
1959 (advance-pc (- pc* pc) (- line* line))
1960 (lp in* pc* file* line* col*)))))))))))
1961
1962 (define (compute-code attr val)
1963 (match attr
1964 ('name (string-table-intern! strtab val))
1965 ('low-pc val)
1966 ('high-pc val)
1967 ('producer (string-table-intern! strtab val))
1968 ('language (language-name->code val))
1969 ('stmt-list val)))
1970
1971 (define (choose-form attr val code)
1972 (cond
1973 ((string? val) 'strp)
1974 ((eq? attr 'stmt-list) 'sec-offset)
1975 ((eq? attr 'low-pc) 'addr)
1976 ((exact-integer? code)
1977 (cond
1978 ((< code 0) 'sleb128)
1979 ((<= code #xff) 'data1)
1980 ((<= code #xffff) 'data2)
1981 ((<= code #xffffffff) 'data4)
1982 ((<= code #xffffffffffffffff) 'data8)
1983 (else 'uleb128)))
1984 (else (error "unhandled case" attr val code))))
1985
1986 (define (add-die-relocation! kind sym)
1987 (set! die-relocs
1988 (cons (make-linker-reloc kind (port-position die-port) 0 sym)
1989 die-relocs)))
1990
1991 (define (write-value code form)
1992 (match form
1993 ('data1 (put-u8 die-port code))
1994 ('data2 (put-u16 die-port code))
1995 ('data4 (put-u32 die-port code))
1996 ('data8 (put-u64 die-port code))
1997 ('uleb128 (put-uleb128 die-port code))
1998 ('sleb128 (put-sleb128 die-port code))
1999 ('addr
2000 (match (asm-word-size asm)
2001 (4
2002 (add-die-relocation! 'abs32/1 code)
2003 (put-u32 die-port 0))
2004 (8
2005 (add-die-relocation! 'abs64/1 code)
2006 (put-u64 die-port 0))))
2007 ('sec-offset (put-u32 die-port code))
2008 ('strp (put-u32 die-port code))))
2009
2010 (define (write-die die)
2011 (match die
2012 ((tag ('@ (attrs vals) ...) children ...)
2013 (let* ((codes (map compute-code attrs vals))
2014 (forms (map choose-form attrs vals codes))
2015 (has-children? (not (null? children)))
2016 (abbrev-code (intern-abbrev tag has-children? attrs forms)))
2017 (put-uleb128 die-port abbrev-code)
2018 (for-each write-value codes forms)
2019 (when has-children?
2020 (for-each write-die children)
2021 (put-uleb128 die-port 0))))))
2022
2023 ;; Compilation unit header.
2024 (put-u32 die-port 0) ; Length; will patch later.
2025 (put-u16 die-port 4) ; DWARF 4.
2026 (put-u32 die-port 0) ; Abbrevs offset.
2027 (put-u8 die-port (asm-word-size asm)) ; Address size.
2028
2029 (write-die (make-compile-unit-die asm))
2030
2031 ;; Terminate the abbrevs list.
2032 (put-uleb128 abbrev-port 0)
2033
2034 (write-sources)
2035
2036 (values (let ((bv (get-die-bv)))
2037 ;; Patch DWARF32 length.
2038 (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
2039 (asm-endianness asm))
2040 (make-object asm '.debug_info bv die-relocs '()
2041 #:type SHT_PROGBITS #:flags 0))
2042 (make-object asm '.debug_abbrev (get-abbrev-bv) '() '()
2043 #:type SHT_PROGBITS #:flags 0)
2044 (make-object asm '.debug_str (link-string-table! strtab) '() '()
2045 #:type SHT_PROGBITS #:flags 0)
2046 (make-object asm '.debug_loc #vu8() '() '()
2047 #:type SHT_PROGBITS #:flags 0)
2048 (let ((bv (get-line-bv)))
2049 ;; Patch DWARF32 length.
2050 (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
2051 (asm-endianness asm))
2052 (make-object asm '.debug_line bv line-relocs '()
2053 #:type SHT_PROGBITS #:flags 0)))))
2054
2055 (define (link-objects asm)
2056 (let*-values (;; Link procprops before constants, because it probably
2057 ;; interns more constants.
2058 ((procprops) (link-procprops asm))
2059 ((ro rw rw-init) (link-constants asm))
2060 ;; Link text object after constants, so that the
2061 ;; constants initializer gets included.
2062 ((text) (link-text-object asm))
2063 ((frame-maps) (link-frame-maps asm))
2064 ((dt) (link-dynamic-section asm text rw rw-init frame-maps))
2065 ((symtab strtab) (link-symtab (linker-object-section text) asm))
2066 ((arities arities-strtab) (link-arities asm))
2067 ((docstrs docstrs-strtab) (link-docstrs asm))
2068 ((dinfo dabbrev dstrtab dloc dline) (link-debug asm))
2069 ;; This needs to be linked last, because linking other
2070 ;; sections adds entries to the string table.
2071 ((shstrtab) (link-shstrtab asm)))
2072 (filter identity
2073 (list text ro frame-maps rw dt symtab strtab
2074 arities arities-strtab
2075 docstrs docstrs-strtab procprops
2076 dinfo dabbrev dstrtab dloc dline
2077 shstrtab))))
2078
2079
2080 \f
2081
2082 ;;;
2083 ;;; High-level public interfaces.
2084 ;;;
2085
2086 (define* (link-assembly asm #:key (page-aligned? #t))
2087 "Produce an ELF image from the code and data emitted into @var{asm}.
2088 The result is a bytevector, by default linked so that read-only and
2089 writable data are on separate pages. Pass @code{#:page-aligned? #f} to
2090 disable this behavior."
2091 (link-elf (link-objects asm) #:page-aligned? page-aligned?))