0.8.3.11
[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
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 (extern-alien-name 
178                             (concatenate 'string
179                                          "alloc_" size-text
180                                          "to_" tn-text))
181                            :foreign))))
182
183 (defun allocation-inline (alloc-tn size)
184   (let ((ok (gen-label))
185         (free-pointer
186          (make-ea :dword :disp 
187                   #!+sb-thread (* n-word-bytes thread-alloc-region-slot)
188                   #!-sb-thread (make-fixup (extern-alien-name "boxed_region")
189                                             :foreign)
190                   :scale 1)) ; thread->alloc_region.free_pointer
191         (end-addr 
192          (make-ea :dword :disp
193                   #!+sb-thread (* n-word-bytes (1+ thread-alloc-region-slot))
194                   #!-sb-thread (make-fixup (extern-alien-name "boxed_region")
195                                            :foreign 4)
196                   :scale 1)))   ; thread->alloc_region.end_addr
197     (unless (and (tn-p size) (location= alloc-tn size))
198       (inst mov alloc-tn size))
199     #!+sb-thread (inst fs-segment-prefix)
200     (inst add alloc-tn free-pointer)
201     #!+sb-thread (inst fs-segment-prefix)
202     (inst cmp alloc-tn end-addr)
203     (inst jmp :be OK)
204     (let ((dst (ecase (tn-offset alloc-tn)
205                  (#.eax-offset "alloc_overflow_eax")
206                  (#.ecx-offset "alloc_overflow_ecx")
207                  (#.edx-offset "alloc_overflow_edx")
208                  (#.ebx-offset "alloc_overflow_ebx")
209                  (#.esi-offset "alloc_overflow_esi")
210                  (#.edi-offset "alloc_overflow_edi"))))
211       (inst call (make-fixup (extern-alien-name dst) :foreign)))
212     (emit-label ok)
213     #!+sb-thread (inst fs-segment-prefix)
214     (inst xchg free-pointer alloc-tn))
215   (values))
216
217
218 ;;; Emit code to allocate an object with a size in bytes given by
219 ;;; SIZE.  The size may be an integer or a TN. If Inline is a VOP
220 ;;; node-var then it is used to make an appropriate speed vs size
221 ;;; decision.
222
223 ;;; Allocation should only be used inside a pseudo-atomic section, which
224 ;;; should also cover subsequent initialization of the object.
225
226 ;;; (FIXME: so why aren't we asserting this?)
227
228 (defun allocation (alloc-tn size &optional inline dynamic-extent)
229   (cond
230     (dynamic-extent (allocation-dynamic-extent alloc-tn size))
231     ((or (null inline) (policy inline (>= speed space)))
232      (allocation-inline alloc-tn size))
233     (t (allocation-notinline alloc-tn size)))
234   (values))
235
236 ;;; Allocate an other-pointer object of fixed SIZE with a single word
237 ;;; header having the specified WIDETAG value. The result is placed in
238 ;;; RESULT-TN.
239 (defmacro with-fixed-allocation ((result-tn widetag size &optional inline)
240                                  &rest forms)
241   `(pseudo-atomic
242     (allocation ,result-tn (pad-data-block ,size) ,inline)
243     (storew (logior (ash (1- ,size) n-widetag-bits) ,widetag)
244             ,result-tn)
245     (inst lea ,result-tn
246      (make-ea :byte :base ,result-tn :disp other-pointer-lowtag))
247     ,@forms))
248 \f
249 ;;;; error code
250 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
251   (defun emit-error-break (vop kind code values)
252     (let ((vector (gensym)))
253       `((inst int 3)                            ; i386 breakpoint instruction
254         ;; The return PC points here; note the location for the debugger.
255         (let ((vop ,vop))
256           (when vop
257                 (note-this-location vop :internal-error)))
258         (inst byte ,kind)                       ; eg trap_Xyyy
259         (with-adjustable-vector (,vector)       ; interr arguments
260           (write-var-integer (error-number-or-lose ',code) ,vector)
261           ,@(mapcar (lambda (tn)
262                       `(let ((tn ,tn))
263                          ;; classic CMU CL comment:
264                          ;;   zzzzz jrd here. tn-offset is zero for constant
265                          ;;   tns.
266                          (write-var-integer (make-sc-offset (sc-number
267                                                              (tn-sc tn))
268                                                             (or (tn-offset tn)
269                                                                 0))
270                                             ,vector)))
271                     values)
272           (inst byte (length ,vector))
273           (dotimes (i (length ,vector))
274             (inst byte (aref ,vector i))))))))
275
276 (defmacro error-call (vop error-code &rest values)
277   #!+sb-doc
278   "Cause an error. ERROR-CODE is the error to cause."
279   (cons 'progn
280         (emit-error-break vop error-trap error-code values)))
281
282 (defmacro generate-error-code (vop error-code &rest values)
283   #!+sb-doc
284   "Generate-Error-Code Error-code Value*
285   Emit code for an error with the specified Error-Code and context Values."
286   `(assemble (*elsewhere*)
287      (let ((start-lab (gen-label)))
288        (emit-label start-lab)
289        (error-call ,vop ,error-code ,@values)
290        start-lab)))
291
292 \f
293 ;;;; PSEUDO-ATOMIC
294
295 ;;; This is used to wrap operations which leave untagged memory lying
296 ;;; around.  It's an operation which the AOP weenies would describe as
297 ;;; having "cross-cutting concerns", meaning it appears all over the
298 ;;; place and there's no logical single place to attach documentation.
299 ;;; grep (mostly in src/runtime) is your friend 
300
301 ;;; FIXME: *PSEUDO-ATOMIC-FOO* could be made into *PSEUDO-ATOMIC-BITS*,
302 ;;; set with a single operation and cleared with SHR *PSEUDO-ATOMIC-BITS*,-2;
303 ;;; the ATOMIC bit is bit 0, the INTERRUPTED bit is bit 1, and you check
304 ;;; the C flag after the shift to see whether you were interrupted.
305 ;;;
306 ;;; KLUDGE: since the stack on the x86 is treated conservatively, it
307 ;;; does not matter whether a signal occurs during construction of a
308 ;;; dynamic-extent object, as the half-finished construction of the
309 ;;; object will not cause any difficulty.  We can therefore elide 
310 (defvar *dynamic-extent* nil)
311
312 #!+sb-thread
313 (defmacro pseudo-atomic (&rest forms)
314   (with-unique-names (label)
315     `(if *dynamic-extent* ; I will burn in hell
316          (progn ,@forms)
317          (let ((,label (gen-label)))
318            (inst fs-segment-prefix)
319            (inst mov (make-ea :byte 
320                               :disp (* 4 thread-pseudo-atomic-interrupted-slot)) 0)
321            (inst fs-segment-prefix)
322            (inst mov (make-ea :byte :disp (* 4 thread-pseudo-atomic-atomic-slot)) 1)
323            ,@forms
324            (inst fs-segment-prefix)
325            (inst mov (make-ea :byte :disp (* 4 thread-pseudo-atomic-atomic-slot)) 0)
326            (inst fs-segment-prefix)
327            (inst cmp (make-ea :byte
328                               :disp (* 4 thread-pseudo-atomic-interrupted-slot)) 0)
329            (inst jmp :eq ,label)
330            ;; if PAI was set, interrupts were disabled at the same
331            ;; time using the process signal mask.
332            (inst break pending-interrupt-trap)
333            (emit-label ,label)))))
334
335 #!-sb-thread
336 (defmacro pseudo-atomic (&rest forms)
337   (with-unique-names (label)
338     `(if *dynamic-extent*
339          (progn ,@forms)
340          (let ((,label (gen-label)))
341            ;; FIXME: The MAKE-EA noise should become a MACROLET macro
342            ;; or something. (perhaps SVLB, for static variable low
343            ;; byte)
344            (inst mov (make-ea :byte :disp (+ nil-value
345                                              (static-symbol-offset
346                                               '*pseudo-atomic-interrupted*)
347                                              (ash symbol-value-slot word-shift)
348                                              ;; FIXME: Use mask, not minus, to
349                                              ;; take out type bits.
350                                              (- other-pointer-lowtag)))
351                  0)
352            (inst mov (make-ea :byte :disp (+ nil-value
353                                              (static-symbol-offset
354                                               '*pseudo-atomic-atomic*)
355                                              (ash symbol-value-slot word-shift)
356                                              (- other-pointer-lowtag)))
357                  (fixnumize 1))
358            ,@forms
359            (inst mov (make-ea :byte :disp (+ nil-value
360                                              (static-symbol-offset
361                                               '*pseudo-atomic-atomic*)
362                                              (ash symbol-value-slot word-shift)
363                                              (- other-pointer-lowtag)))
364                  0)
365            ;; KLUDGE: Is there any requirement for interrupts to be
366            ;; handled in order? It seems as though an interrupt coming
367            ;; in at this point will be executed before any pending
368            ;; interrupts.  Or do incoming interrupts check to see
369            ;; whether any interrupts are pending? I wish I could find
370            ;; the documentation for pseudo-atomics.. -- WHN 19991130
371            (inst cmp (make-ea :byte
372                               :disp (+ nil-value
373                                        (static-symbol-offset
374                                         '*pseudo-atomic-interrupted*)
375                                        (ash symbol-value-slot word-shift)
376                                        (- other-pointer-lowtag)))
377                  0)
378            (inst jmp :eq ,label)
379            ;; if PAI was set, interrupts were disabled at the same
380            ;; time using the process signal mask.
381            (inst break pending-interrupt-trap)
382            (emit-label ,label)))))
383 \f
384 ;;;; indexed references
385
386 (defmacro define-full-reffer (name type offset lowtag scs el-type &optional translate)
387   `(progn
388      (define-vop (,name)
389        ,@(when translate
390            `((:translate ,translate)))
391        (:policy :fast-safe)
392        (:args (object :scs (descriptor-reg))
393               (index :scs (any-reg)))
394        (:arg-types ,type tagged-num)
395        (:results (value :scs ,scs))
396        (:result-types ,el-type)
397        (:generator 3                    ; pw was 5
398          (inst mov value (make-ea :dword :base object :index index
399                                   :disp (- (* ,offset n-word-bytes)
400                                            ,lowtag)))))
401      (define-vop (,(symbolicate name "-C"))
402        ,@(when translate
403            `((:translate ,translate)))
404        (:policy :fast-safe)
405        (:args (object :scs (descriptor-reg)))
406        (:info index)
407        (:arg-types ,type (:constant (signed-byte 30)))
408        (:results (value :scs ,scs))
409        (:result-types ,el-type)
410        (:generator 2                    ; pw was 5
411          (inst mov value (make-ea :dword :base object
412                                   :disp (- (* (+ ,offset index) n-word-bytes)
413                                            ,lowtag)))))))
414
415 (defmacro define-full-setter (name type offset lowtag scs el-type &optional translate)
416   `(progn
417      (define-vop (,name)
418        ,@(when translate
419            `((:translate ,translate)))
420        (:policy :fast-safe)
421        (:args (object :scs (descriptor-reg))
422               (index :scs (any-reg))
423               (value :scs ,scs :target result))
424        (:arg-types ,type tagged-num ,el-type)
425        (:results (result :scs ,scs))
426        (:result-types ,el-type)
427        (:generator 4                    ; was 5
428          (inst mov (make-ea :dword :base object :index index
429                             :disp (- (* ,offset n-word-bytes) ,lowtag))
430                value)
431          (move result value)))
432      (define-vop (,(symbolicate name "-C"))
433        ,@(when translate
434            `((:translate ,translate)))
435        (:policy :fast-safe)
436        (:args (object :scs (descriptor-reg))
437               (value :scs ,scs :target result))
438        (:info index)
439        (:arg-types ,type (:constant (signed-byte 30)) ,el-type)
440        (:results (result :scs ,scs))
441        (:result-types ,el-type)
442        (:generator 3                    ; was 5
443          (inst mov (make-ea :dword :base object
444                             :disp (- (* (+ ,offset index) n-word-bytes)
445                                      ,lowtag))
446                value)
447          (move result value)))))
448
449 ;;; helper for alien stuff.
450 (defmacro with-pinned-objects ((&rest objects) &body body)
451   "Arrange with the garbage collector that the pages occupied by
452 OBJECTS will not be moved in memory for the duration of BODY.
453 Useful for e.g. foreign calls where another thread may trigger
454 garbage collection"
455   `(multiple-value-prog1
456        (progn
457          ,@(loop for p in objects 
458                  collect `(push-word-on-c-stack
459                            (int-sap (sb!kernel:get-lisp-obj-address ,p))))
460          ,@body)
461      ;; If the body returned normally, we should restore the stack pointer
462      ;; for the benefit of any following code in the same function.  If
463      ;; there's a non-local exit in the body, sp is garbage anyway and
464      ;; will get set appropriately from {a, the} frame pointer before it's
465      ;; next needed
466      (pop-words-from-c-stack ,(length objects))))