e9fe96a73efab55a712e742194b07525f538f508
[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       (destructuring-bind (kind name defn) info
292         (macrolet ((frob (kind)
293                          `(let ((old (info :alien-type ,kind name)))
294                             (unless (or (null old) (alien-type-= old defn))
295                               (warn
296                                "redefining ~A ~S to be:~%  ~S,~%was:~%  ~S"
297                                kind name defn old))
298                             (setf (info :alien-type ,kind name) defn))))
299           (ecase kind
300             (:struct (frob :struct))
301             (:union (frob :union))
302             (:enum (frob :enum)))))))
303   (defun %define-alien-type (name new)
304     (ecase (info :alien-type :kind name)
305       (:primitive
306        (error "~S is a built-in alien type." name))
307       (:defined
308        (let ((old (info :alien-type :definition name)))
309          (unless (or (null old) (alien-type-= new old))
310            (warn "redefining ~S to be:~%  ~S,~%was~%  ~S"
311                  name
312                  (unparse-alien-type new)
313                  (unparse-alien-type old)))))
314       (:unknown))
315     (setf (info :alien-type :definition name) new)
316     (setf (info :alien-type :kind name) :defined)
317     name))
318 \f
319 ;;;; the root alien type
320
321 (eval-when (:compile-toplevel :load-toplevel :execute)
322   (create-alien-type-class-if-necessary 'root nil))
323
324 (def!struct (alien-type
325              (:make-load-form-fun sb!kernel:just-dump-it-normally)
326              (:constructor make-alien-type (&key class bits alignment
327                                             &aux (alignment (or alignment (guess-alignment bits))))))
328   (class 'root :type symbol)
329   (bits nil :type (or null unsigned-byte))
330   (alignment nil :type (or null unsigned-byte)))
331 (def!method print-object ((type alien-type) stream)
332   (print-unreadable-object (type stream :type t)
333     (prin1 (unparse-alien-type type) stream)))
334 \f
335 ;;;; the SAP type
336
337 (define-alien-type-class (system-area-pointer))
338
339 (define-alien-type-translator system-area-pointer ()
340   (make-alien-system-area-pointer-type
341    :bits #!-alpha sb!vm:n-word-bits #!+alpha 64))
342
343 (define-alien-type-method (system-area-pointer :unparse) (type)
344   (declare (ignore type))
345   'system-area-pointer)
346
347 (define-alien-type-method (system-area-pointer :lisp-rep) (type)
348   (declare (ignore type))
349   'system-area-pointer)
350
351 (define-alien-type-method (system-area-pointer :alien-rep) (type)
352   (declare (ignore type))
353   'system-area-pointer)
354
355 (define-alien-type-method (system-area-pointer :naturalize-gen) (type alien)
356   (declare (ignore type))
357   alien)
358
359 (define-alien-type-method (system-area-pointer :deport-gen) (type object)
360   (declare (ignore type))
361   (/noshow "doing alien type method SYSTEM-AREA-POINTER :DEPORT-GEN" object)
362   object)
363
364 (define-alien-type-method (system-area-pointer :extract-gen) (type sap offset)
365   (declare (ignore type))
366   `(sap-ref-sap ,sap (/ ,offset sb!vm:n-byte-bits)))
367 \f
368 ;;;; the ALIEN-VALUE type
369
370 (define-alien-type-class (alien-value :include system-area-pointer))
371
372 (define-alien-type-method (alien-value :lisp-rep) (type)
373   (declare (ignore type))
374   nil)
375
376 (define-alien-type-method (alien-value :naturalize-gen) (type alien)
377   `(%sap-alien ,alien ',type))
378
379 (define-alien-type-method (alien-value :deport-gen) (type value)
380   (declare (ignore type))
381   (/noshow "doing alien type method ALIEN-VALUE :DEPORT-GEN" value)
382   `(alien-sap ,value))
383 \f
384 ;;; HEAP-ALIEN-INFO -- defstruct.
385 ;;;
386 ;;; Information describing a heap-allocated alien.
387 (def!struct (heap-alien-info
388              (:make-load-form-fun sb!kernel:just-dump-it-normally))
389   ;; The type of this alien.
390   (type (missing-arg) :type alien-type)
391   ;; The form to evaluate to produce the SAP pointing to where in the heap
392   ;; it is.
393   (sap-form (missing-arg)))
394 (def!method print-object ((info heap-alien-info) stream)
395   (print-unreadable-object (info stream :type t)
396     (funcall (formatter "~S ~S")
397              stream
398              (heap-alien-info-sap-form info)
399              (unparse-alien-type (heap-alien-info-type info)))))
400 \f
401 ;;;; Interfaces to the different methods
402
403 (defun alien-type-= (type1 type2)
404   #!+sb-doc
405   "Return T iff TYPE1 and TYPE2 describe equivalent alien types."
406   (or (eq type1 type2)
407       (and (eq (alien-type-class type1)
408                (alien-type-class type2))
409            (invoke-alien-type-method :type= type1 type2))))
410
411 (defun alien-subtype-p (type1 type2)
412   #!+sb-doc
413   "Return T iff the alien type TYPE1 is a subtype of TYPE2. Currently, the
414    only supported subtype relationships are is that any pointer type is a
415    subtype of (* t), and any array type first dimension will match
416    (array <eltype> nil ...). Otherwise, the two types have to be
417    ALIEN-TYPE-=."
418   (or (eq type1 type2)
419       (invoke-alien-type-method :subtypep type1 type2)))
420
421 (defun compute-naturalize-lambda (type)
422   `(lambda (alien ignore)
423      (declare (ignore ignore))
424      ,(invoke-alien-type-method :naturalize-gen type 'alien)))
425
426 (defun compute-deport-lambda (type)
427   (declare (type alien-type type))
428   (/noshow "entering COMPUTE-DEPORT-LAMBDA" type)
429   (multiple-value-bind (form value-type)
430       (invoke-alien-type-method :deport-gen type 'value)
431     `(lambda (value ignore)
432        (declare (type ,(or value-type
433                            (compute-lisp-rep-type type)
434                            `(alien ,type))
435                       value)
436                 (ignore ignore))
437        ,form)))
438
439 (defun compute-extract-lambda (type)
440   `(lambda (sap offset ignore)
441      (declare (type system-area-pointer sap)
442               (type unsigned-byte offset)
443               (ignore ignore))
444      (naturalize ,(invoke-alien-type-method :extract-gen type 'sap 'offset)
445                  ',type)))
446
447 (defun compute-deposit-lambda (type)
448   (declare (type alien-type type))
449   `(lambda (sap offset ignore value)
450      (declare (type system-area-pointer sap)
451               (type unsigned-byte offset)
452               (ignore ignore))
453      (let ((value (deport value ',type)))
454        ,(invoke-alien-type-method :deposit-gen type 'sap 'offset 'value)
455        ;; Note: the reason we don't just return the pre-deported value
456        ;; is because that would inhibit any (deport (naturalize ...))
457        ;; optimizations that might have otherwise happen. Re-naturalizing
458        ;; the value might cause extra consing, but is flushable, so probably
459        ;; results in better code.
460        (naturalize value ',type))))
461
462 (defun compute-lisp-rep-type (type)
463   (invoke-alien-type-method :lisp-rep type))
464
465 (defun compute-alien-rep-type (type)
466   (invoke-alien-type-method :alien-rep type))
467 \f
468 ;;;; default methods
469
470 (define-alien-type-method (root :unparse) (type)
471   `(<unknown-alien-type> ,(type-of type)))
472
473 (define-alien-type-method (root :type=) (type1 type2)
474   (declare (ignore type1 type2))
475   t)
476
477 (define-alien-type-method (root :subtypep) (type1 type2)
478   (alien-type-= type1 type2))
479
480 (define-alien-type-method (root :lisp-rep) (type)
481   (declare (ignore type))
482   nil)
483
484 (define-alien-type-method (root :alien-rep) (type)
485   (declare (ignore type))
486   '*)
487
488 (define-alien-type-method (root :naturalize-gen) (type alien)
489   (declare (ignore alien))
490   (error "cannot represent ~S typed aliens" type))
491
492 (define-alien-type-method (root :deport-gen) (type object)
493   (declare (ignore object))
494   (error "cannot represent ~S typed aliens" type))
495
496 (define-alien-type-method (root :extract-gen) (type sap offset)
497   (declare (ignore sap offset))
498   (error "cannot represent ~S typed aliens" type))
499
500 (define-alien-type-method (root :deposit-gen) (type sap offset value)
501   `(setf ,(invoke-alien-type-method :extract-gen type sap offset) ,value))
502
503 (define-alien-type-method (root :arg-tn) (type state)
504   (declare (ignore state))
505   (error "Aliens of type ~S cannot be passed as arguments to CALL-OUT."
506          (unparse-alien-type type)))
507
508 (define-alien-type-method (root :result-tn) (type state)
509   (declare (ignore state))
510   (error "Aliens of type ~S cannot be returned from CALL-OUT."
511          (unparse-alien-type type)))
512 \f
513 ;;;; the INTEGER type
514
515 (define-alien-type-class (integer)
516   (signed t :type (member t nil)))
517
518 (define-alien-type-translator signed (&optional (bits sb!vm:n-word-bits))
519   (make-alien-integer-type :bits bits))
520
521 (define-alien-type-translator integer (&optional (bits sb!vm:n-word-bits))
522   (make-alien-integer-type :bits bits))
523
524 (define-alien-type-translator unsigned (&optional (bits sb!vm:n-word-bits))
525   (make-alien-integer-type :bits bits :signed nil))
526
527 (define-alien-type-method (integer :unparse) (type)
528   (list (if (alien-integer-type-signed type) 'signed 'unsigned)
529         (alien-integer-type-bits type)))
530
531 (define-alien-type-method (integer :type=) (type1 type2)
532   (and (eq (alien-integer-type-signed type1)
533            (alien-integer-type-signed type2))
534        (= (alien-integer-type-bits type1)
535           (alien-integer-type-bits type2))))
536
537 (define-alien-type-method (integer :lisp-rep) (type)
538   (list (if (alien-integer-type-signed type) 'signed-byte 'unsigned-byte)
539         (alien-integer-type-bits type)))
540
541 (define-alien-type-method (integer :alien-rep) (type)
542   (list (if (alien-integer-type-signed type) 'signed-byte 'unsigned-byte)
543         (alien-integer-type-bits type)))
544
545 (define-alien-type-method (integer :naturalize-gen) (type alien)
546   (declare (ignore type))
547   alien)
548
549 (define-alien-type-method (integer :deport-gen) (type value)
550   (declare (ignore type))
551   value)
552
553 (define-alien-type-method (integer :extract-gen) (type sap offset)
554   (declare (type alien-integer-type type))
555   (let ((ref-fun
556          (if (alien-integer-type-signed type)
557           (case (alien-integer-type-bits type)
558             (8 'signed-sap-ref-8)
559             (16 'signed-sap-ref-16)
560             (32 'signed-sap-ref-32)
561             (64 'signed-sap-ref-64))
562           (case (alien-integer-type-bits type)
563             (8 'sap-ref-8)
564             (16 'sap-ref-16)
565             (32 'sap-ref-32)
566             (64 'sap-ref-64)))))
567     (if ref-fun
568         `(,ref-fun ,sap (/ ,offset sb!vm:n-byte-bits))
569         (error "cannot extract ~W-bit integers"
570                (alien-integer-type-bits type)))))
571 \f
572 ;;;; the BOOLEAN type
573
574 (define-alien-type-class (boolean :include integer :include-args (signed)))
575
576 ;;; FIXME: Check to make sure that we aren't attaching user-readable
577 ;;; stuff to CL:BOOLEAN in any way which impairs ANSI compliance.
578 (define-alien-type-translator boolean (&optional (bits sb!vm:n-word-bits))
579   (make-alien-boolean-type :bits bits :signed nil))
580
581 (define-alien-type-method (boolean :unparse) (type)
582   `(boolean ,(alien-boolean-type-bits type)))
583
584 (define-alien-type-method (boolean :lisp-rep) (type)
585   (declare (ignore type))
586   `(member t nil))
587
588 (define-alien-type-method (boolean :naturalize-gen) (type alien)
589   (declare (ignore type))
590   `(not (zerop ,alien)))
591
592 (define-alien-type-method (boolean :deport-gen) (type value)
593   (declare (ignore type))
594   `(if ,value 1 0))
595 \f
596 ;;;; the ENUM type
597
598 (define-alien-type-class (enum :include (integer (bits 32))
599                                :include-args (signed))
600   name          ; name of this enum (if any)
601   from          ; alist from keywords to integers
602   to            ; alist or vector from integers to keywords
603   kind          ; kind of from mapping, :VECTOR or :ALIST
604   offset)       ; offset to add to value for :VECTOR from mapping
605
606 (define-alien-type-translator enum (&whole
607                                  type name
608                                  &rest mappings
609                                  &environment env)
610   (cond (mappings
611          (let ((result (parse-enum name mappings)))
612            (when name
613              (multiple-value-bind (old old-p)
614                  (auxiliary-alien-type :enum name env)
615                (when old-p
616                  (unless (alien-type-= result old)
617                    (warn "redefining alien enum ~S" name))))
618              (setf (auxiliary-alien-type :enum name env) result))
619            result))
620         (name
621          (multiple-value-bind (result found)
622              (auxiliary-alien-type :enum name env)
623            (unless found
624              (error "unknown enum type: ~S" name))
625            result))
626         (t
627          (error "empty enum type: ~S" type))))
628
629 (defun parse-enum (name elements)
630   (when (null elements)
631     (error "An enumeration must contain at least one element."))
632   (let ((min nil)
633         (max nil)
634         (from-alist ())
635         (prev -1))
636     (declare (list from-alist))
637     (dolist (el elements)
638       (multiple-value-bind (sym val)
639           (if (listp el)
640               (values (first el) (second el))
641               (values el (1+ prev)))
642         (setf prev val)
643         (unless (keywordp sym)
644           (error "The enumeration element ~S is not a keyword." sym))
645         (unless (integerp val)
646           (error "The element value ~S is not an integer." val))
647         (unless (and max (> max val)) (setq max val))
648         (unless (and min (< min val)) (setq min val))
649         (when (rassoc val from-alist)
650           (error "The element value ~S is used more than once." val))
651         (when (assoc sym from-alist :test #'eq)
652           (error "The enumeration element ~S is used more than once." sym))
653         (push (cons sym val) from-alist)))
654     (let* ((signed (minusp min))
655            (min-bits (if signed
656                          (1+ (max (integer-length min)
657                                   (integer-length max)))
658                          (integer-length max))))
659       (when (> min-bits 32)
660         (error "can't represent enums needing more than 32 bits"))
661       (setf from-alist (sort from-alist #'< :key #'cdr))
662       (cond
663        ;; If range is at least 20% dense, use vector mapping. Crossover
664        ;; point solely on basis of space would be 25%. Vector mapping
665        ;; is always faster, so give the benefit of the doubt.
666        ((< 0.2 (/ (float (length from-alist)) (float (- max min))))
667         ;; If offset is small and ignorable, ignore it to save time.
668         (when (< 0 min 10) (setq min 0))
669         (let ((to (make-array (1+ (- max min)))))
670           (dolist (el from-alist)
671             (setf (svref to (- (cdr el) min)) (car el)))
672           (make-alien-enum-type :name name :signed signed
673                                 :from from-alist :to to :kind
674                                 :vector :offset (- min))))
675        (t
676         (make-alien-enum-type :name name :signed signed
677                               :from from-alist
678                               :to (mapcar (lambda (x) (cons (cdr x) (car x)))
679                                           from-alist)
680                               :kind :alist))))))
681
682 (define-alien-type-method (enum :unparse) (type)
683   `(enum ,(alien-enum-type-name type)
684          ,@(let ((prev -1))
685              (mapcar (lambda (mapping)
686                        (let ((sym (car mapping))
687                              (value (cdr mapping)))
688                          (prog1
689                              (if (= (1+ prev) value)
690                                  sym
691                                  `(,sym ,value))
692                            (setf prev value))))
693                      (alien-enum-type-from type)))))
694
695 (define-alien-type-method (enum :type=) (type1 type2)
696   (and (eq (alien-enum-type-name type1)
697            (alien-enum-type-name type2))
698        (equal (alien-enum-type-from type1)
699               (alien-enum-type-from type2))))
700
701 (define-alien-type-method (enum :lisp-rep) (type)
702   `(member ,@(mapcar #'car (alien-enum-type-from type))))
703
704 (define-alien-type-method (enum :naturalize-gen) (type alien)
705   (ecase (alien-enum-type-kind type)
706     (:vector
707      `(svref ',(alien-enum-type-to type)
708              (+ ,alien ,(alien-enum-type-offset type))))
709     (:alist
710      `(ecase ,alien
711         ,@(mapcar (lambda (mapping)
712                     `(,(car mapping) ,(cdr mapping)))
713                   (alien-enum-type-to type))))))
714
715 (define-alien-type-method (enum :deport-gen) (type value)
716   `(ecase ,value
717      ,@(mapcar (lambda (mapping)
718                  `(,(car mapping) ,(cdr mapping)))
719                (alien-enum-type-from type))))
720 \f
721 ;;;; the FLOAT types
722
723 (define-alien-type-class (float)
724   (type (missing-arg) :type symbol))
725
726 (define-alien-type-method (float :unparse) (type)
727   (alien-float-type-type type))
728
729 (define-alien-type-method (float :lisp-rep) (type)
730   (alien-float-type-type type))
731
732 (define-alien-type-method (float :alien-rep) (type)
733   (alien-float-type-type type))
734
735 (define-alien-type-method (float :naturalize-gen) (type alien)
736   (declare (ignore type))
737   alien)
738
739 (define-alien-type-method (float :deport-gen) (type value)
740   (declare (ignore type))
741   value)
742
743 (define-alien-type-class (single-float :include (float (bits 32))
744                                        :include-args (type)))
745
746 (define-alien-type-translator single-float ()
747   (make-alien-single-float-type :type 'single-float))
748
749 (define-alien-type-method (single-float :extract-gen) (type sap offset)
750   (declare (ignore type))
751   `(sap-ref-single ,sap (/ ,offset sb!vm:n-byte-bits)))
752
753 (define-alien-type-class (double-float :include (float (bits 64))
754                                        :include-args (type)))
755
756 (define-alien-type-translator double-float ()
757   (make-alien-double-float-type :type 'double-float))
758
759 (define-alien-type-method (double-float :extract-gen) (type sap offset)
760   (declare (ignore type))
761   `(sap-ref-double ,sap (/ ,offset sb!vm:n-byte-bits)))
762
763 #!+long-float
764 (define-alien-type-class (long-float :include (float (bits #!+x86 96
765                                                            #!+sparc 128))
766                                      :include-args (type)))
767
768 #!+long-float
769 (define-alien-type-translator long-float ()
770   (make-alien-long-float-type :type 'long-float))
771
772 #!+long-float
773 (define-alien-type-method (long-float :extract-gen) (type sap offset)
774   (declare (ignore type))
775   `(sap-ref-long ,sap (/ ,offset sb!vm:n-byte-bits)))
776 \f
777 ;;;; the POINTER type
778
779 (define-alien-type-class (pointer :include (alien-value (bits
780                                                          #!-alpha
781                                                          sb!vm:n-word-bits
782                                                          #!+alpha 64)))
783   (to nil :type (or alien-type null)))
784
785 (define-alien-type-translator * (to &environment env)
786   (make-alien-pointer-type :to (if (eq to t) nil (parse-alien-type to env))))
787
788 (define-alien-type-method (pointer :unparse) (type)
789   (let ((to (alien-pointer-type-to type)))
790     `(* ,(if to
791              (%unparse-alien-type to)
792              t))))
793
794 (define-alien-type-method (pointer :type=) (type1 type2)
795   (let ((to1 (alien-pointer-type-to type1))
796         (to2 (alien-pointer-type-to type2)))
797     (if to1
798         (if to2
799             (alien-type-= to1 to2)
800             nil)
801         (null to2))))
802
803 (define-alien-type-method (pointer :subtypep) (type1 type2)
804   (and (alien-pointer-type-p type2)
805        (let ((to1 (alien-pointer-type-to type1))
806              (to2 (alien-pointer-type-to type2)))
807          (if to1
808              (if to2
809                  (alien-subtype-p to1 to2)
810                  t)
811              (null to2)))))
812
813 (define-alien-type-method (pointer :deport-gen) (type value)
814   (/noshow "doing alien type method POINTER :DEPORT-GEN" type value)
815   (values
816    ;; FIXME: old version, highlighted a bug in xc optimization
817    `(etypecase ,value
818       (null
819        (int-sap 0))
820       (system-area-pointer
821        ,value)
822       ((alien ,type)
823        (alien-sap ,value)))
824    ;; new version, works around bug in xc optimization
825    #+nil
826    `(etypecase ,value
827       (system-area-pointer
828        ,value)
829       ((alien ,type)
830        (alien-sap ,value))
831       (null
832        (int-sap 0)))
833    `(or null system-area-pointer (alien ,type))))
834 \f
835 ;;;; the MEM-BLOCK type
836
837 (define-alien-type-class (mem-block :include alien-value))
838
839 (define-alien-type-method (mem-block :extract-gen) (type sap offset)
840   (declare (ignore type))
841   `(sap+ ,sap (/ ,offset sb!vm:n-byte-bits)))
842
843 (define-alien-type-method (mem-block :deposit-gen) (type sap offset value)
844   (let ((bits (alien-mem-block-type-bits type)))
845     (unless bits
846       (error "can't deposit aliens of type ~S (unknown size)" type))
847     `(sb!kernel:system-area-copy ,value 0 ,sap ,offset ',bits)))
848 \f
849 ;;;; the ARRAY type
850
851 (define-alien-type-class (array :include mem-block)
852   (element-type (missing-arg) :type alien-type)
853   (dimensions (missing-arg) :type list))
854
855 (define-alien-type-translator array (ele-type &rest dims &environment env)
856
857   (when dims
858     (unless (typep (first dims) '(or index null))
859       (error "The first dimension is not a non-negative fixnum or NIL: ~S"
860              (first dims)))
861     (let ((loser (find-if-not (lambda (x) (typep x 'index))
862                               (rest dims))))
863       (when loser
864         (error "A dimension is not a non-negative fixnum: ~S" loser))))
865         
866   (let ((parsed-ele-type (parse-alien-type ele-type env)))
867     (make-alien-array-type
868      :element-type parsed-ele-type
869      :dimensions dims
870      :alignment (alien-type-alignment parsed-ele-type)
871      :bits (if (and (alien-type-bits parsed-ele-type)
872                     (every #'integerp dims))
873                (* (align-offset (alien-type-bits parsed-ele-type)
874                                 (alien-type-alignment parsed-ele-type))
875                   (reduce #'* dims))))))
876
877 (define-alien-type-method (array :unparse) (type)
878   `(array ,(%unparse-alien-type (alien-array-type-element-type type))
879           ,@(alien-array-type-dimensions type)))
880
881 (define-alien-type-method (array :type=) (type1 type2)
882   (and (equal (alien-array-type-dimensions type1)
883               (alien-array-type-dimensions type2))
884        (alien-type-= (alien-array-type-element-type type1)
885                      (alien-array-type-element-type type2))))
886
887 (define-alien-type-method (array :subtypep) (type1 type2)
888   (and (alien-array-type-p type2)
889        (let ((dim1 (alien-array-type-dimensions type1))
890              (dim2 (alien-array-type-dimensions type2)))
891          (and (= (length dim1) (length dim2))
892               (or (and dim2
893                        (null (car dim2))
894                        (equal (cdr dim1) (cdr dim2)))
895                   (equal dim1 dim2))
896               (alien-subtype-p (alien-array-type-element-type type1)
897                                (alien-array-type-element-type type2))))))
898 \f
899 ;;;; the RECORD type
900
901 (def!struct (alien-record-field
902              (:make-load-form-fun sb!kernel:just-dump-it-normally))
903   (name (missing-arg) :type symbol)
904   (type (missing-arg) :type alien-type)
905   (bits nil :type (or unsigned-byte null))
906   (offset 0 :type unsigned-byte))
907 (def!method print-object ((field alien-record-field) stream)
908   (print-unreadable-object (field stream :type t)
909     (format stream
910             "~S ~S~@[:~D~]"
911             (alien-record-field-type field)
912             (alien-record-field-name field)
913             (alien-record-field-bits field))))
914
915 (define-alien-type-class (record :include mem-block)
916   (kind :struct :type (member :struct :union))
917   (name nil :type (or symbol null))
918   (fields nil :type list))
919
920 (define-alien-type-translator struct (name &rest fields &environment env)
921   (parse-alien-record-type :struct name fields env))
922
923 (define-alien-type-translator union (name &rest fields &environment env)
924   (parse-alien-record-type :union name fields env))
925
926 (defun parse-alien-record-type (kind name fields env)
927   (declare (type (or sb!kernel:lexenv null) env))
928   (cond (fields
929          (let* ((old (and name (auxiliary-alien-type kind name env)))
930                 (old-fields (and old (alien-record-type-fields old))))
931            (cond (old-fields
932                   ;; KLUDGE: We can't easily compare the new fields
933                   ;; against the old fields, since the old fields have
934                   ;; already been parsed into an internal
935                   ;; representation, so we just punt, assuming that
936                   ;; they're consistent. -- WHN 200000505
937                   #|
938                   (unless (equal fields old-fields)
939                     ;; FIXME: Perhaps this should be a warning, and we
940                     ;; should overwrite the old definition and proceed?
941                     (error "mismatch in fields for ~S~%  old ~S~%  new ~S"
942                            name old-fields fields))
943                   |#
944                   old)
945                  (t
946                   (let ((new (make-alien-record-type :name name
947                                                      :kind kind)))
948                     (when name
949                       (setf (auxiliary-alien-type kind name env) new))
950                     (parse-alien-record-fields new fields env)
951                     new)))))
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")