7bab89b392cc83dc677e35763a3f2fbea5198560
[sbcl.git] / src / code / host-alieneval.lisp
1 ;;;; the part of the Alien implementation which is needed at
2 ;;;; cross-compilation time
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!ALIEN")
14
15 (/show0 "host-alieneval.lisp 15")
16 \f
17 ;;;; utility functions
18
19 (defun align-offset (offset alignment)
20   (let ((extra (rem offset alignment)))
21     (if (zerop extra) offset (+ offset (- alignment extra)))))
22
23 (defun guess-alignment (bits)
24   (cond ((null bits) nil)
25         #!-(or x86 (and ppc darwin)) ((> bits 32) 64)
26         ((> bits 16) 32)
27         ((> bits 8) 16)
28         ((> bits 1) 8)
29         (t 1)))
30 \f
31 ;;;; ALIEN-TYPE-INFO stuff
32
33 (eval-when (#-sb-xc :compile-toplevel :execute :load-toplevel)
34
35 (defstruct (alien-type-class (:copier nil))
36   (name nil :type symbol)
37   (include nil :type (or null alien-type-class))
38   (unparse nil :type (or null function))
39   (type= nil :type (or null function))
40   (lisp-rep nil :type (or null function))
41   (alien-rep nil :type (or null function))
42   (extract-gen nil :type (or null function))
43   (deposit-gen nil :type (or null function))
44   (naturalize-gen nil :type (or null function))
45   (deport-gen nil :type (or null function))
46   ;; Cast?
47   (arg-tn nil :type (or null function))
48   (result-tn nil :type (or null function))
49   (subtypep nil :type (or null function)))
50 (def!method print-object ((type-class alien-type-class) stream)
51   (print-unreadable-object (type-class stream :type t)
52     (prin1 (alien-type-class-name type-class) stream)))
53
54 (defun alien-type-class-or-lose (name)
55   (or (gethash name *alien-type-classes*)
56       (error "no alien type class ~S" name)))
57
58 (defun create-alien-type-class-if-necessary (name include)
59   (let ((old (gethash name *alien-type-classes*))
60         (include (and include (alien-type-class-or-lose include))))
61     (if old
62         (setf (alien-type-class-include old) include)
63         (setf (gethash name *alien-type-classes*)
64               (make-alien-type-class :name name :include include)))))
65
66 (defparameter *method-slot-alist*
67   '((:unparse . alien-type-class-unparse)
68     (:type= . alien-type-class-type=)
69     (:subtypep . alien-type-class-subtypep)
70     (:lisp-rep . alien-type-class-lisp-rep)
71     (:alien-rep . alien-type-class-alien-rep)
72     (:extract-gen . alien-type-class-extract-gen)
73     (:deposit-gen . alien-type-class-deposit-gen)
74     (:naturalize-gen . alien-type-class-naturalize-gen)
75     (:deport-gen . alien-type-class-deport-gen)
76     ;; cast?
77     (:arg-tn . alien-type-class-arg-tn)
78     (:result-tn . alien-type-class-result-tn)))
79
80 (defun method-slot (method)
81   (cdr (or (assoc method *method-slot-alist*)
82            (error "no method ~S" method))))
83
84 ) ; EVAL-WHEN
85
86 ;;; We define a keyword "BOA" constructor so that we can reference the
87 ;;; slot names in init forms.
88 (def!macro define-alien-type-class ((name &key include include-args)
89                                     &rest slots)
90   (let ((defstruct-name (symbolicate "ALIEN-" name "-TYPE")))
91     (multiple-value-bind (include include-defstruct overrides)
92         (etypecase include
93           (null
94            (values nil 'alien-type nil))
95           (symbol
96            (values
97             include
98             (symbolicate "ALIEN-" include "-TYPE")
99             nil))
100           (list
101            (values
102             (car include)
103             (symbolicate "ALIEN-" (car include) "-TYPE")
104             (cdr include))))
105       `(progn
106          (eval-when (:compile-toplevel :load-toplevel :execute)
107            (create-alien-type-class-if-necessary ',name ',(or include 'root)))
108          (def!struct (,defstruct-name
109                         (:include ,include-defstruct
110                                   (class ',name)
111                                   ,@overrides)
112                         (:constructor
113                          ,(symbolicate "MAKE-" defstruct-name)
114                          (&key class bits alignment
115                                ,@(mapcar (lambda (x)
116                                            (if (atom x) x (car x)))
117                                          slots)
118                                ,@include-args
119                                ;; KLUDGE
120                                &aux (alignment (or alignment (guess-alignment bits))))))
121            ,@slots)))))
122
123 (def!macro define-alien-type-method ((class method) lambda-list &rest body)
124   (let ((defun-name (symbolicate class "-" method "-METHOD")))
125     `(progn
126        (defun ,defun-name ,lambda-list
127          ,@body)
128        (setf (,(method-slot method) (alien-type-class-or-lose ',class))
129              #',defun-name))))
130
131 (def!macro invoke-alien-type-method (method type &rest args)
132   (let ((slot (method-slot method)))
133     (once-only ((type type))
134       `(funcall (do ((class (alien-type-class-or-lose (alien-type-class ,type))
135                             (alien-type-class-include class)))
136                     ((null class)
137                      (error "method ~S not defined for ~S"
138                             ',method (alien-type-class ,type)))
139                   (let ((fn (,slot class)))
140                     (when fn
141                       (return fn))))
142                 ,type ,@args))))
143 \f
144 ;;;; type parsing and unparsing
145
146 ;;; CMU CL used COMPILER-LET to bind *AUXILIARY-TYPE-DEFINITIONS*, and
147 ;;; COMPILER-LET is no longer supported by ANSI or SBCL. Instead, we
148 ;;; follow the suggestion in CLTL2 of using SYMBOL-MACROLET to achieve
149 ;;; a similar effect.
150 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
151   (defun auxiliary-type-definitions (env)
152     (multiple-value-bind (result expanded-p)
153         (sb!xc:macroexpand '&auxiliary-type-definitions& env)
154       (if expanded-p
155           result
156           ;; This is like having the global symbol-macro definition be
157           ;; NIL, but global symbol-macros make me vaguely queasy, so
158           ;; I do it this way instead.
159           nil))))
160
161 ;;; Process stuff in a new scope.
162 (def!macro with-auxiliary-alien-types (env &body body)
163   ``(symbol-macrolet ((&auxiliary-type-definitions&
164                        ,(append *new-auxiliary-types*
165                                 (auxiliary-type-definitions ,env))))
166       ,(let ((*new-auxiliary-types* nil))
167          ,@body)))
168
169 ;;; Parse TYPE as an alien type specifier and return the resultant
170 ;;; ALIEN-TYPE structure.
171 (defun parse-alien-type (type env)
172   (declare (type (or sb!kernel:lexenv null) env))
173   (if (consp type)
174       (let ((translator (info :alien-type :translator (car type))))
175         (unless translator
176           (error "unknown alien type: ~S" type))
177         (funcall translator type env))
178       (ecase (info :alien-type :kind type)
179         (:primitive
180          (let ((translator (info :alien-type :translator type)))
181            (unless translator
182              (error "no translator for primitive alien type ~S" type))
183            (funcall translator (list type) env)))
184         (:defined
185          (or (info :alien-type :definition type)
186              (error "no definition for alien type ~S" type)))
187         (:unknown
188          (error "unknown alien type: ~S" type)))))
189
190 (defun auxiliary-alien-type (kind name env)
191   (declare (type (or sb!kernel:lexenv null) env))
192   (flet ((aux-defn-matches (x)
193            (and (eq (first x) kind) (eq (second x) name))))
194     (let ((in-auxiliaries
195            (or (find-if #'aux-defn-matches *new-auxiliary-types*)
196                (find-if #'aux-defn-matches (auxiliary-type-definitions env)))))
197       (if in-auxiliaries
198           (values (third in-auxiliaries) t)
199           (ecase kind
200             (:struct
201              (info :alien-type :struct name))
202             (:union
203              (info :alien-type :union name))
204             (:enum
205              (info :alien-type :enum name)))))))
206
207 (defun (setf auxiliary-alien-type) (new-value kind name env)
208   (declare (type (or sb!kernel:lexenv null) env))
209   (flet ((aux-defn-matches (x)
210            (and (eq (first x) kind) (eq (second x) name))))
211     (when (find-if #'aux-defn-matches *new-auxiliary-types*)
212       (error "attempt to multiply define ~A ~S" kind name))
213     (when (find-if #'aux-defn-matches (auxiliary-type-definitions env))
214       (error "attempt to shadow definition of ~A ~S" kind name)))
215   (push (list kind name new-value) *new-auxiliary-types*)
216   new-value)
217
218 (defun verify-local-auxiliaries-okay ()
219   (dolist (info *new-auxiliary-types*)
220     (destructuring-bind (kind name defn) info
221       (declare (ignore defn))
222       (when (ecase kind
223               (:struct
224                (info :alien-type :struct name))
225               (:union
226                (info :alien-type :union name))
227               (:enum
228                (info :alien-type :enum name)))
229         (error "attempt to shadow definition of ~A ~S" kind name)))))
230
231 (defun unparse-alien-type (type)
232   #!+sb-doc
233   "Convert the alien-type structure TYPE back into a list specification of
234    the type."
235   (declare (type alien-type type))
236   (let ((*record-types-already-unparsed* nil))
237     (%unparse-alien-type type)))
238
239 ;;; Does all the work of UNPARSE-ALIEN-TYPE. It's separate because we
240 ;;; need to recurse inside the binding of
241 ;;; *RECORD-TYPES-ALREADY-UNPARSED*.
242 (defun %unparse-alien-type (type)
243   (invoke-alien-type-method :unparse type))
244 \f
245 ;;;; alien type defining stuff
246
247 (def!macro define-alien-type-translator (name lambda-list &body body)
248   (with-unique-names (whole env)
249     (let ((defun-name (symbolicate "ALIEN-" name "-TYPE-TRANSLATOR")))
250       (multiple-value-bind (body decls docs)
251           (sb!kernel:parse-defmacro lambda-list whole body name
252                                     'define-alien-type-translator
253                                     :environment env)
254         `(eval-when (:compile-toplevel :load-toplevel :execute)
255            (defun ,defun-name (,whole ,env)
256              (declare (ignorable ,env))
257              ,@decls
258              (block ,name
259                ,body))
260            (%define-alien-type-translator ',name #',defun-name ,docs))))))
261
262 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
263   (defun %define-alien-type-translator (name translator docs)
264     (declare (ignore docs))
265     (setf (info :alien-type :kind name) :primitive)
266     (setf (info :alien-type :translator name) translator)
267     (clear-info :alien-type :definition name)
268     #+nil
269     (setf (fdocumentation name 'alien-type) docs)
270     name))
271
272 (def!macro define-alien-type (name type &environment env)
273   #!+sb-doc
274   "Define the alien type NAME to be equivalent to TYPE. Name may be NIL for
275    STRUCT and UNION types, in which case the name is taken from the type
276    specifier."
277   (with-auxiliary-alien-types env
278     (let ((alien-type (parse-alien-type type env)))
279       `(eval-when (:compile-toplevel :load-toplevel :execute)
280          ,@(when *new-auxiliary-types*
281              `((%def-auxiliary-alien-types ',*new-auxiliary-types*)))
282          ,@(when name
283              `((%define-alien-type ',name ',alien-type)))))))
284 (def!macro def-alien-type (&rest rest)
285   (deprecation-warning 'def-alien-type 'define-alien-type)
286   `(define-alien-type ,@rest))
287
288 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
289   (defun %def-auxiliary-alien-types (types)
290     (dolist (info types)
291       ;; Clear up the type we're about to define from the toplevel
292       ;; *new-auxiliary-types* (local scopes take care of themselves).
293       ;; Unless this is done we never actually get back the full type
294       ;; from INFO, since the *new-auxiliary-types* have precendence.
295       (setf *new-auxiliary-types*
296             (remove info *new-auxiliary-types*
297                     :test (lambda (a b)
298                             (and (eq (first a) (first b))
299                                  (eq (second a) (second b))))))
300       (destructuring-bind (kind name defn) info
301         (macrolet ((frob (kind)
302                          `(let ((old (info :alien-type ,kind name)))
303                             (unless (or (null old) (alien-type-= old defn))
304                               (warn
305                                "redefining ~A ~S to be:~%  ~S,~%was:~%  ~S"
306                                kind name defn old))
307                             (setf (info :alien-type ,kind name) defn))))
308           (ecase kind
309             (:struct (frob :struct))
310             (:union (frob :union))
311             (:enum (frob :enum)))))))
312   (defun %define-alien-type (name new)
313     (ecase (info :alien-type :kind name)
314       (:primitive
315        (error "~S is a built-in alien type." name))
316       (:defined
317        (let ((old (info :alien-type :definition name)))
318          (unless (or (null old) (alien-type-= new old))
319            (warn "redefining ~S to be:~%  ~S,~%was~%  ~S"
320                  name
321                  (unparse-alien-type new)
322                  (unparse-alien-type old)))))
323       (:unknown))
324     (setf (info :alien-type :definition name) new)
325     (setf (info :alien-type :kind name) :defined)
326     name))
327 \f
328 ;;;; the root alien type
329
330 (eval-when (:compile-toplevel :load-toplevel :execute)
331   (create-alien-type-class-if-necessary 'root nil))
332
333 (def!struct (alien-type
334              (:make-load-form-fun sb!kernel:just-dump-it-normally)
335              (:constructor make-alien-type (&key class bits alignment
336                                             &aux (alignment (or alignment (guess-alignment bits))))))
337   (class 'root :type symbol)
338   (bits nil :type (or null unsigned-byte))
339   (alignment nil :type (or null unsigned-byte)))
340 (def!method print-object ((type alien-type) stream)
341   (print-unreadable-object (type stream :type t)
342     (prin1 (unparse-alien-type type) stream)))
343 \f
344 ;;;; the SAP type
345
346 (define-alien-type-class (system-area-pointer))
347
348 (define-alien-type-translator system-area-pointer ()
349   (make-alien-system-area-pointer-type
350    :bits #!-alpha sb!vm:n-word-bits #!+alpha 64))
351
352 (define-alien-type-method (system-area-pointer :unparse) (type)
353   (declare (ignore type))
354   'system-area-pointer)
355
356 (define-alien-type-method (system-area-pointer :lisp-rep) (type)
357   (declare (ignore type))
358   'system-area-pointer)
359
360 (define-alien-type-method (system-area-pointer :alien-rep) (type)
361   (declare (ignore type))
362   'system-area-pointer)
363
364 (define-alien-type-method (system-area-pointer :naturalize-gen) (type alien)
365   (declare (ignore type))
366   alien)
367
368 (define-alien-type-method (system-area-pointer :deport-gen) (type object)
369   (declare (ignore type))
370   (/noshow "doing alien type method SYSTEM-AREA-POINTER :DEPORT-GEN" object)
371   object)
372
373 (define-alien-type-method (system-area-pointer :extract-gen) (type sap offset)
374   (declare (ignore type))
375   `(sap-ref-sap ,sap (/ ,offset sb!vm:n-byte-bits)))
376 \f
377 ;;;; the ALIEN-VALUE type
378
379 (define-alien-type-class (alien-value :include system-area-pointer))
380
381 (define-alien-type-method (alien-value :lisp-rep) (type)
382   (declare (ignore type))
383   nil)
384
385 (define-alien-type-method (alien-value :naturalize-gen) (type alien)
386   `(%sap-alien ,alien ',type))
387
388 (define-alien-type-method (alien-value :deport-gen) (type value)
389   (declare (ignore type))
390   (/noshow "doing alien type method ALIEN-VALUE :DEPORT-GEN" value)
391   `(alien-sap ,value))
392 \f
393 ;;; HEAP-ALIEN-INFO -- defstruct.
394 ;;;
395 ;;; Information describing a heap-allocated alien.
396 (def!struct (heap-alien-info
397              (:make-load-form-fun sb!kernel:just-dump-it-normally))
398   ;; The type of this alien.
399   (type (missing-arg) :type alien-type)
400   ;; The form to evaluate to produce the SAP pointing to where in the heap
401   ;; it is.
402   (sap-form (missing-arg)))
403 (def!method print-object ((info heap-alien-info) stream)
404   (print-unreadable-object (info stream :type t)
405     (funcall (formatter "~S ~S")
406              stream
407              (heap-alien-info-sap-form info)
408              (unparse-alien-type (heap-alien-info-type info)))))
409 \f
410 ;;;; Interfaces to the different methods
411
412 (defun alien-type-= (type1 type2)
413   #!+sb-doc
414   "Return T iff TYPE1 and TYPE2 describe equivalent alien types."
415   (or (eq type1 type2)
416       (and (eq (alien-type-class type1)
417                (alien-type-class type2))
418            (invoke-alien-type-method :type= type1 type2))))
419
420 (defun alien-subtype-p (type1 type2)
421   #!+sb-doc
422   "Return T iff the alien type TYPE1 is a subtype of TYPE2. Currently, the
423    only supported subtype relationships are is that any pointer type is a
424    subtype of (* t), and any array type first dimension will match
425    (array <eltype> nil ...). Otherwise, the two types have to be
426    ALIEN-TYPE-=."
427   (or (eq type1 type2)
428       (invoke-alien-type-method :subtypep type1 type2)))
429
430 (defun compute-naturalize-lambda (type)
431   `(lambda (alien ignore)
432      (declare (ignore ignore))
433      ,(invoke-alien-type-method :naturalize-gen type 'alien)))
434
435 (defun compute-deport-lambda (type)
436   (declare (type alien-type type))
437   (/noshow "entering COMPUTE-DEPORT-LAMBDA" type)
438   (multiple-value-bind (form value-type)
439       (invoke-alien-type-method :deport-gen type 'value)
440     `(lambda (value ignore)
441        (declare (type ,(or value-type
442                            (compute-lisp-rep-type type)
443                            `(alien ,type))
444                       value)
445                 (ignore ignore))
446        ,form)))
447
448 (defun compute-extract-lambda (type)
449   `(lambda (sap offset ignore)
450      (declare (type system-area-pointer sap)
451               (type unsigned-byte offset)
452               (ignore ignore))
453      (naturalize ,(invoke-alien-type-method :extract-gen type 'sap 'offset)
454                  ',type)))
455
456 (defun compute-deposit-lambda (type)
457   (declare (type alien-type type))
458   `(lambda (sap offset ignore value)
459      (declare (type system-area-pointer sap)
460               (type unsigned-byte offset)
461               (ignore ignore))
462      (let ((value (deport value ',type)))
463        ,(invoke-alien-type-method :deposit-gen type 'sap 'offset 'value)
464        ;; Note: the reason we don't just return the pre-deported value
465        ;; is because that would inhibit any (deport (naturalize ...))
466        ;; optimizations that might have otherwise happen. Re-naturalizing
467        ;; the value might cause extra consing, but is flushable, so probably
468        ;; results in better code.
469        (naturalize value ',type))))
470
471 (defun compute-lisp-rep-type (type)
472   (invoke-alien-type-method :lisp-rep type))
473
474 (defun compute-alien-rep-type (type)
475   (invoke-alien-type-method :alien-rep type))
476 \f
477 ;;;; default methods
478
479 (define-alien-type-method (root :unparse) (type)
480   `(<unknown-alien-type> ,(type-of type)))
481
482 (define-alien-type-method (root :type=) (type1 type2)
483   (declare (ignore type1 type2))
484   t)
485
486 (define-alien-type-method (root :subtypep) (type1 type2)
487   (alien-type-= type1 type2))
488
489 (define-alien-type-method (root :lisp-rep) (type)
490   (declare (ignore type))
491   nil)
492
493 (define-alien-type-method (root :alien-rep) (type)
494   (declare (ignore type))
495   '*)
496
497 (define-alien-type-method (root :naturalize-gen) (type alien)
498   (declare (ignore alien))
499   (error "cannot represent ~S typed aliens" type))
500
501 (define-alien-type-method (root :deport-gen) (type object)
502   (declare (ignore object))
503   (error "cannot represent ~S typed aliens" type))
504
505 (define-alien-type-method (root :extract-gen) (type sap offset)
506   (declare (ignore sap offset))
507   (error "cannot represent ~S typed aliens" type))
508
509 (define-alien-type-method (root :deposit-gen) (type sap offset value)
510   `(setf ,(invoke-alien-type-method :extract-gen type sap offset) ,value))
511
512 (define-alien-type-method (root :arg-tn) (type state)
513   (declare (ignore state))
514   (error "Aliens of type ~S cannot be passed as arguments to CALL-OUT."
515          (unparse-alien-type type)))
516
517 (define-alien-type-method (root :result-tn) (type state)
518   (declare (ignore state))
519   (error "Aliens of type ~S cannot be returned from CALL-OUT."
520          (unparse-alien-type type)))
521 \f
522 ;;;; the INTEGER type
523
524 (define-alien-type-class (integer)
525   (signed t :type (member t nil)))
526
527 (define-alien-type-translator signed (&optional (bits sb!vm:n-word-bits))
528   (make-alien-integer-type :bits bits))
529
530 (define-alien-type-translator integer (&optional (bits sb!vm:n-word-bits))
531   (make-alien-integer-type :bits bits))
532
533 (define-alien-type-translator unsigned (&optional (bits sb!vm:n-word-bits))
534   (make-alien-integer-type :bits bits :signed nil))
535
536 (define-alien-type-method (integer :unparse) (type)
537   (list (if (alien-integer-type-signed type) 'signed 'unsigned)
538         (alien-integer-type-bits type)))
539
540 (define-alien-type-method (integer :type=) (type1 type2)
541   (and (eq (alien-integer-type-signed type1)
542            (alien-integer-type-signed type2))
543        (= (alien-integer-type-bits type1)
544           (alien-integer-type-bits type2))))
545
546 (define-alien-type-method (integer :lisp-rep) (type)
547   (list (if (alien-integer-type-signed type) 'signed-byte 'unsigned-byte)
548         (alien-integer-type-bits type)))
549
550 (define-alien-type-method (integer :alien-rep) (type)
551   (list (if (alien-integer-type-signed type) 'signed-byte 'unsigned-byte)
552         (alien-integer-type-bits type)))
553
554 (define-alien-type-method (integer :naturalize-gen) (type alien)
555   (declare (ignore type))
556   alien)
557
558 (define-alien-type-method (integer :deport-gen) (type value)
559   (declare (ignore type))
560   value)
561
562 (define-alien-type-method (integer :extract-gen) (type sap offset)
563   (declare (type alien-integer-type type))
564   (let ((ref-fun
565          (if (alien-integer-type-signed type)
566           (case (alien-integer-type-bits type)
567             (8 'signed-sap-ref-8)
568             (16 'signed-sap-ref-16)
569             (32 'signed-sap-ref-32)
570             (64 'signed-sap-ref-64))
571           (case (alien-integer-type-bits type)
572             (8 'sap-ref-8)
573             (16 'sap-ref-16)
574             (32 'sap-ref-32)
575             (64 'sap-ref-64)))))
576     (if ref-fun
577         `(,ref-fun ,sap (/ ,offset sb!vm:n-byte-bits))
578         (error "cannot extract ~W-bit integers"
579                (alien-integer-type-bits type)))))
580 \f
581 ;;;; the BOOLEAN type
582
583 (define-alien-type-class (boolean :include integer :include-args (signed)))
584
585 ;;; FIXME: Check to make sure that we aren't attaching user-readable
586 ;;; stuff to CL:BOOLEAN in any way which impairs ANSI compliance.
587 (define-alien-type-translator boolean (&optional (bits sb!vm:n-word-bits))
588   (make-alien-boolean-type :bits bits :signed nil))
589
590 (define-alien-type-method (boolean :unparse) (type)
591   `(boolean ,(alien-boolean-type-bits type)))
592
593 (define-alien-type-method (boolean :lisp-rep) (type)
594   (declare (ignore type))
595   `(member t nil))
596
597 (define-alien-type-method (boolean :naturalize-gen) (type alien)
598   (declare (ignore type))
599   `(not (zerop ,alien)))
600
601 (define-alien-type-method (boolean :deport-gen) (type value)
602   (declare (ignore type))
603   `(if ,value 1 0))
604 \f
605 ;;;; the ENUM type
606
607 (define-alien-type-class (enum :include (integer (bits 32))
608                                :include-args (signed))
609   name          ; name of this enum (if any)
610   from          ; alist from keywords to integers
611   to            ; alist or vector from integers to keywords
612   kind          ; kind of from mapping, :VECTOR or :ALIST
613   offset)       ; offset to add to value for :VECTOR from mapping
614
615 (define-alien-type-translator enum (&whole
616                                  type name
617                                  &rest mappings
618                                  &environment env)
619   (cond (mappings
620          (let ((result (parse-enum name mappings)))
621            (when name
622              (multiple-value-bind (old old-p)
623                  (auxiliary-alien-type :enum name env)
624                (when old-p
625                  (unless (alien-type-= result old)
626                    (warn "redefining alien enum ~S" name))))
627              (setf (auxiliary-alien-type :enum name env) result))
628            result))
629         (name
630          (multiple-value-bind (result found)
631              (auxiliary-alien-type :enum name env)
632            (unless found
633              (error "unknown enum type: ~S" name))
634            result))
635         (t
636          (error "empty enum type: ~S" type))))
637
638 (defun parse-enum (name elements)
639   (when (null elements)
640     (error "An enumeration must contain at least one element."))
641   (let ((min nil)
642         (max nil)
643         (from-alist ())
644         (prev -1))
645     (declare (list from-alist))
646     (dolist (el elements)
647       (multiple-value-bind (sym val)
648           (if (listp el)
649               (values (first el) (second el))
650               (values el (1+ prev)))
651         (setf prev val)
652         (unless (keywordp sym)
653           (error "The enumeration element ~S is not a keyword." sym))
654         (unless (integerp val)
655           (error "The element value ~S is not an integer." val))
656         (unless (and max (> max val)) (setq max val))
657         (unless (and min (< min val)) (setq min val))
658         (when (rassoc val from-alist)
659           (error "The element value ~S is used more than once." val))
660         (when (assoc sym from-alist :test #'eq)
661           (error "The enumeration element ~S is used more than once." sym))
662         (push (cons sym val) from-alist)))
663     (let* ((signed (minusp min))
664            (min-bits (if signed
665                          (1+ (max (integer-length min)
666                                   (integer-length max)))
667                          (integer-length max))))
668       (when (> min-bits 32)
669         (error "can't represent enums needing more than 32 bits"))
670       (setf from-alist (sort from-alist #'< :key #'cdr))
671       (cond
672        ;; If range is at least 20% dense, use vector mapping. Crossover
673        ;; point solely on basis of space would be 25%. Vector mapping
674        ;; is always faster, so give the benefit of the doubt.
675        ((< 0.2 (/ (float (length from-alist)) (float (- max min))))
676         ;; If offset is small and ignorable, ignore it to save time.
677         (when (< 0 min 10) (setq min 0))
678         (let ((to (make-array (1+ (- max min)))))
679           (dolist (el from-alist)
680             (setf (svref to (- (cdr el) min)) (car el)))
681           (make-alien-enum-type :name name :signed signed
682                                 :from from-alist :to to :kind
683                                 :vector :offset (- min))))
684        (t
685         (make-alien-enum-type :name name :signed signed
686                               :from from-alist
687                               :to (mapcar (lambda (x) (cons (cdr x) (car x)))
688                                           from-alist)
689                               :kind :alist))))))
690
691 (define-alien-type-method (enum :unparse) (type)
692   `(enum ,(alien-enum-type-name type)
693          ,@(let ((prev -1))
694              (mapcar (lambda (mapping)
695                        (let ((sym (car mapping))
696                              (value (cdr mapping)))
697                          (prog1
698                              (if (= (1+ prev) value)
699                                  sym
700                                  `(,sym ,value))
701                            (setf prev value))))
702                      (alien-enum-type-from type)))))
703
704 (define-alien-type-method (enum :type=) (type1 type2)
705   (and (eq (alien-enum-type-name type1)
706            (alien-enum-type-name type2))
707        (equal (alien-enum-type-from type1)
708               (alien-enum-type-from type2))))
709
710 (define-alien-type-method (enum :lisp-rep) (type)
711   `(member ,@(mapcar #'car (alien-enum-type-from type))))
712
713 (define-alien-type-method (enum :naturalize-gen) (type alien)
714   (ecase (alien-enum-type-kind type)
715     (:vector
716      `(svref ',(alien-enum-type-to type)
717              (+ ,alien ,(alien-enum-type-offset type))))
718     (:alist
719      `(ecase ,alien
720         ,@(mapcar (lambda (mapping)
721                     `(,(car mapping) ,(cdr mapping)))
722                   (alien-enum-type-to type))))))
723
724 (define-alien-type-method (enum :deport-gen) (type value)
725   `(ecase ,value
726      ,@(mapcar (lambda (mapping)
727                  `(,(car mapping) ,(cdr mapping)))
728                (alien-enum-type-from type))))
729 \f
730 ;;;; the FLOAT types
731
732 (define-alien-type-class (float)
733   (type (missing-arg) :type symbol))
734
735 (define-alien-type-method (float :unparse) (type)
736   (alien-float-type-type type))
737
738 (define-alien-type-method (float :lisp-rep) (type)
739   (alien-float-type-type type))
740
741 (define-alien-type-method (float :alien-rep) (type)
742   (alien-float-type-type type))
743
744 (define-alien-type-method (float :naturalize-gen) (type alien)
745   (declare (ignore type))
746   alien)
747
748 (define-alien-type-method (float :deport-gen) (type value)
749   (declare (ignore type))
750   value)
751
752 (define-alien-type-class (single-float :include (float (bits 32))
753                                        :include-args (type)))
754
755 (define-alien-type-translator single-float ()
756   (make-alien-single-float-type :type 'single-float))
757
758 (define-alien-type-method (single-float :extract-gen) (type sap offset)
759   (declare (ignore type))
760   `(sap-ref-single ,sap (/ ,offset sb!vm:n-byte-bits)))
761
762 (define-alien-type-class (double-float :include (float (bits 64))
763                                        :include-args (type)))
764
765 (define-alien-type-translator double-float ()
766   (make-alien-double-float-type :type 'double-float))
767
768 (define-alien-type-method (double-float :extract-gen) (type sap offset)
769   (declare (ignore type))
770   `(sap-ref-double ,sap (/ ,offset sb!vm:n-byte-bits)))
771
772 \f
773 ;;;; the POINTER type
774
775 (define-alien-type-class (pointer :include (alien-value (bits
776                                                          #!-alpha
777                                                          sb!vm:n-word-bits
778                                                          #!+alpha 64)))
779   (to nil :type (or alien-type null)))
780
781 (define-alien-type-translator * (to &environment env)
782   (make-alien-pointer-type :to (if (eq to t) nil (parse-alien-type to env))))
783
784 (define-alien-type-method (pointer :unparse) (type)
785   (let ((to (alien-pointer-type-to type)))
786     `(* ,(if to
787              (%unparse-alien-type to)
788              t))))
789
790 (define-alien-type-method (pointer :type=) (type1 type2)
791   (let ((to1 (alien-pointer-type-to type1))
792         (to2 (alien-pointer-type-to type2)))
793     (if to1
794         (if to2
795             (alien-type-= to1 to2)
796             nil)
797         (null to2))))
798
799 (define-alien-type-method (pointer :subtypep) (type1 type2)
800   (and (alien-pointer-type-p type2)
801        (let ((to1 (alien-pointer-type-to type1))
802              (to2 (alien-pointer-type-to type2)))
803          (if to1
804              (if to2
805                  (alien-subtype-p to1 to2)
806                  t)
807              (null to2)))))
808
809 (define-alien-type-method (pointer :deport-gen) (type value)
810   (/noshow "doing alien type method POINTER :DEPORT-GEN" type value)
811   (values
812    ;; FIXME: old version, highlighted a bug in xc optimization
813    `(etypecase ,value
814       (null
815        (int-sap 0))
816       (system-area-pointer
817        ,value)
818       ((alien ,type)
819        (alien-sap ,value)))
820    ;; new version, works around bug in xc optimization
821    #+nil
822    `(etypecase ,value
823       (system-area-pointer
824        ,value)
825       ((alien ,type)
826        (alien-sap ,value))
827       (null
828        (int-sap 0)))
829    `(or null system-area-pointer (alien ,type))))
830 \f
831 ;;;; the MEM-BLOCK type
832
833 (define-alien-type-class (mem-block :include alien-value))
834
835 (define-alien-type-method (mem-block :extract-gen) (type sap offset)
836   (declare (ignore type))
837   `(sap+ ,sap (/ ,offset sb!vm:n-byte-bits)))
838
839 (define-alien-type-method (mem-block :deposit-gen) (type sap offset value)
840   (let ((bits (alien-mem-block-type-bits type)))
841     (unless bits
842       (error "can't deposit aliens of type ~S (unknown size)" type))
843     `(sb!kernel:system-area-copy ,value 0 ,sap ,offset ',bits)))
844 \f
845 ;;;; the ARRAY type
846
847 (define-alien-type-class (array :include mem-block)
848   (element-type (missing-arg) :type alien-type)
849   (dimensions (missing-arg) :type list))
850
851 (define-alien-type-translator array (ele-type &rest dims &environment env)
852
853   (when dims
854     (unless (typep (first dims) '(or index null))
855       (error "The first dimension is not a non-negative fixnum or NIL: ~S"
856              (first dims)))
857     (let ((loser (find-if-not (lambda (x) (typep x 'index))
858                               (rest dims))))
859       (when loser
860         (error "A dimension is not a non-negative fixnum: ~S" loser))))
861         
862   (let ((parsed-ele-type (parse-alien-type ele-type env)))
863     (make-alien-array-type
864      :element-type parsed-ele-type
865      :dimensions dims
866      :alignment (alien-type-alignment parsed-ele-type)
867      :bits (if (and (alien-type-bits parsed-ele-type)
868                     (every #'integerp dims))
869                (* (align-offset (alien-type-bits parsed-ele-type)
870                                 (alien-type-alignment parsed-ele-type))
871                   (reduce #'* dims))))))
872
873 (define-alien-type-method (array :unparse) (type)
874   `(array ,(%unparse-alien-type (alien-array-type-element-type type))
875           ,@(alien-array-type-dimensions type)))
876
877 (define-alien-type-method (array :type=) (type1 type2)
878   (and (equal (alien-array-type-dimensions type1)
879               (alien-array-type-dimensions type2))
880        (alien-type-= (alien-array-type-element-type type1)
881                      (alien-array-type-element-type type2))))
882
883 (define-alien-type-method (array :subtypep) (type1 type2)
884   (and (alien-array-type-p type2)
885        (let ((dim1 (alien-array-type-dimensions type1))
886              (dim2 (alien-array-type-dimensions type2)))
887          (and (= (length dim1) (length dim2))
888               (or (and dim2
889                        (null (car dim2))
890                        (equal (cdr dim1) (cdr dim2)))
891                   (equal dim1 dim2))
892               (alien-subtype-p (alien-array-type-element-type type1)
893                                (alien-array-type-element-type type2))))))
894 \f
895 ;;;; the RECORD type
896
897 (def!struct (alien-record-field
898              (:make-load-form-fun sb!kernel:just-dump-it-normally))
899   (name (missing-arg) :type symbol)
900   (type (missing-arg) :type alien-type)
901   (bits nil :type (or unsigned-byte null))
902   (offset 0 :type unsigned-byte))
903 (def!method print-object ((field alien-record-field) stream)
904   (print-unreadable-object (field stream :type t)
905     (format stream
906             "~S ~S~@[:~D~]"
907             (alien-record-field-type field)
908             (alien-record-field-name field)
909             (alien-record-field-bits field))))
910
911 (define-alien-type-class (record :include mem-block)
912   (kind :struct :type (member :struct :union))
913   (name nil :type (or symbol null))
914   (fields nil :type list))
915
916 (define-alien-type-translator struct (name &rest fields &environment env)
917   (parse-alien-record-type :struct name fields env))
918
919 (define-alien-type-translator union (name &rest fields &environment env)
920   (parse-alien-record-type :union name fields env))
921
922 ;;; FIXME: This is really pretty horrible: we avoid creating new
923 ;;; ALIEN-RECORD-TYPE objects when a live one is flitting around the
924 ;;; system already. This way forwrd-references sans fields get get
925 ;;; "updated" for free to contain the field info. Maybe rename
926 ;;; MAKE-ALIEN-RECORD-TYPE to %MAKE-ALIEN-RECORD-TYPE and use
927 ;;; ENSURE-ALIEN-RECORD-TYPE instead. --NS 20040729
928 (defun parse-alien-record-type (kind name fields env)
929   (declare (type (or sb!kernel:lexenv null) env))
930   (cond (fields
931          (let* ((old (and name (auxiliary-alien-type kind name env)))
932                 (old-fields (and old (alien-record-type-fields old))))
933            ;; KLUDGE: We can't easily compare the new fields
934            ;; against the old fields, since the old fields have
935            ;; already been parsed into an internal
936            ;; representation, so we just punt, assuming that
937            ;; they're consistent. -- WHN 200000505
938            #|
939              (unless (equal fields old-fields)
940                ;; FIXME: Perhaps this should be a warning, and we
941                ;; should overwrite the old definition and proceed?
942                (error "mismatch in fields for ~S~%  old ~S~%  new ~S"
943                       name old-fields fields))
944            |#
945            (if old-fields
946                old
947                (let ((type (or old (make-alien-record-type :name name :kind kind))))
948                  (when (and name (not old))
949                    (setf (auxiliary-alien-type kind name env) type))
950                  (parse-alien-record-fields type fields env)
951                  type))))
952         (name
953          (or (auxiliary-alien-type kind name env)
954              (setf (auxiliary-alien-type kind name env)
955                    (make-alien-record-type :name name :kind kind))))
956         (t
957          (make-alien-record-type :kind kind))))
958
959 ;;; This is used by PARSE-ALIEN-TYPE to parse the fields of struct and
960 ;;; union types. RESULT holds the record type we are paring the fields
961 ;;; of, and FIELDS is the list of field specifications.
962 (defun parse-alien-record-fields (result fields env)
963   (declare (type alien-record-type result)
964            (type list fields))
965   (let ((total-bits 0)
966         (overall-alignment 1)
967         (parsed-fields nil))
968     (dolist (field fields)
969       (destructuring-bind (var type &optional bits) field
970         (declare (ignore bits))
971         (let* ((field-type (parse-alien-type type env))
972                (bits (alien-type-bits field-type))
973                (alignment (alien-type-alignment field-type))
974                (parsed-field
975                 (make-alien-record-field :type field-type
976                                          :name var)))
977           (push parsed-field parsed-fields)
978           (when (null bits)
979             (error "unknown size: ~S" (unparse-alien-type field-type)))
980           (when (null alignment)
981             (error "unknown alignment: ~S" (unparse-alien-type field-type)))
982           (setf overall-alignment (max overall-alignment alignment))
983           (ecase (alien-record-type-kind result)
984             (:struct
985              (let ((offset (align-offset total-bits alignment)))
986                (setf (alien-record-field-offset parsed-field) offset)
987                (setf total-bits (+ offset bits))))
988             (:union
989              (setf total-bits (max total-bits bits)))))))
990     (let ((new (nreverse parsed-fields)))
991       (setf (alien-record-type-fields result) new))
992     (setf (alien-record-type-alignment result) overall-alignment)
993     (setf (alien-record-type-bits result)
994           (align-offset total-bits overall-alignment))))
995
996 (define-alien-type-method (record :unparse) (type)
997   `(,(case (alien-record-type-kind type)
998        (:struct 'struct)
999        (:union 'union)
1000        (t '???))
1001     ,(alien-record-type-name type)
1002     ,@(unless (member type *record-types-already-unparsed* :test #'eq)
1003         (push type *record-types-already-unparsed*)
1004         (mapcar (lambda (field)
1005                   `(,(alien-record-field-name field)
1006                     ,(%unparse-alien-type (alien-record-field-type field))
1007                     ,@(if (alien-record-field-bits field)
1008                           (list (alien-record-field-bits field)))))
1009                 (alien-record-type-fields type)))))
1010
1011 ;;; Test the record fields. The depth is limiting in case of cyclic
1012 ;;; pointers.
1013 (defun record-fields-match (fields1 fields2 depth)
1014   (declare (type list fields1 fields2)
1015            (type (mod 64) depth))
1016   (labels ((record-type-= (type1 type2 depth)
1017              (and (eq (alien-record-type-name type1)
1018                       (alien-record-type-name type2))
1019                   (eq (alien-record-type-kind type1)
1020                       (alien-record-type-kind type2))
1021                   (= (length (alien-record-type-fields type1))
1022                      (length (alien-record-type-fields type2)))
1023                   (record-fields-match (alien-record-type-fields type1)
1024                                        (alien-record-type-fields type2)
1025                                        (1+ depth))))
1026            (pointer-type-= (type1 type2 depth)
1027              (let ((to1 (alien-pointer-type-to type1))
1028                    (to2 (alien-pointer-type-to type2)))
1029                (if to1
1030                    (if to2
1031                        (type-= to1 to2 (1+ depth))
1032                        nil)
1033                    (null to2))))
1034            (type-= (type1 type2 depth)
1035              (cond ((and (alien-pointer-type-p type1)
1036                          (alien-pointer-type-p type2))
1037                     (or (> depth 10)
1038                         (pointer-type-= type1 type2 depth)))
1039                    ((and (alien-record-type-p type1)
1040                          (alien-record-type-p type2))
1041                     (record-type-= type1 type2 depth))
1042                    (t
1043                     (alien-type-= type1 type2)))))
1044     (do ((fields1-rem fields1 (rest fields1-rem))
1045          (fields2-rem fields2 (rest fields2-rem)))
1046         ((or (eq fields1-rem fields2-rem)
1047              (endp fields1-rem) (endp fields2-rem))
1048          (eq fields1-rem fields2-rem))
1049       (let ((field1 (first fields1-rem))
1050             (field2 (first fields2-rem)))
1051         (declare (type alien-record-field field1 field2))
1052         (unless (and (eq (alien-record-field-name field1)
1053                          (alien-record-field-name field2))
1054                      (eql (alien-record-field-bits field1)
1055                           (alien-record-field-bits field2))
1056                      (eql (alien-record-field-offset field1)
1057                           (alien-record-field-offset field2))
1058                      (let ((field1 (alien-record-field-type field1))
1059                            (field2 (alien-record-field-type field2)))
1060                        (type-= field1 field2 (1+ depth))))
1061           (return nil))))))
1062
1063 (define-alien-type-method (record :type=) (type1 type2)
1064   (and (eq (alien-record-type-name type1)
1065            (alien-record-type-name type2))
1066        (eq (alien-record-type-kind type1)
1067            (alien-record-type-kind type2))
1068        (= (length (alien-record-type-fields type1))
1069           (length (alien-record-type-fields type2)))
1070        (record-fields-match (alien-record-type-fields type1)
1071                             (alien-record-type-fields type2) 0)))
1072 \f
1073 ;;;; the FUNCTION and VALUES alien types
1074
1075 ;;; not documented in CMU CL:-(
1076 ;;;
1077 ;;; reverse engineering observations:
1078 ;;;   * seems to be set when translating return values
1079 ;;;   * seems to enable the translation of (VALUES), which is the
1080 ;;;     Lisp idiom for C's return type "void" (which is likely
1081 ;;;     why it's set when when translating return values)
1082 (defvar *values-type-okay* nil)
1083
1084 (define-alien-type-class (fun :include mem-block)
1085   (result-type (missing-arg) :type alien-type)
1086   (arg-types (missing-arg) :type list)
1087   (stub nil :type (or null function)))
1088
1089 (define-alien-type-translator function (result-type &rest arg-types
1090                                                     &environment env)
1091   (make-alien-fun-type
1092    :result-type (let ((*values-type-okay* t))
1093                   (parse-alien-type result-type env))
1094    :arg-types (mapcar (lambda (arg-type) (parse-alien-type arg-type env))
1095                       arg-types)))
1096
1097 (define-alien-type-method (fun :unparse) (type)
1098   `(function ,(%unparse-alien-type (alien-fun-type-result-type type))
1099              ,@(mapcar #'%unparse-alien-type
1100                        (alien-fun-type-arg-types type))))
1101
1102 (define-alien-type-method (fun :type=) (type1 type2)
1103   (and (alien-type-= (alien-fun-type-result-type type1)
1104                      (alien-fun-type-result-type type2))
1105        (= (length (alien-fun-type-arg-types type1))
1106           (length (alien-fun-type-arg-types type2)))
1107        (every #'alien-type-=
1108               (alien-fun-type-arg-types type1)
1109               (alien-fun-type-arg-types type2))))
1110
1111 (define-alien-type-class (values)
1112   (values (missing-arg) :type list))
1113
1114 (define-alien-type-translator values (&rest values &environment env)
1115   (unless *values-type-okay*
1116     (error "cannot use values types here"))
1117   (let ((*values-type-okay* nil))
1118     (make-alien-values-type
1119      :values (mapcar (lambda (alien-type) (parse-alien-type alien-type env))
1120                      values))))
1121
1122 (define-alien-type-method (values :unparse) (type)
1123   `(values ,@(mapcar #'%unparse-alien-type
1124                      (alien-values-type-values type))))
1125
1126 (define-alien-type-method (values :type=) (type1 type2)
1127   (and (= (length (alien-values-type-values type1))
1128           (length (alien-values-type-values type2)))
1129        (every #'alien-type-=
1130               (alien-values-type-values type1)
1131               (alien-values-type-values type2))))
1132 \f
1133 ;;;; a structure definition needed both in the target and in the
1134 ;;;; cross-compilation host
1135
1136 ;;; information about local aliens. The WITH-ALIEN macro builds one of
1137 ;;; these structures and LOCAL-ALIEN and friends communicate
1138 ;;; information about how that local alien is represented.
1139 (def!struct (local-alien-info
1140              (:make-load-form-fun sb!kernel:just-dump-it-normally)
1141              (:constructor make-local-alien-info
1142                            (&key type force-to-memory-p
1143                             &aux (force-to-memory-p (or force-to-memory-p
1144                                                         (alien-array-type-p type)
1145                                                         (alien-record-type-p type))))))
1146   ;; the type of the local alien
1147   (type (missing-arg) :type alien-type)
1148   ;; Must this local alien be forced into memory? Using the ADDR macro
1149   ;; on a local alien will set this.
1150   (force-to-memory-p nil :type (member t nil)))
1151 (def!method print-object ((info local-alien-info) stream)
1152   (print-unreadable-object (info stream :type t)
1153     (format stream
1154             "~:[~;(forced to stack) ~]~S"
1155             (local-alien-info-force-to-memory-p info)
1156             (unparse-alien-type (local-alien-info-type info)))))
1157 \f
1158 ;;;; the ADDR macro
1159
1160 (defmacro-mundanely addr (expr &environment env)
1161   #!+sb-doc
1162   "Return an Alien pointer to the data addressed by Expr, which must be a call
1163    to SLOT or DEREF, or a reference to an Alien variable."
1164   (let ((form (sb!xc:macroexpand expr env)))
1165     (or (typecase form
1166           (cons
1167            (case (car form)
1168              (slot
1169               (cons '%slot-addr (cdr form)))
1170              (deref
1171               (cons '%deref-addr (cdr form)))
1172              (%heap-alien
1173               (cons '%heap-alien-addr (cdr form)))
1174              (local-alien
1175               (let ((info (let ((info-arg (second form)))
1176                             (and (consp info-arg)
1177                                  (eq (car info-arg) 'quote)
1178                                  (second info-arg)))))
1179                 (unless (local-alien-info-p info)
1180                   (error "Something is wrong, LOCAL-ALIEN-INFO not found: ~S"
1181                          form))
1182                 (setf (local-alien-info-force-to-memory-p info) t))
1183               (cons '%local-alien-addr (cdr form)))))
1184           (symbol
1185            (let ((kind (info :variable :kind form)))
1186              (when (eq kind :alien)
1187                `(%heap-alien-addr ',(info :variable :alien-info form))))))
1188         (error "~S is not a valid L-value." form))))
1189
1190 (/show0 "host-alieneval.lisp end of file")