0.8.21.21: fix & share EXTERN-ALIEN-NAME logic (fixes bug #373)
[sbcl.git] / src / compiler / x86 / macros.lisp
1 ;;;; a bunch of handy macros for the x86
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!VM")
13
14 ;;; We can load/store into fp registers through the top of stack
15 ;;; %st(0) (fr0 here). Loads imply a push to an empty register which
16 ;;; then changes all the reg numbers. These macros help manage that.
17
18 ;;; Use this when we don't have to load anything. It preserves old tos
19 ;;; value, but probably destroys tn with operation.
20 (defmacro with-tn@fp-top((tn) &body body)
21   `(progn
22     (unless (zerop (tn-offset ,tn))
23       (inst fxch ,tn))
24     ,@body
25     (unless (zerop (tn-offset ,tn))
26       (inst fxch ,tn))))
27
28 ;;; Use this to prepare for load of new value from memory. This
29 ;;; changes the register numbering so the next instruction had better
30 ;;; be a FP load from memory; a register load from another register
31 ;;; will probably be loading the wrong register!
32 (defmacro with-empty-tn@fp-top((tn) &body body)
33   `(progn
34     (inst fstp ,tn)
35     ,@body
36     (unless (zerop (tn-offset ,tn))
37       (inst fxch ,tn))))                ; save into new dest and restore st(0)
38 \f
39 ;;;; instruction-like macros
40
41 (defmacro move (dst src)
42   #!+sb-doc
43   "Move SRC into DST unless they are location=."
44   (once-only ((n-dst dst)
45               (n-src src))
46     `(unless (location= ,n-dst ,n-src)
47        (inst mov ,n-dst ,n-src))))
48
49 (defmacro make-ea-for-object-slot (ptr slot lowtag)
50   `(make-ea :dword :base ,ptr :disp (- (* ,slot n-word-bytes) ,lowtag)))
51
52 (defmacro loadw (value ptr &optional (slot 0) (lowtag 0))
53   `(inst mov ,value (make-ea-for-object-slot ,ptr ,slot ,lowtag)))
54
55 (defmacro storew (value ptr &optional (slot 0) (lowtag 0))
56   (once-only ((value value))
57     `(inst mov (make-ea-for-object-slot ,ptr ,slot ,lowtag) ,value)))
58
59 (defmacro pushw (ptr &optional (slot 0) (lowtag 0))
60   `(inst push (make-ea-for-object-slot ,ptr ,slot ,lowtag)))
61
62 (defmacro popw (ptr &optional (slot 0) (lowtag 0))
63   `(inst pop (make-ea-for-object-slot ,ptr ,slot ,lowtag)))
64 \f
65 ;;;; macros to generate useful values
66
67 (defmacro load-symbol (reg symbol)
68   `(inst mov ,reg (+ nil-value (static-symbol-offset ,symbol))))
69
70 (defmacro load-symbol-value (reg symbol)
71   `(inst mov ,reg
72          (make-ea :dword
73                   :disp (+ nil-value
74                            (static-symbol-offset ',symbol)
75                            (ash symbol-value-slot word-shift)
76                            (- other-pointer-lowtag)))))
77
78 (defmacro store-symbol-value (reg symbol)
79   `(inst mov
80          (make-ea :dword
81                   :disp (+ nil-value
82                            (static-symbol-offset ',symbol)
83                            (ash symbol-value-slot word-shift)
84                            (- other-pointer-lowtag)))
85          ,reg))
86
87 #!+sb-thread
88 (defmacro load-tl-symbol-value (reg symbol)
89   `(progn
90     (inst mov ,reg
91      (make-ea :dword
92       :disp (+ nil-value
93                (static-symbol-offset ',symbol)
94                (ash symbol-tls-index-slot word-shift)
95                (- other-pointer-lowtag))))
96     (inst fs-segment-prefix)
97     (inst mov ,reg (make-ea :dword :scale 1 :index ,reg))))
98 #!-sb-thread
99 (defmacro load-tl-symbol-value (reg symbol) `(load-symbol-value ,reg ,symbol))
100
101 #!+sb-thread
102 (defmacro store-tl-symbol-value (reg symbol temp)
103   `(progn
104     (inst mov ,temp
105      (make-ea :dword
106       :disp (+ nil-value
107                (static-symbol-offset ',symbol)
108                (ash symbol-tls-index-slot word-shift)
109                (- other-pointer-lowtag))))
110     (inst fs-segment-prefix)
111     (inst mov (make-ea :dword :scale 1 :index ,temp) ,reg)))
112 #!-sb-thread
113 (defmacro store-tl-symbol-value (reg symbol temp)
114   (declare (ignore temp))
115   `(store-symbol-value ,reg ,symbol))
116   
117 (defmacro load-type (target source &optional (offset 0))
118   #!+sb-doc
119   "Loads the type bits of a pointer into target independent of
120    byte-ordering issues."
121   (once-only ((n-target target)
122               (n-source source)
123               (n-offset offset))
124     (ecase *backend-byte-order*
125       (:little-endian
126        `(inst mov ,n-target
127               (make-ea :byte :base ,n-source :disp ,n-offset)))
128       (:big-endian
129        `(inst mov ,n-target
130               (make-ea :byte :base ,n-source :disp (+ ,n-offset 3)))))))
131 \f
132 ;;;; allocation helpers
133
134 ;;; All allocation is done by calls to assembler routines that
135 ;;; eventually invoke the C alloc() function.  Once upon a time
136 ;;; (before threads) allocation within an alloc_region could also be
137 ;;; done inline, with the aid of two C symbols storing the current
138 ;;; allocation region boundaries; however, C symbols are global.
139
140 ;;; C calls for allocation don't /seem/ to make an awful lot of
141 ;;; difference to speed.  Guessing from historical context, it looks
142 ;;; like inline allocation was introduced before pseudo-atomic, at
143 ;;; which time all calls to alloc() would have needed a syscall to
144 ;;; mask signals for the duration.  Now we have pseudoatomic there's
145 ;;; no need for that overhead.  Still, inline alloc would be a neat
146 ;;; addition someday (except see below).
147
148 (defun allocation-dynamic-extent (alloc-tn size)
149   (inst sub esp-tn size)
150   ;; FIXME: SIZE _should_ be double-word aligned (suggested but
151   ;; unfortunately not enforced by PAD-DATA-BLOCK and
152   ;; WITH-FIXED-ALLOCATION), so that ESP is always divisible by 8 (for
153   ;; 32-bit lispobjs).  In that case, this AND instruction is
154   ;; unneccessary and could be removed.  If not, explain why.  -- CSR,
155   ;; 2004-03-30
156   (inst and esp-tn #.(ldb (byte 32 0) (lognot lowtag-mask)))
157   (aver (not (location= alloc-tn esp-tn)))
158   (inst mov alloc-tn esp-tn)
159   (values))
160
161 (defun allocation-notinline (alloc-tn size)
162   (let* ((alloc-tn-offset (tn-offset alloc-tn))
163          ;; C call to allocate via dispatch routines. Each
164          ;; destination has a special entry point. The size may be a
165          ;; register or a constant.
166          (tn-text (ecase alloc-tn-offset
167                     (#.eax-offset "eax")
168                     (#.ecx-offset "ecx")
169                     (#.edx-offset "edx")
170                     (#.ebx-offset "ebx")
171                     (#.esi-offset "esi")
172                     (#.edi-offset "edi")))
173          (size-text (case size (8 "8_") (16 "16_") (t ""))))
174     (unless (or (eql size 8) (eql size 16))
175       (unless (and (tn-p size) (location= alloc-tn size))
176         (inst mov alloc-tn size)))
177     (inst call (make-fixup (concatenate 'string
178                                          "alloc_" size-text
179                                          "to_" tn-text)
180                            :foreign))))
181
182 (defun allocation-inline (alloc-tn size)
183   (let ((ok (gen-label))
184         (free-pointer
185          (make-ea :dword :disp 
186                   #!+sb-thread (* n-word-bytes thread-alloc-region-slot)
187                   #!-sb-thread (make-fixup "boxed_region" :foreign)
188                   :scale 1)) ; thread->alloc_region.free_pointer
189         (end-addr 
190          (make-ea :dword :disp
191                   #!+sb-thread (* n-word-bytes (1+ thread-alloc-region-slot))
192                   #!-sb-thread (make-fixup "boxed_region" :foreign 4)
193                   :scale 1)))   ; thread->alloc_region.end_addr
194     (unless (and (tn-p size) (location= alloc-tn size))
195       (inst mov alloc-tn size))
196     #!+sb-thread (inst fs-segment-prefix)
197     (inst add alloc-tn free-pointer)
198     #!+sb-thread (inst fs-segment-prefix)
199     (inst cmp alloc-tn end-addr)
200     (inst jmp :be OK)
201     (let ((dst (ecase (tn-offset alloc-tn)
202                  (#.eax-offset "alloc_overflow_eax")
203                  (#.ecx-offset "alloc_overflow_ecx")
204                  (#.edx-offset "alloc_overflow_edx")
205                  (#.ebx-offset "alloc_overflow_ebx")
206                  (#.esi-offset "alloc_overflow_esi")
207                  (#.edi-offset "alloc_overflow_edi"))))
208       (inst call (make-fixup dst :foreign)))
209     (emit-label ok)
210     #!+sb-thread (inst fs-segment-prefix)
211     (inst xchg free-pointer alloc-tn))
212   (values))
213
214
215 ;;; Emit code to allocate an object with a size in bytes given by
216 ;;; SIZE.  The size may be an integer or a TN. If Inline is a VOP
217 ;;; node-var then it is used to make an appropriate speed vs size
218 ;;; decision.
219
220 ;;; Allocation should only be used inside a pseudo-atomic section, which
221 ;;; should also cover subsequent initialization of the object.
222
223 ;;; (FIXME: so why aren't we asserting this?)
224
225 (defun allocation (alloc-tn size &optional inline dynamic-extent)
226   (cond
227     (dynamic-extent (allocation-dynamic-extent alloc-tn size))
228     ;; FIXME: for reasons unknown, inline allocation is a speed win on
229     ;; non-P4s, and a speed loss on P4s (and probably other such
230     ;; high-spec high-cache machines).  :INLINE-ALLOCATION-IS-GOOD is
231     ;; a bit of a KLUDGE, really.  -- CSR, 2004-08-05 (following
232     ;; observations made by ASF and Juho Snellman)
233     ((and (member :inline-allocation-is-good *backend-subfeatures*)
234           (or (null inline) (policy inline (>= speed space))))
235      (allocation-inline alloc-tn size))
236     (t (allocation-notinline alloc-tn size)))
237   (values))
238
239 ;;; Allocate an other-pointer object of fixed SIZE with a single word
240 ;;; header having the specified WIDETAG value. The result is placed in
241 ;;; RESULT-TN.
242 (defmacro with-fixed-allocation ((result-tn widetag size &optional inline)
243                                  &rest forms)
244   `(pseudo-atomic
245     (allocation ,result-tn (pad-data-block ,size) ,inline)
246     (storew (logior (ash (1- ,size) n-widetag-bits) ,widetag)
247             ,result-tn)
248     (inst lea ,result-tn
249      (make-ea :byte :base ,result-tn :disp other-pointer-lowtag))
250     ,@forms))
251 \f
252 ;;;; error code
253 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
254   (defun emit-error-break (vop kind code values)
255     (let ((vector (gensym)))
256       `((inst int 3)                            ; i386 breakpoint instruction
257         ;; The return PC points here; note the location for the debugger.
258         (let ((vop ,vop))
259           (when vop
260                 (note-this-location vop :internal-error)))
261         (inst byte ,kind)                       ; eg trap_Xyyy
262         (with-adjustable-vector (,vector)       ; interr arguments
263           (write-var-integer (error-number-or-lose ',code) ,vector)
264           ,@(mapcar (lambda (tn)
265                       `(let ((tn ,tn))
266                          ;; classic CMU CL comment:
267                          ;;   zzzzz jrd here. tn-offset is zero for constant
268                          ;;   tns.
269                          (write-var-integer (make-sc-offset (sc-number
270                                                              (tn-sc tn))
271                                                             (or (tn-offset tn)
272                                                                 0))
273                                             ,vector)))
274                     values)
275           (inst byte (length ,vector))
276           (dotimes (i (length ,vector))
277             (inst byte (aref ,vector i))))))))
278
279 (defmacro error-call (vop error-code &rest values)
280   #!+sb-doc
281   "Cause an error. ERROR-CODE is the error to cause."
282   (cons 'progn
283         (emit-error-break vop error-trap error-code values)))
284
285 (defmacro generate-error-code (vop error-code &rest values)
286   #!+sb-doc
287   "Generate-Error-Code Error-code Value*
288   Emit code for an error with the specified Error-Code and context Values."
289   `(assemble (*elsewhere*)
290      (let ((start-lab (gen-label)))
291        (emit-label start-lab)
292        (error-call ,vop ,error-code ,@values)
293        start-lab)))
294
295 \f
296 ;;;; PSEUDO-ATOMIC
297
298 ;;; This is used to wrap operations which leave untagged memory lying
299 ;;; around.  It's an operation which the AOP weenies would describe as
300 ;;; having "cross-cutting concerns", meaning it appears all over the
301 ;;; place and there's no logical single place to attach documentation.
302 ;;; grep (mostly in src/runtime) is your friend 
303
304 ;;; FIXME: *PSEUDO-ATOMIC-FOO* could be made into *PSEUDO-ATOMIC-BITS*,
305 ;;; set with a single operation and cleared with SHR *PSEUDO-ATOMIC-BITS*,-2;
306 ;;; the ATOMIC bit is bit 0, the INTERRUPTED bit is bit 1, and you check
307 ;;; the C flag after the shift to see whether you were interrupted.
308 ;;;
309 ;;; KLUDGE: since the stack on the x86 is treated conservatively, it
310 ;;; does not matter whether a signal occurs during construction of a
311 ;;; dynamic-extent object, as the half-finished construction of the
312 ;;; object will not cause any difficulty.  We can therefore elide 
313 (defmacro maybe-pseudo-atomic (really-p &body forms)
314   `(if ,really-p
315        (progn ,@forms)
316        (pseudo-atomic ,@forms)))
317
318 #!+sb-thread
319 (defmacro pseudo-atomic (&rest forms)
320   (with-unique-names (label)
321     `(let ((,label (gen-label)))
322        (inst fs-segment-prefix)
323        (inst mov (make-ea :byte
324                           :disp (* 4 thread-pseudo-atomic-interrupted-slot)) 0)
325        (inst fs-segment-prefix)
326        (inst mov (make-ea :byte :disp (* 4 thread-pseudo-atomic-atomic-slot)) 1)
327        ,@forms
328        (inst fs-segment-prefix)
329        (inst mov (make-ea :byte :disp (* 4 thread-pseudo-atomic-atomic-slot)) 0)
330        (inst fs-segment-prefix)
331        (inst cmp (make-ea :byte
332                           :disp (* 4 thread-pseudo-atomic-interrupted-slot)) 0)
333        (inst jmp :eq ,label)
334        ;; if PAI was set, interrupts were disabled at the same
335        ;; time using the process signal mask.
336        (inst break pending-interrupt-trap)
337        (emit-label ,label))))
338
339 #!-sb-thread
340 (defmacro pseudo-atomic (&rest forms)
341   (with-unique-names (label)
342     `(let ((,label (gen-label)))
343        ;; FIXME: The MAKE-EA noise should become a MACROLET macro
344        ;; or something. (perhaps SVLB, for static variable low
345        ;; byte)
346        (inst mov (make-ea :byte :disp (+ nil-value
347                                          (static-symbol-offset
348                                           '*pseudo-atomic-interrupted*)
349                                          (ash symbol-value-slot word-shift)
350                                          ;; FIXME: Use mask, not minus, to
351                                          ;; take out type bits.
352                                          (- other-pointer-lowtag)))
353              0)
354        (inst mov (make-ea :byte :disp (+ nil-value
355                                          (static-symbol-offset
356                                           '*pseudo-atomic-atomic*)
357                                          (ash symbol-value-slot word-shift)
358                                          (- other-pointer-lowtag)))
359              (fixnumize 1))
360        ,@forms
361        (inst mov (make-ea :byte :disp (+ nil-value
362                                          (static-symbol-offset
363                                           '*pseudo-atomic-atomic*)
364                                          (ash symbol-value-slot word-shift)
365                                          (- other-pointer-lowtag)))
366              0)
367        ;; KLUDGE: Is there any requirement for interrupts to be
368        ;; handled in order? It seems as though an interrupt coming
369        ;; in at this point will be executed before any pending
370        ;; interrupts.  Or do incoming interrupts check to see
371        ;; whether any interrupts are pending? I wish I could find
372        ;; the documentation for pseudo-atomics.. -- WHN 19991130
373        (inst cmp (make-ea :byte
374                           :disp (+ nil-value
375                                    (static-symbol-offset
376                                     '*pseudo-atomic-interrupted*)
377                                    (ash symbol-value-slot word-shift)
378                                    (- other-pointer-lowtag)))
379              0)
380        (inst jmp :eq ,label)
381        ;; if PAI was set, interrupts were disabled at the same
382        ;; time using the process signal mask.
383        (inst break pending-interrupt-trap)
384        (emit-label ,label))))
385 \f
386 ;;;; indexed references
387
388 (defmacro define-full-reffer (name type offset lowtag scs el-type &optional translate)
389   `(progn
390      (define-vop (,name)
391        ,@(when translate
392            `((:translate ,translate)))
393        (:policy :fast-safe)
394        (:args (object :scs (descriptor-reg))
395               (index :scs (any-reg)))
396        (:arg-types ,type tagged-num)
397        (:results (value :scs ,scs))
398        (:result-types ,el-type)
399        (:generator 3                    ; pw was 5
400          (inst mov value (make-ea :dword :base object :index index
401                                   :disp (- (* ,offset n-word-bytes)
402                                            ,lowtag)))))
403      (define-vop (,(symbolicate name "-C"))
404        ,@(when translate
405            `((:translate ,translate)))
406        (:policy :fast-safe)
407        (:args (object :scs (descriptor-reg)))
408        (:info index)
409        (:arg-types ,type (:constant (signed-byte 30)))
410        (:results (value :scs ,scs))
411        (:result-types ,el-type)
412        (:generator 2                    ; pw was 5
413          (inst mov value (make-ea :dword :base object
414                                   :disp (- (* (+ ,offset index) n-word-bytes)
415                                            ,lowtag)))))))
416
417 (defmacro define-full-setter (name type offset lowtag scs el-type &optional translate)
418   `(progn
419      (define-vop (,name)
420        ,@(when translate
421            `((:translate ,translate)))
422        (:policy :fast-safe)
423        (:args (object :scs (descriptor-reg))
424               (index :scs (any-reg))
425               (value :scs ,scs :target result))
426        (:arg-types ,type tagged-num ,el-type)
427        (:results (result :scs ,scs))
428        (:result-types ,el-type)
429        (:generator 4                    ; was 5
430          (inst mov (make-ea :dword :base object :index index
431                             :disp (- (* ,offset n-word-bytes) ,lowtag))
432                value)
433          (move result value)))
434      (define-vop (,(symbolicate name "-C"))
435        ,@(when translate
436            `((:translate ,translate)))
437        (:policy :fast-safe)
438        (:args (object :scs (descriptor-reg))
439               (value :scs ,scs :target result))
440        (:info index)
441        (:arg-types ,type (:constant (signed-byte 30)) ,el-type)
442        (:results (result :scs ,scs))
443        (:result-types ,el-type)
444        (:generator 3                    ; was 5
445          (inst mov (make-ea :dword :base object
446                             :disp (- (* (+ ,offset index) n-word-bytes)
447                                      ,lowtag))
448                value)
449          (move result value)))))
450
451 ;;; helper for alien stuff.
452 (defmacro with-pinned-objects ((&rest objects) &body body)
453   "Arrange with the garbage collector that the pages occupied by
454 OBJECTS will not be moved in memory for the duration of BODY.
455 Useful for e.g. foreign calls where another thread may trigger
456 garbage collection"
457   `(multiple-value-prog1
458        (progn
459          ,@(loop for p in objects 
460                  collect `(push-word-on-c-stack
461                            (int-sap (sb!kernel:get-lisp-obj-address ,p))))
462          ,@body)
463      ;; If the body returned normally, we should restore the stack pointer
464      ;; for the benefit of any following code in the same function.  If
465      ;; there's a non-local exit in the body, sp is garbage anyway and
466      ;; will get set appropriately from {a, the} frame pointer before it's
467      ;; next needed
468      (pop-words-from-c-stack ,(length objects))))