9d6ce4a1161103c5a1e81cd5805d4a7e01ac9ba7
[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-reffer (name type offset lowtag scs el-type &optional translate)
393   `(progn
394      (define-vop (,name)
395        ,@(when translate
396            `((:translate ,translate)))
397        (:policy :fast-safe)
398        (:args (object :scs (descriptor-reg))
399               (index :scs (any-reg immediate unsigned-reg)))
400        (:arg-types ,type tagged-num)
401        (:results (value :scs ,scs))
402        (:result-types ,el-type)
403        (:generator 3                    ; pw was 5
404          (sc-case index
405            (immediate
406             (inst mov value (make-ea :dword :base object
407                                      :disp (- (* (+ ,offset (tn-value index))
408                                                  n-word-bytes)
409                                               ,lowtag))))
410            (unsigned-reg
411             (inst mov value (make-ea :dword :base object :index index :scale 4
412                                      :disp (- (* ,offset n-word-bytes)
413                                               ,lowtag))))
414            (t
415             (inst mov value (make-ea :dword :base object :index index
416                                      :disp (- (* ,offset n-word-bytes)
417                                               ,lowtag)))))))))
418
419 (defmacro define-full-reffer+offset (name type offset lowtag scs el-type &optional translate)
420   `(progn
421      (define-vop (,name)
422        ,@(when translate
423            `((:translate ,translate)))
424        (:policy :fast-safe)
425        (:args (object :scs (descriptor-reg))
426               (index :scs (any-reg immediate unsigned-reg)))
427        (:arg-types ,type tagged-num
428                    (:constant (constant-displacement ,lowtag sb!vm:n-word-bytes ,offset)))
429        (:info offset)
430        (:results (value :scs ,scs))
431        (:result-types ,el-type)
432        (:generator 3                    ; pw was 5
433          (sc-case index
434            (immediate
435             (inst mov value (make-ea :dword :base object
436                                      :disp (- (* (+ ,offset
437                                                     (tn-value index)
438                                                     offset)
439                                                  n-word-bytes)
440                                               ,lowtag))))
441            (unsigned-reg
442             (inst mov value (make-ea :dword :base object :index index :scale 4
443                                      :disp (- (* (+ ,offset offset)
444                                                  n-word-bytes)
445                                               ,lowtag))))
446            (t
447             (inst mov value (make-ea :dword :base object :index index
448                                      :disp (- (* (+ ,offset offset)
449                                                  n-word-bytes)
450                                               ,lowtag)))))))))
451
452 (defmacro define-full-setter (name type offset lowtag scs el-type &optional translate)
453   `(progn
454      (define-vop (,name)
455        ,@(when translate
456            `((:translate ,translate)))
457        (:policy :fast-safe)
458        (:args (object :scs (descriptor-reg))
459               (index :scs (any-reg immediate))
460               (value :scs ,scs :target result))
461        (:arg-types ,type tagged-num ,el-type)
462        (:results (result :scs ,scs))
463        (:result-types ,el-type)
464        (:generator 4                    ; was 5
465          (sc-case index
466            (immediate
467             (inst mov (make-ea :dword :base object
468                                :disp (- (* (+ ,offset (tn-value index))
469                                            n-word-bytes)
470                                         ,lowtag))
471                   value))
472            (t
473             (inst mov (make-ea :dword :base object :index index
474                                :disp (- (* ,offset n-word-bytes) ,lowtag))
475                   value)))
476         (move result value)))))
477
478 (defmacro define-full-setter+offset (name type offset lowtag scs el-type &optional translate)
479   `(progn
480      (define-vop (,name)
481        ,@(when translate
482            `((:translate ,translate)))
483        (:policy :fast-safe)
484        (:args (object :scs (descriptor-reg))
485               (index :scs (any-reg immediate))
486               (value :scs ,scs :target result))
487        (:info offset)
488        (:arg-types ,type tagged-num
489                    (:constant (constant-displacement ,lowtag sb!vm:n-word-bytes ,offset)) ,el-type)
490        (:results (result :scs ,scs))
491        (:result-types ,el-type)
492        (:generator 4                    ; was 5
493          (sc-case index
494            (immediate
495             (inst mov (make-ea :dword :base object
496                                :disp (- (* (+ ,offset (tn-value index) offset)
497                                            n-word-bytes)
498                                         ,lowtag))
499                   value))
500            (t
501             (inst mov (make-ea :dword :base object :index index
502                                :disp (- (* (+ ,offset offset)
503                                            n-word-bytes) ,lowtag))
504                   value)))
505         (move result value)))))
506
507 ;;; helper for alien stuff.
508 (def!macro with-pinned-objects ((&rest objects) &body body)
509   "Arrange with the garbage collector that the pages occupied by
510 OBJECTS will not be moved in memory for the duration of BODY.
511 Useful for e.g. foreign calls where another thread may trigger
512 garbage collection"
513   `(multiple-value-prog1
514        (progn
515          ,@(loop for p in objects
516                  collect
517                  ;; There is no race here wrt to gc, because at every
518                  ;; point during the execution there is a reference to
519                  ;; P on the stack or in a register.
520                  `(push-word-on-c-stack
521                    (int-sap (sb!kernel:get-lisp-obj-address ,p))))
522          ,@body)
523      ;; If the body returned normally, we should restore the stack pointer
524      ;; for the benefit of any following code in the same function.  If
525      ;; there's a non-local exit in the body, sp is garbage anyway and
526      ;; will get set appropriately from {a, the} frame pointer before it's
527      ;; next needed
528      (pop-words-from-c-stack ,(length objects))))