af95da2250bf02cf904eebaaa29215e9a8eb43be
[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 &optional (size :dword))
50   `(make-ea ,size :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 ;;; A handy macro for storing widetags.
60 (defmacro storeb (value ptr &optional (slot 0) (lowtag 0))
61   (once-only ((value value))
62     `(inst mov (make-ea-for-object-slot ,ptr ,slot ,lowtag :byte) ,value)))
63
64 (defmacro pushw (ptr &optional (slot 0) (lowtag 0))
65   `(inst push (make-ea-for-object-slot ,ptr ,slot ,lowtag)))
66
67 (defmacro popw (ptr &optional (slot 0) (lowtag 0))
68   `(inst pop (make-ea-for-object-slot ,ptr ,slot ,lowtag)))
69 \f
70 ;;;; macros to generate useful values
71
72 (defmacro load-symbol (reg symbol)
73   `(inst mov ,reg (+ nil-value (static-symbol-offset ,symbol))))
74
75 (defmacro make-ea-for-symbol-value (symbol)
76   (declare (type symbol symbol))
77   `(make-ea :dword
78     :disp (+ nil-value
79            (static-symbol-offset ',symbol)
80            (ash symbol-value-slot word-shift)
81            (- other-pointer-lowtag))))
82
83 (defmacro load-symbol-value (reg symbol)
84   `(inst mov ,reg (make-ea-for-symbol-value ,symbol)))
85
86 (defmacro store-symbol-value (reg symbol)
87   `(inst mov (make-ea-for-symbol-value ,symbol) ,reg))
88
89 #!+sb-thread
90 (defmacro make-ea-for-symbol-tls-index (symbol)
91   (declare (type symbol symbol))
92   `(make-ea :dword
93     :disp (+ nil-value
94            (static-symbol-offset ',symbol)
95            (ash symbol-tls-index-slot word-shift)
96            (- other-pointer-lowtag))))
97
98 #!+sb-thread
99 (defmacro load-tl-symbol-value (reg symbol)
100   `(progn
101     (inst mov ,reg (make-ea-for-symbol-tls-index ,symbol))
102     (inst fs-segment-prefix)
103     (inst mov ,reg (make-ea :dword :base ,reg))))
104 #!-sb-thread
105 (defmacro load-tl-symbol-value (reg symbol) `(load-symbol-value ,reg ,symbol))
106
107 #!+sb-thread
108 (defmacro store-tl-symbol-value (reg symbol temp)
109   `(progn
110     (inst mov ,temp (make-ea-for-symbol-tls-index ,symbol))
111     (inst fs-segment-prefix)
112     (inst mov (make-ea :dword :base ,temp) ,reg)))
113 #!-sb-thread
114 (defmacro store-tl-symbol-value (reg symbol temp)
115   (declare (ignore temp))
116   `(store-symbol-value ,reg ,symbol))
117
118 (defmacro load-binding-stack-pointer (reg)
119   #!+sb-thread
120   `(progn
121      (inst fs-segment-prefix)
122      (inst mov ,reg (make-ea :dword
123                              :disp (* 4 thread-binding-stack-pointer-slot))))
124   #!-sb-thread
125   `(load-symbol-value ,reg *binding-stack-pointer*))
126
127 (defmacro store-binding-stack-pointer (reg)
128   #!+sb-thread
129   `(progn
130      (inst fs-segment-prefix)
131      (inst mov (make-ea :dword
132                         :disp (* 4 thread-binding-stack-pointer-slot))
133            ,reg))
134   #!-sb-thread
135   `(store-symbol-value ,reg *binding-stack-pointer*))
136
137 (defmacro load-type (target source &optional (offset 0))
138   #!+sb-doc
139   "Loads the type bits of a pointer into target independent of
140    byte-ordering issues."
141   (once-only ((n-target target)
142               (n-source source)
143               (n-offset offset))
144     (ecase *backend-byte-order*
145       (:little-endian
146        `(inst mov ,n-target
147               (make-ea :byte :base ,n-source :disp ,n-offset)))
148       (:big-endian
149        `(inst mov ,n-target
150               (make-ea :byte :base ,n-source :disp (+ ,n-offset 3)))))))
151 \f
152 ;;;; allocation helpers
153
154 ;;; Allocation within alloc_region (which is thread local) can be done
155 ;;; inline.  If the alloc_region is overflown allocation is done by
156 ;;; calling the C alloc() function.
157
158 ;;; C calls for allocation don't /seem/ to make an awful lot of
159 ;;; difference to speed. On pure consing it's about a 25%
160 ;;; gain. Guessing from historical context, it looks like inline
161 ;;; allocation was introduced before pseudo-atomic, at which time all
162 ;;; calls to alloc() would have needed a syscall to mask signals for
163 ;;; the duration.  Now we have pseudoatomic there's no need for that
164 ;;; overhead.
165
166 (defun allocation-dynamic-extent (alloc-tn size)
167   (inst sub esp-tn size)
168   ;; FIXME: SIZE _should_ be double-word aligned (suggested but
169   ;; unfortunately not enforced by PAD-DATA-BLOCK and
170   ;; WITH-FIXED-ALLOCATION), so that ESP is always divisible by 8 (for
171   ;; 32-bit lispobjs).  In that case, this AND instruction is
172   ;; unneccessary and could be removed.  If not, explain why.  -- CSR,
173   ;; 2004-03-30
174   (inst and esp-tn (lognot lowtag-mask))
175   (aver (not (location= alloc-tn esp-tn)))
176   (inst mov alloc-tn esp-tn)
177   (values))
178
179 (defun allocation-notinline (alloc-tn size)
180   (let* ((alloc-tn-offset (tn-offset alloc-tn))
181          ;; C call to allocate via dispatch routines. Each
182          ;; destination has a special entry point. The size may be a
183          ;; register or a constant.
184          (tn-text (ecase alloc-tn-offset
185                     (#.eax-offset "eax")
186                     (#.ecx-offset "ecx")
187                     (#.edx-offset "edx")
188                     (#.ebx-offset "ebx")
189                     (#.esi-offset "esi")
190                     (#.edi-offset "edi")))
191          (size-text (case size (8 "8_") (16 "16_") (t ""))))
192     (unless (or (eql size 8) (eql size 16))
193       (unless (and (tn-p size) (location= alloc-tn size))
194         (inst mov alloc-tn size)))
195     (inst call (make-fixup (concatenate 'string
196                                          "alloc_" size-text
197                                          "to_" tn-text)
198                            :foreign))))
199
200 (defun allocation-inline (alloc-tn size)
201   (let ((ok (gen-label))
202         (done (gen-label))
203         (free-pointer
204          (make-ea :dword :disp
205                   #!+sb-thread (* n-word-bytes thread-alloc-region-slot)
206                   #!-sb-thread (make-fixup "boxed_region" :foreign)
207                   :scale 1)) ; thread->alloc_region.free_pointer
208         (end-addr
209          (make-ea :dword :disp
210                   #!+sb-thread (* n-word-bytes (1+ thread-alloc-region-slot))
211                   #!-sb-thread (make-fixup "boxed_region" :foreign 4)
212                   :scale 1)))   ; thread->alloc_region.end_addr
213     (unless (and (tn-p size) (location= alloc-tn size))
214       (inst mov alloc-tn size))
215     #!+sb-thread (inst fs-segment-prefix)
216     (inst add alloc-tn free-pointer)
217     #!+sb-thread (inst fs-segment-prefix)
218     (inst cmp alloc-tn end-addr)
219     (inst jmp :be ok)
220     (let ((dst (ecase (tn-offset alloc-tn)
221                  (#.eax-offset "alloc_overflow_eax")
222                  (#.ecx-offset "alloc_overflow_ecx")
223                  (#.edx-offset "alloc_overflow_edx")
224                  (#.ebx-offset "alloc_overflow_ebx")
225                  (#.esi-offset "alloc_overflow_esi")
226                  (#.edi-offset "alloc_overflow_edi"))))
227       (inst call (make-fixup dst :foreign)))
228     (inst jmp-short done)
229     (emit-label ok)
230     ;; Swap ALLOC-TN and FREE-POINTER
231     (cond ((and (tn-p size) (location= alloc-tn size))
232            ;; XCHG is extremely slow, use the xor swap trick
233            #!+sb-thread (inst fs-segment-prefix)
234            (inst xor alloc-tn free-pointer)
235            #!+sb-thread (inst fs-segment-prefix)
236            (inst xor free-pointer alloc-tn)
237            #!+sb-thread (inst fs-segment-prefix)
238            (inst xor alloc-tn free-pointer))
239           (t
240            ;; It's easier if SIZE is still available.
241            #!+sb-thread (inst fs-segment-prefix)
242            (inst mov free-pointer alloc-tn)
243            (inst sub alloc-tn size)))
244     (emit-label done))
245   (values))
246
247
248 ;;; Emit code to allocate an object with a size in bytes given by
249 ;;; SIZE.  The size may be an integer or a TN. If Inline is a VOP
250 ;;; node-var then it is used to make an appropriate speed vs size
251 ;;; decision.
252
253 ;;; Allocation should only be used inside a pseudo-atomic section, which
254 ;;; should also cover subsequent initialization of the object.
255
256 ;;; (FIXME: so why aren't we asserting this?)
257
258 (defun allocation (alloc-tn size &optional inline dynamic-extent)
259   (cond
260     (dynamic-extent (allocation-dynamic-extent alloc-tn size))
261     ((or (null inline) (policy inline (>= speed space)))
262      (allocation-inline alloc-tn size))
263     (t (allocation-notinline alloc-tn size)))
264   (values))
265
266 ;;; Allocate an other-pointer object of fixed SIZE with a single word
267 ;;; header having the specified WIDETAG value. The result is placed in
268 ;;; RESULT-TN.
269 (defmacro with-fixed-allocation ((result-tn widetag size &optional inline)
270                                  &body forms)
271   (unless forms
272     (bug "empty &body in WITH-FIXED-ALLOCATION"))
273   (once-only ((result-tn result-tn) (size size))
274     `(pseudo-atomic
275       (allocation ,result-tn (pad-data-block ,size) ,inline)
276       (storew (logior (ash (1- ,size) n-widetag-bits) ,widetag)
277               ,result-tn)
278       (inst lea ,result-tn
279             (make-ea :byte :base ,result-tn :disp other-pointer-lowtag))
280       ,@forms)))
281 \f
282 ;;;; error code
283 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
284   (defun emit-error-break (vop kind code values)
285     (let ((vector (gensym)))
286       `((progn
287           #-darwin (inst int 3)         ; i386 breakpoint instruction
288           ;; CLH 20060314
289           ;; On Darwin, we need to use #x0b0f instead of int3 in order
290           ;; to generate a SIGILL instead of a SIGTRAP as darwin/x86
291           ;; doesn't seem to be reliably firing SIGTRAP
292           ;; handlers. Hopefully this will be fixed by Apple at a
293           ;; later date.
294           #+darwin (inst word #x0b0f))
295         ;; The return PC points here; note the location for the debugger.
296         (let ((vop ,vop))
297           (when vop
298                 (note-this-location vop :internal-error)))
299         (inst byte ,kind)                       ; eg trap_Xyyy
300         (with-adjustable-vector (,vector)       ; interr arguments
301           (write-var-integer (error-number-or-lose ',code) ,vector)
302           ,@(mapcar (lambda (tn)
303                       `(let ((tn ,tn))
304                          ;; classic CMU CL comment:
305                          ;;   zzzzz jrd here. tn-offset is zero for constant
306                          ;;   tns.
307                          (write-var-integer (make-sc-offset (sc-number
308                                                              (tn-sc tn))
309                                                             (or (tn-offset tn)
310                                                                 0))
311                                             ,vector)))
312                     values)
313           (inst byte (length ,vector))
314           (dotimes (i (length ,vector))
315             (inst byte (aref ,vector i))))))))
316
317 (defmacro error-call (vop error-code &rest values)
318   #!+sb-doc
319   "Cause an error. ERROR-CODE is the error to cause."
320   (cons 'progn
321         (emit-error-break vop error-trap error-code values)))
322
323 (defmacro generate-error-code (vop error-code &rest values)
324   #!+sb-doc
325   "Generate-Error-Code Error-code Value*
326   Emit code for an error with the specified Error-Code and context Values."
327   `(assemble (*elsewhere*)
328      (let ((start-lab (gen-label)))
329        (emit-label start-lab)
330        (error-call ,vop ,error-code ,@values)
331        start-lab)))
332
333 \f
334 ;;;; PSEUDO-ATOMIC
335
336 ;;; This is used to wrap operations which leave untagged memory lying
337 ;;; around.  It's an operation which the AOP weenies would describe as
338 ;;; having "cross-cutting concerns", meaning it appears all over the
339 ;;; place and there's no logical single place to attach documentation.
340 ;;; grep (mostly in src/runtime) is your friend
341
342 ;;; KLUDGE: since the stack on the x86 is treated conservatively, it
343 ;;; does not matter whether a signal occurs during construction of a
344 ;;; dynamic-extent object, as the half-finished construction of the
345 ;;; object will not cause any difficulty.  We can therefore elide
346 (defmacro maybe-pseudo-atomic (really-p &body forms)
347   `(if ,really-p
348        (progn ,@forms)
349        (pseudo-atomic ,@forms)))
350
351 #!+sb-thread
352 (defmacro pseudo-atomic (&rest forms)
353   (with-unique-names (label)
354     `(let ((,label (gen-label)))
355        (inst fs-segment-prefix)
356        (inst or (make-ea :byte :disp (* 4 thread-pseudo-atomic-bits-slot))
357             (fixnumize 1))
358        ,@forms
359        (inst fs-segment-prefix)
360        (inst xor (make-ea :byte :disp (* 4 thread-pseudo-atomic-bits-slot))
361              (fixnumize 1))
362        (inst jmp :z ,label)
363        ;; if PAI was set, interrupts were disabled at the same
364        ;; time using the process signal mask.
365        (inst break pending-interrupt-trap)
366        (emit-label ,label))))
367
368 #!-sb-thread
369 (defmacro pseudo-atomic (&rest forms)
370   (with-unique-names (label)
371     `(let ((,label (gen-label)))
372        ;; FIXME: The MAKE-EA noise should become a MACROLET macro
373        ;; or something. (perhaps SVLB, for static variable low
374        ;; byte)
375        (inst or (make-ea :byte :disp (+ nil-value
376                                         (static-symbol-offset
377                                          '*pseudo-atomic-bits*)
378                                         (ash symbol-value-slot word-shift)
379                                         (- other-pointer-lowtag)))
380              (fixnumize 1))
381        ,@forms
382        (inst xor (make-ea :byte :disp (+ nil-value
383                                          (static-symbol-offset
384                                           '*pseudo-atomic-bits*)
385                                          (ash symbol-value-slot word-shift)
386                                          (- other-pointer-lowtag)))
387              (fixnumize 1))
388        (inst jmp :z ,label)
389        ;; if PAI was set, interrupts were disabled at the same
390        ;; time using the process signal mask.
391        (inst break pending-interrupt-trap)
392        (emit-label ,label))))
393 \f
394 ;;;; indexed references
395
396 (defmacro define-full-reffer (name type offset lowtag scs el-type &optional translate)
397   `(progn
398      (define-vop (,name)
399        ,@(when translate
400            `((:translate ,translate)))
401        (:policy :fast-safe)
402        (:args (object :scs (descriptor-reg))
403               (index :scs (any-reg immediate unsigned-reg)))
404        (:arg-types ,type tagged-num)
405        (:results (value :scs ,scs))
406        (:result-types ,el-type)
407        (:generator 3                    ; pw was 5
408          (sc-case index
409            (immediate
410             (inst mov value (make-ea :dword :base object
411                                      :disp (- (* (+ ,offset (tn-value index))
412                                                  n-word-bytes)
413                                               ,lowtag))))
414            (unsigned-reg
415             (inst mov value (make-ea :dword :base object :index index :scale 4
416                                      :disp (- (* ,offset n-word-bytes)
417                                               ,lowtag))))
418            (t
419             (inst mov value (make-ea :dword :base object :index index
420                                      :disp (- (* ,offset n-word-bytes)
421                                               ,lowtag)))))))))
422
423 (defmacro define-full-reffer+offset (name type offset lowtag scs el-type &optional translate)
424   `(progn
425      (define-vop (,name)
426        ,@(when translate
427            `((:translate ,translate)))
428        (:policy :fast-safe)
429        (:args (object :scs (descriptor-reg))
430               (index :scs (any-reg immediate unsigned-reg)))
431        (:arg-types ,type tagged-num
432                    (:constant (constant-displacement ,lowtag sb!vm:n-word-bytes ,offset)))
433        (:info offset)
434        (:results (value :scs ,scs))
435        (:result-types ,el-type)
436        (:generator 3                    ; pw was 5
437          (sc-case index
438            (immediate
439             (inst mov value (make-ea :dword :base object
440                                      :disp (- (* (+ ,offset
441                                                     (tn-value index)
442                                                     offset)
443                                                  n-word-bytes)
444                                               ,lowtag))))
445            (unsigned-reg
446             (inst mov value (make-ea :dword :base object :index index :scale 4
447                                      :disp (- (* (+ ,offset offset)
448                                                  n-word-bytes)
449                                               ,lowtag))))
450            (t
451             (inst mov value (make-ea :dword :base object :index index
452                                      :disp (- (* (+ ,offset offset)
453                                                  n-word-bytes)
454                                               ,lowtag)))))))))
455
456 (defmacro define-full-setter (name type offset lowtag scs el-type &optional translate)
457   `(progn
458      (define-vop (,name)
459        ,@(when translate
460            `((:translate ,translate)))
461        (:policy :fast-safe)
462        (:args (object :scs (descriptor-reg))
463               (index :scs (any-reg immediate))
464               (value :scs ,scs :target result))
465        (:arg-types ,type tagged-num ,el-type)
466        (:results (result :scs ,scs))
467        (:result-types ,el-type)
468        (:generator 4                    ; was 5
469          (sc-case index
470            (immediate
471             (inst mov (make-ea :dword :base object
472                                :disp (- (* (+ ,offset (tn-value index))
473                                            n-word-bytes)
474                                         ,lowtag))
475                   value))
476            (t
477             (inst mov (make-ea :dword :base object :index index
478                                :disp (- (* ,offset n-word-bytes) ,lowtag))
479                   value)))
480         (move result value)))))
481
482 (defmacro define-full-setter+offset (name type offset lowtag scs el-type &optional translate)
483   `(progn
484      (define-vop (,name)
485        ,@(when translate
486            `((:translate ,translate)))
487        (:policy :fast-safe)
488        (:args (object :scs (descriptor-reg))
489               (index :scs (any-reg immediate))
490               (value :scs ,scs :target result))
491        (:info offset)
492        (:arg-types ,type tagged-num
493                    (:constant (constant-displacement ,lowtag sb!vm:n-word-bytes ,offset)) ,el-type)
494        (:results (result :scs ,scs))
495        (:result-types ,el-type)
496        (:generator 4                    ; was 5
497          (sc-case index
498            (immediate
499             (inst mov (make-ea :dword :base object
500                                :disp (- (* (+ ,offset (tn-value index) offset)
501                                            n-word-bytes)
502                                         ,lowtag))
503                   value))
504            (t
505             (inst mov (make-ea :dword :base object :index index
506                                :disp (- (* (+ ,offset offset)
507                                            n-word-bytes) ,lowtag))
508                   value)))
509         (move result value)))))
510
511 ;;; helper for alien stuff.
512 (def!macro with-pinned-objects ((&rest objects) &body body)
513   "Arrange with the garbage collector that the pages occupied by
514 OBJECTS will not be moved in memory for the duration of BODY.
515 Useful for e.g. foreign calls where another thread may trigger
516 garbage collection"
517   `(multiple-value-prog1
518        (progn
519          ,@(loop for p in objects
520                  collect
521                  ;; There is no race here wrt to gc, because at every
522                  ;; point during the execution there is a reference to
523                  ;; P on the stack or in a register.
524                  `(push-word-on-c-stack
525                    (int-sap (sb!kernel:get-lisp-obj-address ,p))))
526          ,@body)
527      ;; If the body returned normally, we should restore the stack pointer
528      ;; for the benefit of any following code in the same function.  If
529      ;; there's a non-local exit in the body, sp is garbage anyway and
530      ;; will get set appropriately from {a, the} frame pointer before it's
531      ;; next needed
532      (pop-words-from-c-stack ,(length objects))))