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