0.pre7.38:
[sbcl.git] / src / code / target-alieneval.lisp
1 ;;;; This file contains parts of the ALIEN implementation that
2 ;;;; are not part of the compiler.
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 "target-alieneval.lisp 15")
16 \f
17 ;;;; alien variables
18
19 ;;; Make a string out of the symbol, converting all uppercase letters to
20 ;;; lower case and hyphens into underscores.
21 (eval-when (:compile-toplevel :load-toplevel :execute)
22   (defun guess-alien-name-from-lisp-name (lisp-name)
23     (declare (type symbol lisp-name))
24     (nsubstitute #\_ #\- (string-downcase (symbol-name lisp-name)))))
25
26 ;;; The opposite of GUESS-ALIEN-NAME-FROM-LISP-NAME. Make a symbol out
27 ;;; of the string, converting all lowercase letters to uppercase and
28 ;;; underscores into hyphens.
29 (eval-when (:compile-toplevel :load-toplevel :execute)
30   (defun guess-lisp-name-from-alien-name (alien-name)
31     (declare (type simple-string alien-name))
32     (intern (nsubstitute #\- #\_ (string-upcase alien-name)))))
33
34 ;;; Extract the Lisp and alien names from NAME. If only one is given,
35 ;;; guess the other.
36 (eval-when (:compile-toplevel :load-toplevel :execute)
37   (defun pick-lisp-and-alien-names (name)
38     (etypecase name
39       (string
40        (values (guess-lisp-name-from-alien-name name) name))
41       (symbol
42        (values name (guess-alien-name-from-lisp-name name)))
43       (list
44        (unless (proper-list-of-length-p name 2)
45          (error "badly formed alien name"))
46        (values (cadr name) (car name))))))
47
48 (defmacro def-alien-variable (name type &environment env)
49   #!+sb-doc
50   "Define NAME as an external alien variable of type TYPE. NAME should be
51    a list of a string holding the alien name and a symbol to use as the Lisp
52    name. If NAME is just a symbol or string, then the other name is guessed
53    from the one supplied."
54   (multiple-value-bind (lisp-name alien-name) (pick-lisp-and-alien-names name)
55     (with-auxiliary-alien-types env
56       (let ((alien-type (parse-alien-type type env)))
57         `(eval-when (:compile-toplevel :load-toplevel :execute)
58            ,@(when *new-auxiliary-types*
59                `((%def-auxiliary-alien-types ',*new-auxiliary-types*)))
60            (%def-alien-variable ',lisp-name
61                                 ',alien-name
62                                 ',alien-type))))))
63
64 ;;; Do the actual work of DEF-ALIEN-VARIABLE.
65 (eval-when (:compile-toplevel :load-toplevel :execute)
66   (defun %def-alien-variable (lisp-name alien-name type)
67     (setf (info :variable :kind lisp-name) :alien)
68     (setf (info :variable :where-from lisp-name) :defined)
69     (clear-info :variable :constant-value lisp-name)
70     (setf (info :variable :alien-info lisp-name)
71           (make-heap-alien-info :type type
72                                 :sap-form `(foreign-symbol-address
73                                             ',alien-name)))))
74
75 (defmacro extern-alien (name type &environment env)
76   #!+sb-doc
77   "Access the alien variable named NAME, assuming it is of type TYPE. This
78    is SETFable."
79   (let ((alien-name (etypecase name
80                       (symbol (guess-alien-name-from-lisp-name name))
81                       (string name))))
82     `(%heap-alien ',(make-heap-alien-info
83                      :type (parse-alien-type type env)
84                      :sap-form `(foreign-symbol-address ',alien-name)))))
85
86 (defmacro with-alien (bindings &body body &environment env)
87   #!+sb-doc
88   "Establish some local alien variables. Each BINDING is of the form:
89      VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
90    ALLOCATION should be one of:
91      :LOCAL (the default)
92        The alien is allocated on the stack, and has dynamic extent.
93      :STATIC
94        The alien is allocated on the heap, and has infinite extent. The alien
95        is allocated at load time, so the same piece of memory is used each time
96        this form executes.
97      :EXTERN
98        No alien is allocated, but VAR is established as a local name for
99        the external alien given by EXTERNAL-NAME."
100   (/show "entering WITH-ALIEN" bindings)
101   (with-auxiliary-alien-types env
102     (dolist (binding (reverse bindings))
103       (/show binding)
104       (destructuring-bind
105           (symbol type &optional (opt1 nil opt1p) (opt2 nil opt2p))
106           binding
107         (/show symbol type opt1 opt2)
108         (let ((alien-type (parse-alien-type type env)))
109           (/show alien-type)
110           (multiple-value-bind (allocation initial-value)
111               (if opt2p
112                   (values opt1 opt2)
113                   (case opt1
114                     (:extern
115                      (values opt1 (guess-alien-name-from-lisp-name symbol)))
116                     (:static
117                      (values opt1 nil))
118                     (t
119                      (values :local opt1))))
120             (/show allocation initial-value)
121             (setf body
122                   (ecase allocation
123                     #+nil
124                     (:static
125                      (let ((sap
126                             (make-symbol (concatenate 'string "SAP-FOR-"
127                                                       (symbol-name symbol)))))
128                        `((let ((,sap (load-time-value (%make-alien ...))))
129                            (declare (type system-area-pointer ,sap))
130                            (symbol-macrolet
131                             ((,symbol (sap-alien ,sap ,type)))
132                             ,@(when initial-value
133                                 `((setq ,symbol ,initial-value)))
134                             ,@body)))))
135                     (:extern
136                      (/show ":EXTERN case")
137                      (let ((info (make-heap-alien-info
138                                   :type alien-type
139                                   :sap-form `(foreign-symbol-address
140                                               ',initial-value))))
141                        `((symbol-macrolet
142                           ((,symbol (%heap-alien ',info)))
143                           ,@body))))
144                     (:local
145                      (/show ":LOCAL case")
146                      (let ((var (gensym))
147                            (initval (if initial-value (gensym)))
148                            (info (make-local-alien-info :type alien-type)))
149                        (/show var initval info)
150                        `((let ((,var (make-local-alien ',info))
151                                ,@(when initial-value
152                                    `((,initval ,initial-value))))
153                            (note-local-alien-type ',info ,var)
154                            (multiple-value-prog1
155                                (symbol-macrolet
156                                 ((,symbol (local-alien ',info ,var)))
157                                 ,@(when initial-value
158                                     `((setq ,symbol ,initval)))
159                                 ,@body)
160                                (dispose-local-alien ',info ,var))))))))))))
161     (/show "revised" body)
162     (verify-local-auxiliaries-okay)
163     (/show "back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
164     `(symbol-macrolet ((&auxiliary-type-definitions&
165                         ,(append *new-auxiliary-types*
166                                  (auxiliary-type-definitions env))))
167        ,@body)))
168 \f
169 ;;;; runtime C values that don't correspond directly to Lisp types
170
171 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
172 ;;; 'cause it has to be real early in the cold-load order.
173 #!-sb-fluid (declaim (freeze-type alien-value))
174 (def!method print-object ((value alien-value) stream)
175   (print-unreadable-object (value stream)
176     (format stream
177             "~S :SAP #X~8,'0X"
178             'alien-value
179             (sap-int (alien-value-sap value)))))
180
181 #!-sb-fluid (declaim (inline null-alien))
182 (defun null-alien (x)
183   #!+sb-doc
184   "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
185   (zerop (sap-int (alien-sap x))))
186
187 (defmacro sap-alien (sap type &environment env)
188   #!+sb-doc
189   "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
190    evaluated.) TYPE must be pointer-like."
191   (let ((alien-type (parse-alien-type type env)))
192     (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
193         `(%sap-alien ,sap ',alien-type)
194         (error "cannot make aliens of type ~S out of SAPs" type))))
195
196 (defun %sap-alien (sap type)
197   (declare (type system-area-pointer sap)
198            (type alien-type type))
199   (make-alien-value :sap sap :type type))
200
201 (defun alien-sap (alien)
202   #!+sb-doc
203   "Return a System-Area-Pointer pointing to Alien's data."
204   (declare (type alien-value alien))
205   (alien-value-sap alien))
206 \f
207 ;;;; allocation/deallocation of heap aliens
208
209 (defmacro make-alien (type &optional size &environment env)
210   #!+sb-doc
211   "Allocate an alien of type TYPE and return an alien pointer to it. If SIZE
212    is supplied, how it is interpreted depends on TYPE. If TYPE is an array
213    type, SIZE is used as the first dimension for the allocated array. If TYPE
214    is not an array, then SIZE is the number of elements to allocate. The
215    memory is allocated using ``malloc'', so it can be passed to foreign
216    functions which use ``free''."
217   (let ((alien-type (if (alien-type-p type)
218                         type
219                         (parse-alien-type type env))))
220     (multiple-value-bind (size-expr element-type)
221         (if (alien-array-type-p alien-type)
222             (let ((dims (alien-array-type-dimensions alien-type)))
223               (cond
224                (size
225                 (unless dims
226                   (error
227                    "cannot override the size of zero-dimensional arrays"))
228                 (when (constantp size)
229                   (setf alien-type (copy-alien-array-type alien-type))
230                   (setf (alien-array-type-dimensions alien-type)
231                         (cons (eval size) (cdr dims)))))
232                (dims
233                 (setf size (car dims)))
234                (t
235                 (setf size 1)))
236               (values `(* ,size ,@(cdr dims))
237                       (alien-array-type-element-type alien-type)))
238             (values (or size 1) alien-type))
239       (let ((bits (alien-type-bits element-type))
240             (alignment (alien-type-alignment element-type)))
241         (unless bits
242           (error "The size of ~S is unknown."
243                  (unparse-alien-type element-type)))
244         (unless alignment
245           (error "The alignment of ~S is unknown."
246                  (unparse-alien-type element-type)))
247         `(%sap-alien (%make-alien (* ,(align-offset bits alignment)
248                                      ,size-expr))
249                      ',(make-alien-pointer-type :to alien-type))))))
250
251 ;;; Allocate a block of memory at least BITS bits long and return a
252 ;;; system area pointer to it.
253 #!-sb-fluid (declaim (inline %make-alien))
254 (defun %make-alien (bits)
255   (declare (type index bits))
256   (alien-funcall (extern-alien "malloc"
257                                (function system-area-pointer unsigned))
258                  (ash (the index (+ bits 7)) -3)))
259
260 #!-sb-fluid (declaim (inline free-alien))
261 (defun free-alien (alien)
262   #!+sb-doc
263   "Dispose of the storage pointed to by ALIEN. ALIEN must have been allocated
264    by MAKE-ALIEN or malloc(3)."
265   (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
266                  (alien-sap alien))
267   nil)
268 \f
269 ;;;; the SLOT operator
270
271 ;;; Find the field named SLOT, or die trying.
272 (defun slot-or-lose (type slot)
273   (declare (type alien-record-type type)
274            (type symbol slot))
275   (or (find slot (alien-record-type-fields type)
276             :key #'alien-record-field-name)
277       (error "There is no slot named ~S in ~S." slot type)))
278
279 ;;; Extract the value from the named slot from the record ALIEN. If
280 ;;; ALIEN is actually a pointer, then DEREF it first.
281 (defun slot (alien slot)
282   #!+sb-doc
283   "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
284   (declare (type alien-value alien)
285            (type symbol slot)
286            (optimize (inhibit-warnings 3)))
287   (let ((type (alien-value-type alien)))
288     (etypecase type
289       (alien-pointer-type
290        (slot (deref alien) slot))
291       (alien-record-type
292        (let ((field (slot-or-lose type slot)))
293          (extract-alien-value (alien-value-sap alien)
294                               (alien-record-field-offset field)
295                               (alien-record-field-type field)))))))
296
297 ;;; Deposit the value in the specified slot of the record ALIEN. If
298 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
299 ;;; this when it can't figure out anything better.
300 (defun %set-slot (alien slot value)
301   (declare (type alien-value alien)
302            (type symbol slot)
303            (optimize (inhibit-warnings 3)))
304   (let ((type (alien-value-type alien)))
305     (etypecase type
306       (alien-pointer-type
307        (%set-slot (deref alien) slot value))
308       (alien-record-type
309        (let ((field (slot-or-lose type slot)))
310          (deposit-alien-value (alien-value-sap alien)
311                               (alien-record-field-offset field)
312                               (alien-record-field-type field)
313                               value))))))
314
315 ;;; Compute the address of the specified slot and return a pointer to it.
316 (defun %slot-addr (alien slot)
317   (declare (type alien-value alien)
318            (type symbol slot)
319            (optimize (inhibit-warnings 3)))
320   (let ((type (alien-value-type alien)))
321     (etypecase type
322       (alien-pointer-type
323        (%slot-addr (deref alien) slot))
324       (alien-record-type
325        (let* ((field (slot-or-lose type slot))
326               (offset (alien-record-field-offset field))
327               (field-type (alien-record-field-type field)))
328          (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:byte-bits))
329                      (make-alien-pointer-type :to field-type)))))))
330 \f
331 ;;;; the DEREF operator
332
333 ;;; This function does most of the work of the different DEREF
334 ;;; methods. It returns two values: the type and the offset (in bits)
335 ;;; of the referred-to alien.
336 (defun deref-guts (alien indices)
337   (declare (type alien-value alien)
338            (type list indices)
339            (values alien-type integer))
340   (let ((type (alien-value-type alien)))
341     (etypecase type
342       (alien-pointer-type
343        (when (cdr indices)
344          (error "too many indices when derefing ~S: ~D"
345                 type
346                 (length indices)))
347        (let ((element-type (alien-pointer-type-to type)))
348          (values element-type
349                  (if indices
350                      (* (align-offset (alien-type-bits element-type)
351                                       (alien-type-alignment element-type))
352                         (car indices))
353                      0))))
354       (alien-array-type
355        (unless (= (length indices) (length (alien-array-type-dimensions type)))
356          (error "incorrect number of indices when derefing ~S: ~D"
357                 type (length indices)))
358        (labels ((frob (dims indices offset)
359                   (if (null dims)
360                       offset
361                       (frob (cdr dims) (cdr indices)
362                         (+ (if (zerop offset)
363                                0
364                                (* offset (car dims)))
365                            (car indices))))))
366          (let ((element-type (alien-array-type-element-type type)))
367            (values element-type
368                    (* (align-offset (alien-type-bits element-type)
369                                     (alien-type-alignment element-type))
370                       (frob (alien-array-type-dimensions type)
371                         indices 0)))))))))
372
373 ;;; Dereference the alien and return the results.
374 (defun deref (alien &rest indices)
375   #!+sb-doc
376   "De-reference an Alien pointer or array. If an array, the indices are used
377    as the indices of the array element to access. If a pointer, one index can
378    optionally be specified, giving the equivalent of C pointer arithmetic."
379   (declare (type alien-value alien)
380            (type list indices)
381            (optimize (inhibit-warnings 3)))
382   (multiple-value-bind (target-type offset) (deref-guts alien indices)
383     (extract-alien-value (alien-value-sap alien)
384                          offset
385                          target-type)))
386
387 (defun %set-deref (alien value &rest indices)
388   (declare (type alien-value alien)
389            (type list indices)
390            (optimize (inhibit-warnings 3)))
391   (multiple-value-bind (target-type offset) (deref-guts alien indices)
392     (deposit-alien-value (alien-value-sap alien)
393                          offset
394                          target-type
395                          value)))
396
397 (defun %deref-addr (alien &rest indices)
398   (declare (type alien-value alien)
399            (type list indices)
400            (optimize (inhibit-warnings 3)))
401   (multiple-value-bind (target-type offset) (deref-guts alien indices)
402     (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:byte-bits))
403                 (make-alien-pointer-type :to target-type))))
404 \f
405 ;;;; accessing heap alien variables
406
407 (defun %heap-alien (info)
408   (declare (type heap-alien-info info)
409            (optimize (inhibit-warnings 3)))
410   (extract-alien-value (eval (heap-alien-info-sap-form info))
411                        0
412                        (heap-alien-info-type info)))
413
414 (defun %set-heap-alien (info value)
415   (declare (type heap-alien-info info)
416            (optimize (inhibit-warnings 3)))
417   (deposit-alien-value (eval (heap-alien-info-sap-form info))
418                        0
419                        (heap-alien-info-type info)
420                        value))
421
422 (defun %heap-alien-addr (info)
423   (declare (type heap-alien-info info)
424            (optimize (inhibit-warnings 3)))
425   (%sap-alien (eval (heap-alien-info-sap-form info))
426               (make-alien-pointer-type :to (heap-alien-info-type info))))
427 \f
428 ;;;; accessing local aliens
429
430 (defun make-local-alien (info)
431   (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
432          (alien-sap (alien-sap alien)))
433     (finalize
434      alien
435      #'(lambda ()
436          (alien-funcall
437           (extern-alien "free" (function (values) system-area-pointer))
438           alien-sap)))
439     alien))
440
441 (defun note-local-alien-type (info alien)
442   (declare (ignore info alien))
443   nil)
444
445 (defun local-alien (info alien)
446   (declare (ignore info))
447   (deref alien))
448
449 (defun %set-local-alien (info alien value)
450   (declare (ignore info))
451   (setf (deref alien) value))
452
453 (define-setf-expander local-alien (&whole whole info alien)
454   (let ((value (gensym))
455         (info (if (and (consp info)
456                        (eq (car info) 'quote))
457                   (second info)
458                   (error "Something is wrong; local-alien-info not found: ~S"
459                          whole))))
460     (values nil
461             nil
462             (list value)
463             `(if (%local-alien-forced-to-memory-p ',info)
464                  (%set-local-alien ',info ,alien ,value)
465                  (setf ,alien
466                        (deport ,value ',(local-alien-info-type info))))
467             whole)))
468
469 (defun %local-alien-forced-to-memory-p (info)
470   (local-alien-info-force-to-memory-p info))
471
472 (defun %local-alien-addr (info alien)
473   (declare (type local-alien-info info))
474   (unless (local-alien-info-force-to-memory-p info)
475     (error "~S isn't forced to memory. Something went wrong." alien))
476   alien)
477
478 (defun dispose-local-alien (info alien)
479   (declare (ignore info))
480   (cancel-finalization alien)
481   (free-alien alien))
482 \f
483 ;;;; the CAST macro
484
485 (defmacro cast (alien type &environment env)
486   #!+sb-doc
487   "Convert ALIEN to an Alien of the specified TYPE (not evaluated.)  Both types
488    must be Alien array, pointer or function types."
489   `(%cast ,alien ',(parse-alien-type type env)))
490
491 (defun %cast (alien target-type)
492   (declare (type alien-value alien)
493            (type alien-type target-type)
494            (optimize (safety 2))
495            (optimize (inhibit-warnings 3)))
496   (if (or (alien-pointer-type-p target-type)
497           (alien-array-type-p target-type)
498           (alien-function-type-p target-type))
499       (let ((alien-type (alien-value-type alien)))
500         (if (or (alien-pointer-type-p alien-type)
501                 (alien-array-type-p alien-type)
502                 (alien-function-type-p alien-type))
503             (naturalize (alien-value-sap alien) target-type)
504             (error "~S cannot be casted." alien)))
505       (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
506 \f
507 ;;;; the ALIEN-SIZE macro
508
509 (defmacro alien-size (type &optional (units :bits) &environment env)
510   #!+sb-doc
511   "Return the size of the alien type TYPE. UNITS specifies the units to
512    use and can be either :BITS, :BYTES, or :WORDS."
513   (let* ((alien-type (parse-alien-type type env))
514          (bits (alien-type-bits alien-type)))
515     (if bits
516         (values (ceiling bits
517                          (ecase units
518                            (:bits 1)
519                            (:bytes sb!vm:byte-bits)
520                            (:words sb!vm:word-bits))))
521         (error "unknown size for alien type ~S"
522                (unparse-alien-type alien-type)))))
523 \f
524 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
525
526 (defun naturalize (alien type)
527   (declare (type alien-type type))
528   (funcall (coerce (compute-naturalize-lambda type) 'function)
529            alien type))
530
531 (defun deport (value type)
532   (declare (type alien-type type))
533   (funcall (coerce (compute-deport-lambda type) 'function)
534            value type))
535
536 (defun extract-alien-value (sap offset type)
537   (declare (type system-area-pointer sap)
538            (type unsigned-byte offset)
539            (type alien-type type))
540   (funcall (coerce (compute-extract-lambda type) 'function)
541            sap offset type))
542
543 (defun deposit-alien-value (sap offset type value)
544   (declare (type system-area-pointer sap)
545            (type unsigned-byte offset)
546            (type alien-type type))
547   (funcall (coerce (compute-deposit-lambda type) 'function)
548            sap offset type value))
549 \f
550 ;;;; ALIEN-FUNCALL, DEF-ALIEN-ROUTINE
551
552 (defun alien-funcall (alien &rest args)
553   #!+sb-doc
554   "Call the foreign function ALIEN with the specified arguments. ALIEN's
555    type specifies the argument and result types."
556   (declare (type alien-value alien))
557   (let ((type (alien-value-type alien)))
558     (typecase type
559       (alien-pointer-type
560        (apply #'alien-funcall (deref alien) args))
561       (alien-function-type
562        (unless (= (length (alien-function-type-arg-types type))
563                   (length args))
564          (error "wrong number of arguments for ~S~%expected ~D, got ~D"
565                 type
566                 (length (alien-function-type-arg-types type))
567                 (length args)))
568        (let ((stub (alien-function-type-stub type)))
569          (unless stub
570            (setf stub
571                  (let ((fun (gensym))
572                        (parms (make-gensym-list (length args))))
573                    (compile nil
574                             `(lambda (,fun ,@parms)
575                                (declare (type (alien ,type) ,fun))
576                                (alien-funcall ,fun ,@parms)))))
577            (setf (alien-function-type-stub type) stub))
578          (apply stub alien args)))
579       (t
580        (error "~S is not an alien function." alien)))))
581
582 (defmacro def-alien-routine (name result-type &rest args &environment lexenv)
583   #!+sb-doc
584   "DEF-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
585
586   Define a foreign interface function for the routine with the specified NAME.
587   Also automatically DECLAIM the FTYPE of the defined function.
588
589   NAME may be either a string, a symbol, or a list of the form (string symbol).
590
591   RETURN-TYPE is the alien type for the function return value. VOID may be
592   used to specify a function with no result. 
593
594   The remaining forms specify individual arguments that are passed to the
595   routine. ARG-NAME is a symbol that names the argument, primarily for
596   documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
597   way that the argument is passed.
598
599   :IN
600         An :IN argument is simply passed by value. The value to be passed is
601         obtained from argument(s) to the interface function. No values are
602         returned for :In arguments. This is the default mode.
603
604   :OUT
605         The specified argument type must be a pointer to a fixed sized object.
606         A pointer to a preallocated object is passed to the routine, and the
607         the object is accessed on return, with the value being returned from
608         the interface function. :OUT and :IN-OUT cannot be used with pointers
609         to arrays, records or functions.
610
611   :COPY
612         This is similar to :IN, except that the argument values are stored
613         on the stack, and a pointer to the object is passed instead of
614         the value itself.
615
616   :IN-OUT
617         This is a combination of :OUT and :COPY. A pointer to the argument is
618         passed, with the object being initialized from the supplied argument
619         and the return value being determined by accessing the object on
620         return."
621   (multiple-value-bind (lisp-name alien-name)
622       (pick-lisp-and-alien-names name)
623     (collect ((docs) (lisp-args) (arg-types) (alien-vars)
624               (alien-args) (results))
625       (dolist (arg args)
626         (if (stringp arg)
627             (docs arg)
628             (destructuring-bind (name type &optional (style :in)) arg
629               (unless (member style '(:in :copy :out :in-out))
630                 (error "bogus argument style ~S in ~S" style arg))
631               (unless (eq style :out)
632                 (lisp-args name))
633               (when (and (member style '(:out :in-out))
634                          (typep (parse-alien-type type lexenv)
635                                 'alien-pointer-type))
636                 (error "can't use :OUT or :IN-OUT on pointer-like type:~%  ~S"
637                        type))
638               (cond ((eq style :in)
639                      (arg-types type)
640                      (alien-args name))
641                     (t
642                      (arg-types `(* ,type))
643                      (if (eq style :out)
644                          (alien-vars `(,name ,type))
645                          (alien-vars `(,name ,type ,name)))
646                      (alien-args `(addr ,name))))
647               (when (or (eq style :out) (eq style :in-out))
648                 (results name)))))
649       `(progn
650
651          ;; The theory behind this automatic DECLAIM is that (1) if
652          ;; you're calling C, static typing is what you're doing
653          ;; anyway, and (2) such a declamation can be (especially for
654          ;; alien values) both messy to do by hand and very important
655          ;; for performance of later code which uses the return value.
656          (declaim (ftype (function (mapcar (constantly t) ',args)
657                                    (alien ,result-type))
658                          ,lisp-name))
659
660          (defun ,lisp-name ,(lisp-args)
661            ,@(docs)
662            (with-alien
663             ((,lisp-name (function ,result-type ,@(arg-types))
664                          :extern ,alien-name)
665              ,@(alien-vars))
666             ,(if (alien-values-type-p result-type)
667                  (let ((temps (make-gensym-list
668                                (length
669                                 (alien-values-type-values result-type)))))
670                    `(multiple-value-bind ,temps
671                         (alien-funcall ,lisp-name ,@(alien-args))
672                       (values ,@temps ,@(results))))
673                  `(values (alien-funcall ,lisp-name ,@(alien-args))
674                           ,@(results)))))))))
675 \f
676 (defun alien-typep (object type)
677   #!+sb-doc
678   "Return T iff OBJECT is an alien of type TYPE."
679   (let ((lisp-rep-type (compute-lisp-rep-type type)))
680     (if lisp-rep-type
681         (typep object lisp-rep-type)
682         (and (alien-value-p object)
683              (alien-subtype-p (alien-value-type object) type)))))