0.9.5.36: nop
[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-type (target source &optional (offset 0))
112   #!+sb-doc
113   "Loads the type bits of a pointer into target independent of
114    byte-ordering issues."
115   (once-only ((n-target target)
116               (n-source source)
117               (n-offset offset))
118     (ecase *backend-byte-order*
119       (:little-endian
120        `(inst mov ,n-target
121               (make-ea :byte :base ,n-source :disp ,n-offset)))
122       (:big-endian
123        `(inst mov ,n-target
124               (make-ea :byte :base ,n-source :disp (+ ,n-offset 3)))))))
125 \f
126 ;;;; allocation helpers
127
128 ;;; All allocation is done by calls to assembler routines that
129 ;;; eventually invoke the C alloc() function.  Once upon a time
130 ;;; (before threads) allocation within an alloc_region could also be
131 ;;; done inline, with the aid of two C symbols storing the current
132 ;;; allocation region boundaries; however, C symbols are global.
133
134 ;;; C calls for allocation don't /seem/ to make an awful lot of
135 ;;; difference to speed.  Guessing from historical context, it looks
136 ;;; like inline allocation was introduced before pseudo-atomic, at
137 ;;; which time all calls to alloc() would have needed a syscall to
138 ;;; mask signals for the duration.  Now we have pseudoatomic there's
139 ;;; no need for that overhead.  Still, inline alloc would be a neat
140 ;;; addition someday (except see below).
141
142 (defun allocation-dynamic-extent (alloc-tn size)
143   (inst sub esp-tn size)
144   ;; FIXME: SIZE _should_ be double-word aligned (suggested but
145   ;; unfortunately not enforced by PAD-DATA-BLOCK and
146   ;; WITH-FIXED-ALLOCATION), so that ESP is always divisible by 8 (for
147   ;; 32-bit lispobjs).  In that case, this AND instruction is
148   ;; unneccessary and could be removed.  If not, explain why.  -- CSR,
149   ;; 2004-03-30
150   (inst and esp-tn #.(ldb (byte 32 0) (lognot lowtag-mask)))
151   (aver (not (location= alloc-tn esp-tn)))
152   (inst mov alloc-tn esp-tn)
153   (values))
154
155 (defun allocation-notinline (alloc-tn size)
156   (let* ((alloc-tn-offset (tn-offset alloc-tn))
157          ;; C call to allocate via dispatch routines. Each
158          ;; destination has a special entry point. The size may be a
159          ;; register or a constant.
160          (tn-text (ecase alloc-tn-offset
161                     (#.eax-offset "eax")
162                     (#.ecx-offset "ecx")
163                     (#.edx-offset "edx")
164                     (#.ebx-offset "ebx")
165                     (#.esi-offset "esi")
166                     (#.edi-offset "edi")))
167          (size-text (case size (8 "8_") (16 "16_") (t ""))))
168     (unless (or (eql size 8) (eql size 16))
169       (unless (and (tn-p size) (location= alloc-tn size))
170         (inst mov alloc-tn size)))
171     (inst call (make-fixup (concatenate 'string
172                                          "alloc_" size-text
173                                          "to_" tn-text)
174                            :foreign))))
175
176 (defun allocation-inline (alloc-tn size)
177   (let ((ok (gen-label))
178         (free-pointer
179          (make-ea :dword :disp
180                   #!+sb-thread (* n-word-bytes thread-alloc-region-slot)
181                   #!-sb-thread (make-fixup "boxed_region" :foreign)
182                   :scale 1)) ; thread->alloc_region.free_pointer
183         (end-addr
184          (make-ea :dword :disp
185                   #!+sb-thread (* n-word-bytes (1+ thread-alloc-region-slot))
186                   #!-sb-thread (make-fixup "boxed_region" :foreign 4)
187                   :scale 1)))   ; thread->alloc_region.end_addr
188     (unless (and (tn-p size) (location= alloc-tn size))
189       (inst mov alloc-tn size))
190     #!+sb-thread (inst fs-segment-prefix)
191     (inst add alloc-tn free-pointer)
192     #!+sb-thread (inst fs-segment-prefix)
193     (inst cmp alloc-tn end-addr)
194     (inst jmp :be OK)
195     (let ((dst (ecase (tn-offset alloc-tn)
196                  (#.eax-offset "alloc_overflow_eax")
197                  (#.ecx-offset "alloc_overflow_ecx")
198                  (#.edx-offset "alloc_overflow_edx")
199                  (#.ebx-offset "alloc_overflow_ebx")
200                  (#.esi-offset "alloc_overflow_esi")
201                  (#.edi-offset "alloc_overflow_edi"))))
202       (inst call (make-fixup dst :foreign)))
203     (emit-label ok)
204     #!+sb-thread (inst fs-segment-prefix)
205     (inst xchg free-pointer alloc-tn))
206   (values))
207
208
209 ;;; Emit code to allocate an object with a size in bytes given by
210 ;;; SIZE.  The size may be an integer or a TN. If Inline is a VOP
211 ;;; node-var then it is used to make an appropriate speed vs size
212 ;;; decision.
213
214 ;;; Allocation should only be used inside a pseudo-atomic section, which
215 ;;; should also cover subsequent initialization of the object.
216
217 ;;; (FIXME: so why aren't we asserting this?)
218
219 (defun allocation (alloc-tn size &optional inline dynamic-extent)
220   (cond
221     (dynamic-extent (allocation-dynamic-extent alloc-tn size))
222     ;; FIXME: for reasons unknown, inline allocation is a speed win on
223     ;; non-P4s, and a speed loss on P4s (and probably other such
224     ;; high-spec high-cache machines).  :INLINE-ALLOCATION-IS-GOOD is
225     ;; a bit of a KLUDGE, really.  -- CSR, 2004-08-05 (following
226     ;; observations made by ASF and Juho Snellman)
227     ((and (member :inline-allocation-is-good *backend-subfeatures*)
228           (or (null inline) (policy inline (>= speed space))))
229      (allocation-inline alloc-tn size))
230     (t (allocation-notinline alloc-tn size)))
231   (values))
232
233 ;;; Allocate an other-pointer object of fixed SIZE with a single word
234 ;;; header having the specified WIDETAG value. The result is placed in
235 ;;; RESULT-TN.
236 (defmacro with-fixed-allocation ((result-tn widetag size &optional inline)
237                                  &body forms)
238   (unless forms
239     (bug "empty &body in WITH-FIXED-ALLOCATION"))
240   (once-only ((result-tn result-tn) (size size))
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 (defmacro maybe-pseudo-atomic (really-p &body forms)
311   `(if ,really-p
312        (progn ,@forms)
313        (pseudo-atomic ,@forms)))
314
315 #!+sb-thread
316 (defmacro pseudo-atomic (&rest forms)
317   (with-unique-names (label)
318     `(let ((,label (gen-label)))
319        (inst fs-segment-prefix)
320        (inst mov (make-ea :byte
321                           :disp (* 4 thread-pseudo-atomic-interrupted-slot)) 0)
322        (inst fs-segment-prefix)
323        (inst mov (make-ea :byte :disp (* 4 thread-pseudo-atomic-atomic-slot))
324             (fixnumize 1))
325        ,@forms
326        (inst fs-segment-prefix)
327        (inst mov (make-ea :byte :disp (* 4 thread-pseudo-atomic-atomic-slot)) 0)
328        (inst fs-segment-prefix)
329        (inst cmp (make-ea :byte
330                           :disp (* 4 thread-pseudo-atomic-interrupted-slot)) 0)
331        (inst jmp :eq ,label)
332        ;; if PAI was set, interrupts were disabled at the same
333        ;; time using the process signal mask.
334        (inst break pending-interrupt-trap)
335        (emit-label ,label))))
336
337 #!-sb-thread
338 (defmacro pseudo-atomic (&rest forms)
339   (with-unique-names (label)
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
459                  ;; There is no race here wrt to gc, because at every
460                  ;; point during the execution there is a reference to
461                  ;; P on the stack or in a register.
462                  `(push-word-on-c-stack
463                    (int-sap (sb!kernel:get-lisp-obj-address ,p))))
464          ,@body)
465      ;; If the body returned normally, we should restore the stack pointer
466      ;; for the benefit of any following code in the same function.  If
467      ;; there's a non-local exit in the body, sp is garbage anyway and
468      ;; will get set appropriately from {a, the} frame pointer before it's
469      ;; next needed
470      (pop-words-from-c-stack ,(length objects))))