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