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