[project @ 1998-08-24 10:47:52 by sof]
[ghc-hetmet.git] / ghc / includes / StgMacros.lh
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1994
3 %
4 \section[StgMacros]{C macros used in GHC-generated \tr{.hc} files}
5
6 \begin{code}
7 #ifndef STGMACROS_H
8 #define STGMACROS_H
9 \end{code}
10
11 %************************************************************************
12 %*                                                                      *
13 \subsection[StgMacros-abbrev]{Abbreviatory(?) and general macros}
14 %*                                                                      *
15 %************************************************************************
16
17 Mere abbreviations:
18 \begin{code}
19 /* for function declarations */
20 #define STGFUN(f)  F_ f(STG_NO_ARGS)
21 #define STATICFUN(f) static F_ f(STG_NO_ARGS)
22
23 /* for functions/data that are really external to this module */
24 #define EXTFUN(f)       extern F_ f(STG_NO_ARGS)
25 #define EXTDATA(d)      extern W_ d[]
26 #define EXTDATA_RO(d)   extern const W_ d[] /* read-only */
27
28 /* for fwd decls to functions/data somewhere else in this module */
29 /* (identical for the mo') */
30 #define INTFUN(f)       static F_ f(STG_NO_ARGS)
31 #define INTDATA(d)      extern W_ d[]
32 #define INTDATA_RO(d)   extern const W_ d[] /* read-only */
33
34 /* short forms of most of the above */
35
36 #define FN_(f)          F_ f(STG_NO_ARGS)
37 #define IFN_(f)         static F_ f(STG_NO_ARGS)
38 #define EF_(f)          extern F_ f(STG_NO_ARGS)
39 #define ED_(d)          extern W_ d[]
40 #define ED_RO_(d)       extern const W_ d[] /* read-only */
41 #define IF_(f)          static F_ f(STG_NO_ARGS)
42
43 /* GCC is uncooperative about the next one: */
44 /* But, the "extern" prevents initialisation... ADR */
45 #if defined(__GNUC__)
46 #define ID_(d)          extern W_ d[]
47 #define ID_RO_(d)       extern const W_ d[] /* read-only */
48 #else
49 #define ID_(d)          static W_ d[]
50 #define ID_RO_(d)       static const W_ d[] /* read-only */
51 #endif /* not GCC */
52 \end{code}
53
54 General things; note: general-but-``machine-dependent'' macros are
55 given in \tr{StgMachDeps.lh}.
56 \begin{code}
57 I_ STG_MAX PROTO((I_, I_)); /* GCC -Wall loves prototypes */
58
59 extern STG_INLINE
60 I_
61 STG_MAX(I_ a, I_ b) { return((a >= b) ? a : b); }
62 /* NB: the naive #define macro version of STG_MAX
63    can lead to exponential CPP explosion, if you
64    have very-nested STG_MAXes.
65 */
66
67 /*
68 Macros to combine two short words into a single
69 word and split such a word back into two.
70
71 Dependent on machine word size :-)
72 */
73
74 #define COMBINE_WORDS(word,short1,short2)               \
75         do {                                            \
76             ((packed_shorts *)&(word))->wu.s1 = short1; \
77             ((packed_shorts *)&(word))->wu.s2 = short2; \
78         } while(0)
79
80 #define SPLIT_WORD(word,short1,short2)                  \
81         do {                                            \
82             short1 = ((packed_shorts *)&(word))->wu.s1; \
83             short2 = ((packed_shorts *)&(word))->wu.s2; \
84         } while(0)
85
86 \end{code}
87
88 %************************************************************************
89 %*                                                                      *
90 \subsection[StgMacros-gen-stg]{General STGish macros}
91 %*                                                                      *
92 %************************************************************************
93
94 Common sizes of vector-return tables.
95
96 Claim: don't need fwd decls for return pts in \tr{VECTBL*}, because
97 the AbsC flattener ensures that things come out sufficiently
98 ``backwards''.
99
100 \begin{code}
101 #ifdef __STG_REV_TBLS__
102 #define UNVECTBL(staticp,label,a)   /* nothing */
103 #else
104 #define UNVECTBL(staticp,label,a) \
105 EXTFUN(a); \
106 staticp const W_ label[] = { \
107   (W_) a \
108 };
109 #endif
110 \end{code}
111
112 \begin{code}
113 #if defined(USE_SPLIT_MARKERS)
114 #define __STG_SPLIT_MARKER(n) FN_(CAT2(__stg_split_marker,n)){ }
115 #else
116 #define __STG_SPLIT_MARKER(n) /* nothing */
117 #endif
118 \end{code}
119
120 %************************************************************************
121 %*                                                                      *
122 \subsection[StgMacros-exceptions]{Exception-checking macros}
123 %*                                                                      *
124 %************************************************************************
125
126 Argument-satisfaction check, stack(s) overflow check, heap overflow
127 check.
128
129 The @SUBTRACT(upper, lower)@ macros return a positive result in words
130 indicating the amount by which upper is above lower on the stack.
131
132 \begin{code}
133 #define SUBTRACT_A_STK( upper, lower ) AREL( (lower) - (upper) )
134 #define SUBTRACT_B_STK( upper, lower ) BREL( (lower) - (upper) )
135 \end{code}
136
137 %************************************************************************
138 %*                                                                      *
139 \subsubsection[StgMacros-arg-satis]{Argument-satisfaction checks}
140 %*                                                                      *
141 %************************************************************************
142
143 @ARGS_CHK(n)@ sees of there are @n@ words of args on the A/B stack.
144 If not, it jumps to @UpdatePAP@.
145
146 @ARGS_CHK@ args are pre-directionified.
147 Notice that we do the comparisons in the form (x < a+n), for
148 some constant n.  This generates more efficient code (with GCC at least)
149 than (x-a < n).
150
151 \begin{code}
152 #define ARGS_CHK_A(n)                                           \
153         if (SuA /*SUBTRACT_A_STK( SpA, SuA )*/ < (SpA+(n))) {   \
154                 JMP_( UpdatePAP );                              \
155         }
156
157 #define ARGS_CHK_A_LOAD_NODE(n, closure_addr)                   \
158         if (SuA /*SUBTRACT_A_STK( SpA, SuA )*/ < (SpA+(n))) {   \
159                 Node = (P_) closure_addr;                       \
160                 JMP_( UpdatePAP );                              \
161         }
162
163 #define ARGS_CHK_B(n)                                           \
164         if (SpB /*SUBTRACT_B_STK( SpB, SuB )*/ < (SuB-(n))) {   \
165                 JMP_( UpdatePAP );                              \
166         }
167
168
169 #define ARGS_CHK_B_LOAD_NODE(n, closure_addr)                   \
170         if (SpB /*SUBTRACT_B_STK( SpB, SuB )*/ < (SuB-(n))) {   \
171                 Node = (P_) closure_addr;                       \
172                 JMP_( UpdatePAP );                              \
173         }
174 \end{code}
175
176 %************************************************************************
177 %*                                                                      *
178 \subsubsection[StgMacros-stk-chks]{Stack-overflow check}
179 %*                                                                      *
180 %************************************************************************
181
182 @STK_CHK(a,b)@ [misc args omitted...] checks that we can allocate @a@
183 words of A stack and @b@ words of B stack.  If not, it calls
184 @StackOverflow@ (which dies).
185
186 (It will be different in the parallel case.)
187
188 NB: args @a@ and @b@ are pre-direction-ified!
189 \begin{code}
190 I_ SqueezeUpdateFrames PROTO((P_, P_, P_));
191 int sanityChk_StkO (P_ stko); /* ToDo: move to a sane place */
192
193 #if ! defined(CONCURRENT)
194
195 extern void StackOverflow(STG_NO_ARGS) STG_NORETURN;
196
197 #if STACK_CHECK_BY_PAGE_FAULT
198
199 #define STACK_OVERFLOW(liveness,hda,hdb,spa,spb,rtype,reenter)  \
200     /* use memory protection instead; still need ticky-ness */
201
202 #else
203
204 #define STACK_OVERFLOW(liveness,hda,hdb,spa,spb,rtype,reenter)  \
205     ULTRASAFESTGCALL0(void,(void *),StackOverflow)
206
207 #endif /* not using page-faulting */
208
209 #else /* threaded */
210
211 I_ StackOverflow PROTO((W_, W_));
212
213 /*
214  * On a uniprocessor, we do *NOT* context switch on a stack overflow 
215  * (though we may GC).  Therefore, we never have to reenter node.
216  */
217
218 #define STACK_OVERFLOW(liveness,hda,hdb,spa,spb,rtype,reenter) \
219     DO_STACKOVERFLOW((hda+hdb)<<2|((rtype)<<1)|(reenter),((spa)<<20)|((spb)<<8)|(liveness))
220
221 #define STACK_OVERFLOW_HEADROOM(args,y)     ((args) >> 2)
222 #define STACK_OVERFLOW_PRIM_RETURN(args,y)  ((args) & 2)
223 #define STACK_OVERFLOW_REENTER(args,y)      ((args) & 1)
224
225 #define STACK_OVERFLOW_AWORDS(x,args)       (((args) >> 20) & 0x0fff)
226 #define STACK_OVERFLOW_BWORDS(x,args)       (((args) >> 8) & 0x0fff)
227 #define STACK_OVERFLOW_LIVENESS(x,args)     ((args) & 0xff)
228
229 #endif  /* CONCURRENT */
230
231 #define STK_CHK(liveness_mask,a_headroom,b_headroom,spa,spb,ret_type,reenter)\
232 do {                                                            \
233   DO_ASTK_HWM(); /* ticky-ticky profiling */                    \
234   DO_BSTK_HWM();                                                \
235   if (STKS_OVERFLOW_OP(((a_headroom) + 1), ((b_headroom) + 1))) {       \
236     STACK_OVERFLOW(liveness_mask,a_headroom,b_headroom,spa,spb,ret_type,reenter);\
237   }                                                             \
238 }while(0)
239 \end{code}
240
241 %************************************************************************
242 %*                                                                      *
243 \subsubsection[StgMacros-heap-chks]{Heap-overflow checks}
244 %*                                                                      *
245 %************************************************************************
246
247 Please see the general discussion/commentary about ``what really
248 happens in a GC,'' in \tr{SMinterface.lh}.
249
250 \begin{code}
251 void PerformGC PROTO((W_));
252 void RealPerformGC PROTO((W_ liveness, W_ reqsize, W_  always_reenter_node, rtsBool do_full_collection));
253 void checkInCCallGC(STG_NO_ARGS);
254
255 #ifndef PAR
256 void StgPerformGarbageCollection(STG_NO_ARGS);
257 #endif
258
259 #ifndef CONCURRENT
260
261 #define OR_MSG_PENDING  /* never */
262
263 #define HEAP_OVERFLOW(liveness,n,reenter)       \
264     do {                                        \
265     DO_GC((((W_)n)<<8)|(liveness));             \
266     } while (0)
267
268 #define REQSIZE_BITMASK ((1L << ((BITS_IN(W_) - 8 + 1))) - 1)
269 #define HEAP_OVERFLOW_REQSIZE(args)     (((args) >> 8) & REQSIZE_BITMASK)
270 #define HEAP_OVERFLOW_REENTER(args)     0
271 #define HEAP_OVERFLOW_LIVENESS(args)    ((args) & 0xff)
272
273 #else /* CONCURRENT */
274
275 void ReallyPerformThreadGC PROTO((W_, rtsBool));
276
277 #define HEAP_OVERFLOW(liveness,n,reenter)       \
278     do {                                        \
279     DO_GC((((W_)(n))<<9)|((reenter)<<8)|(liveness)); \
280     } while (0)
281
282 #define REQSIZE_BITMASK ((1L << ((BITS_IN(W_) - 9 + 1))) - 1)
283 #define HEAP_OVERFLOW_REQSIZE(args)     (((args) >> 9) & REQSIZE_BITMASK)
284 #define HEAP_OVERFLOW_REENTER(args)     (((args) >> 8) & 0x1)
285 #define HEAP_OVERFLOW_LIVENESS(args)    ((args) & 0xff)
286
287 #ifndef PAR
288
289 #define OR_MSG_PENDING  /* never */
290
291 #else 
292
293 extern int PacketsWaiting;              /*Probes for incoming messages*/
294 extern int heapChkCounter;              /*Not currently used! We check for messages when*/
295                                         /*a thread is resheduled PWT*/
296 /* #define OR_MSG_PENDING       || (--heapChkCounter == 0 && PacketsWaiting())*/
297 #define OR_MSG_PENDING  /* never */
298
299 #endif  /* PAR */
300 #endif  /* CONCURRENT */
301
302 #if 0 /* alpha_TARGET_ARCH */
303 #define CACHE_LINE  4   /* words */
304 #define LINES_AHEAD 3
305 #define PRE_FETCH(n)                                    \
306 do {                                                    \
307  StgInt j;                                              \
308  j = ((STG_VOLATILE StgInt *) Hp)[LINES_AHEAD * CACHE_LINE];    \
309 } while(0);
310 #define EXTRA_HEAP_WORDS (CACHE_LINE * LINES_AHEAD)
311 #else
312 #define PRE_FETCH(reg)
313 #define EXTRA_HEAP_WORDS 0
314 #endif
315
316 #if defined(GRAN)
317 #define HEAP_CHK(liveness_mask,n,reenter)                       \
318         do {                                                    \
319         /* TICKY_PARANOIA(__FILE__, __LINE__); */               \
320         /* THREAD_CONTEXT_SWITCH(liveness_mask,reenter); */             \
321         ALLOC_HEAP(n); /* ticky profiling */                    \
322         GRAN_ALLOC_HEAP(n,liveness_mask); /* Granularity Simulation */ \
323         if (((Hp = Hp + (n)) > HpLim)) {                        \
324             /* Old:  STGCALL3_GC(PerformGC,liveness_mask,n,StgFalse); */\
325             HEAP_OVERFLOW(liveness_mask,n,StgFalse); \
326         }}while(0)
327
328 #else
329
330 #define HEAP_CHK(liveness_mask,n,reenter)               \
331 do {                                                    \
332   /* TICKY_PARANOIA(__FILE__, __LINE__); */             \
333   PRE_FETCH(n);                                         \
334   ALLOC_HEAP(n); /* ticky profiling */                  \
335   if (((Hp = Hp + (n)) > HpLim) OR_INTERVAL_EXPIRED OR_CONTEXT_SWITCH OR_MSG_PENDING) { \
336     HEAP_OVERFLOW(liveness_mask,n,reenter);             \
337   }                                                     \
338 } while(0)
339
340 #endif  /* GRAN */
341
342 #ifdef CONCURRENT
343
344 #define HEAP_CHK_AND_RESTORE_N(liveness_mask,n,reenter) \
345 do {                                                    \
346   /* TICKY_PARANOIA(__FILE__, __LINE__); */             \
347   PRE_FETCH(n);                                         \
348   ALLOC_HEAP(n); /* ticky profiling */                  \
349   if (((Hp = Hp + (n)) > HpLim) OR_INTERVAL_EXPIRED OR_CONTEXT_SWITCH OR_MSG_PENDING) { \
350     HEAP_OVERFLOW(liveness_mask,n,reenter);             \
351     n = TSO_ARG1(CurrentTSO);                           \
352   }} while(0)
353
354 #else
355
356 #define HEAP_CHK_AND_RESTORE_N(liveness_mask,n,reenter)     \
357     HEAP_CHK(liveness_mask,n,reenter)
358
359 #endif
360
361 \end{code}
362
363
364 %************************************************************************
365 %*                                                                      *
366 \subsection[StgMacros-prim-ops]{Primitive operations}
367 %*                                                                      *
368 %************************************************************************
369
370 One thing to be {\em very careful about} with these macros that assign
371 to results is that the assignment must come {\em last}.  Some of the
372 other arguments may be in terms of addressing modes that get clobbered
373 by the assignment.  (Dirty imperative programming RULES!)
374
375 The order here is roughly that in \tr{compiler/prelude/PrimOps.lhs}.
376
377 %************************************************************************
378 %*                                                                      *
379 \subsubsection[StgMacros-compare-primops]{Primitive comparison ops on basic types}
380 %*                                                                      *
381 %************************************************************************
382
383 We cast the chars in case one of them is a literal (so C things work right
384 even for 8-bit chars).
385 \begin{code}
386 #define gtCharZh(r,a,b) r=(I_)((a)> (b))
387 #define geCharZh(r,a,b) r=(I_)((a)>=(b))
388 #define eqCharZh(r,a,b) r=(I_)((a)==(b))
389 #define neCharZh(r,a,b) r=(I_)((a)!=(b))
390 #define ltCharZh(r,a,b) r=(I_)((a)< (b))
391 #define leCharZh(r,a,b) r=(I_)((a)<=(b))
392
393 /* Int comparisons: >#, >=# etc */
394 #define ZgZh(r,a,b)     r=(I_)((a) >(b))
395 #define ZgZeZh(r,a,b)   r=(I_)((a)>=(b))
396 #define ZeZeZh(r,a,b)   r=(I_)((a)==(b))
397 #define ZdZeZh(r,a,b)   r=(I_)((a)!=(b))
398 #define ZlZh(r,a,b)     r=(I_)((a) <(b))
399 #define ZlZeZh(r,a,b)   r=(I_)((a)<=(b))
400
401 #define gtWordZh(r,a,b) r=(I_)((a) >(b))
402 #define geWordZh(r,a,b) r=(I_)((a)>=(b))
403 #define eqWordZh(r,a,b) r=(I_)((a)==(b))
404 #define neWordZh(r,a,b) r=(I_)((a)!=(b))
405 #define ltWordZh(r,a,b) r=(I_)((a) <(b))
406 #define leWordZh(r,a,b) r=(I_)((a)<=(b))
407
408 #define gtAddrZh(r,a,b) r=(I_)((a) >(b))
409 #define geAddrZh(r,a,b) r=(I_)((a)>=(b))
410 #define eqAddrZh(r,a,b) r=(I_)((a)==(b))
411 #define neAddrZh(r,a,b) r=(I_)((a)!=(b))
412 #define ltAddrZh(r,a,b) r=(I_)((a) <(b))
413 #define leAddrZh(r,a,b) r=(I_)((a)<=(b))
414
415 #define gtFloatZh(r,a,b)  r=(I_)((a)> (b))
416 #define geFloatZh(r,a,b)  r=(I_)((a)>=(b))
417 #define eqFloatZh(r,a,b)  r=(I_)((a)==(b))
418 #define neFloatZh(r,a,b)  r=(I_)((a)!=(b))
419 #define ltFloatZh(r,a,b)  r=(I_)((a)< (b))
420 #define leFloatZh(r,a,b)  r=(I_)((a)<=(b))
421
422 /* Double comparisons: >##, >=#@ etc */
423 #define ZgZhZh(r,a,b)   r=(I_)((a) >(b))
424 #define ZgZeZhZh(r,a,b) r=(I_)((a)>=(b))
425 #define ZeZeZhZh(r,a,b) r=(I_)((a)==(b))
426 #define ZdZeZhZh(r,a,b) r=(I_)((a)!=(b))
427 #define ZlZhZh(r,a,b)   r=(I_)((a) <(b))
428 #define ZlZeZhZh(r,a,b) r=(I_)((a)<=(b))
429 \end{code}
430
431 %************************************************************************
432 %*                                                                      *
433 \subsubsection[StgMacros-char-primops]{Primitive @Char#@ ops (and @LitString#@ish things, too)}
434 %*                                                                      *
435 %************************************************************************
436
437 We cast the chars in case one of them is a literal (so C things work right
438 even for 8-bit chars).
439 \begin{code}
440 #define ordZh(r,a)      r=(I_)((W_) (a))
441 #define chrZh(r,a)      r=(StgChar)((W_)(a))
442 \end{code}
443
444 %************************************************************************
445 %*                                                                      *
446 \subsubsection[StgMacros-int-primops]{Primitive @Int#@ ops}
447 %*                                                                      *
448 %************************************************************************
449
450 \begin{code}
451 I_ stg_div PROTO((I_ a, I_ b));
452
453 #define ZpZh(r,a,b)             r=(a)+(b)
454 #define ZmZh(r,a,b)             r=(a)-(b)
455 #define ZtZh(r,a,b)             r=(a)*(b)
456 #define quotIntZh(r,a,b)        r=(a)/(b)
457 /* ZdZh not used??? --SDM */
458 #define ZdZh(r,a,b)             r=ULTRASAFESTGCALL2(I_,(void *, I_, I_),stg_div,(a),(b))
459 #define remIntZh(r,a,b)         r=(a)%(b)
460 #define negateIntZh(r,a)        r=-(a)
461
462 /* Ever used ? -- SOF */
463 #define absIntZh(a)             r=(( (a) >= 0 ) ? (a) : (-(a)))
464 \end{code}
465
466 %************************************************************************
467 %*                                                                      *
468 \subsubsection[StgMacros-word-primops]{Primitive @Word#@ ops}
469 %*                                                                      *
470 %************************************************************************
471
472 \begin{code}
473 #define quotWordZh(r,a,b)       r=((W_)a)/((W_)b)
474 #define remWordZh(r,a,b)        r=((W_)a)%((W_)b)
475
476 #define andZh(r,a,b)    r=(a)&(b)
477 #define orZh(r,a,b)     r=(a)|(b)
478 #define xorZh(r,a,b)    r=(a)^(b)
479 #define notZh(r,a)      r=~(a)
480
481 #define shiftLZh(r,a,b)   r=(a)<<(b)
482 #define shiftRLZh(r,a,b)  r=(a)>>(b)
483 #define iShiftLZh(r,a,b)  r=(a)<<(b)
484 /* Right shifting of signed quantities is not portable in C, so
485    the behaviour you'll get from using these primops depends
486    on the whatever your C compiler is doing. ToDo: fix. -- sof 8/98
487 */
488 #define iShiftRAZh(r,a,b) r=(a)>>(b)
489 #define iShiftRLZh(r,a,b) r=(a)>>(b)
490
491 #define int2WordZh(r,a) r=(W_)(a)
492 #define word2IntZh(r,a) r=(I_)(a)
493
494 \end{code}
495
496 %************************************************************************
497 %*                                                                      *
498 \subsubsection[StgMacros-addr-primops]{Primitive @Addr#@ ops}
499 %*                                                                      *
500 %************************************************************************
501
502 \begin{code}
503 #define int2AddrZh(r,a) r=(A_)(a)
504 #define addr2IntZh(r,a) r=(I_)(a)
505 \end{code}
506
507 %************************************************************************
508 %*                                                                      *
509 \subsubsection[StgMacros-float-primops]{Primitive @Float#@ ops}
510 %*                                                                      *
511 %************************************************************************
512
513 \begin{code}
514 #define plusFloatZh(r,a,b)      r=(a)+(b)
515 #define minusFloatZh(r,a,b)     r=(a)-(b)
516 #define timesFloatZh(r,a,b)     r=(a)*(b)
517 #define divideFloatZh(r,a,b)    r=(a)/(b)
518 #define negateFloatZh(r,a)      r=-(a)
519
520 #define int2FloatZh(r,a)        r=(StgFloat)(a)
521 #define float2IntZh(r,a)        r=(I_)(a)
522
523 #define expFloatZh(r,a)         r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),exp,a)
524 #define logFloatZh(r,a)         r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),log,a)
525 #define sqrtFloatZh(r,a)        r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),sqrt,a)
526 #define sinFloatZh(r,a)         r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),sin,a)
527 #define cosFloatZh(r,a)         r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),cos,a)
528 #define tanFloatZh(r,a)         r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),tan,a)
529 #define asinFloatZh(r,a)        r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),asin,a)
530 #define acosFloatZh(r,a)        r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),acos,a)
531 #define atanFloatZh(r,a)        r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),atan,a)
532 #define sinhFloatZh(r,a)        r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),sinh,a)
533 #define coshFloatZh(r,a)        r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),cosh,a)
534 #define tanhFloatZh(r,a)        r=(StgFloat) SAFESTGCALL1(StgDouble,(void *, StgDouble),tanh,a)
535 #define powerFloatZh(r,a,b)     r=(StgFloat) SAFESTGCALL2(StgDouble,(void *, StgDouble,StgDouble),pow,a,b)
536
537 /* encoding/decoding given w/ Integer stuff */
538 \end{code}
539
540 %************************************************************************
541 %*                                                                      *
542 \subsubsection[StgMacros-double-primops]{Primitive @Double#@ ops}
543 %*                                                                      *
544 %************************************************************************
545
546 \begin{code}
547 #define ZpZhZh(r,a,b)           r=(a)+(b)
548 #define ZmZhZh(r,a,b)           r=(a)-(b)
549 #define ZtZhZh(r,a,b)           r=(a)*(b)
550 #define ZdZhZh(r,a,b)           r=(a)/(b)
551 #define negateDoubleZh(r,a)     r=-(a)
552
553 #define int2DoubleZh(r,a)       r=(StgDouble)(a)
554 #define double2IntZh(r,a)       r=(I_)(a)
555
556 #define float2DoubleZh(r,a)     r=(StgDouble)(a)
557 #define double2FloatZh(r,a)     r=(StgFloat)(a)
558
559 #define expDoubleZh(r,a)        r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),exp,a)
560 #define logDoubleZh(r,a)        r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),log,a)
561 #define sqrtDoubleZh(r,a)       r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),sqrt,a)
562 #define sinDoubleZh(r,a)        r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),sin,a)
563 #define cosDoubleZh(r,a)        r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),cos,a)
564 #define tanDoubleZh(r,a)        r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),tan,a)
565 #define asinDoubleZh(r,a)       r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),asin,a)
566 #define acosDoubleZh(r,a)       r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),acos,a)
567 #define atanDoubleZh(r,a)       r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),atan,a)
568 #define sinhDoubleZh(r,a)       r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),sinh,a)
569 #define coshDoubleZh(r,a)       r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),cosh,a)
570 #define tanhDoubleZh(r,a)       r=(StgDouble) SAFESTGCALL1(StgDouble,(void *, StgDouble),tanh,a)
571 /* Power: **## */
572 #define ZtZtZhZh(r,a,b) r=(StgDouble) SAFESTGCALL2(StgDouble,(void *, StgDouble,StgDouble),pow,a,b)
573 \end{code}
574
575
576 %************************************************************************
577 %*                                                                      *
578 \subsubsection[StgMacros-64-primops]{Primitive @Int64#@ and @Word64#@ ops}
579 %*                                                                      *
580 %************************************************************************
581
582 Apart from the Integer casting primops, all primops over 64-bit (i.e., long long)
583 @Int64#@ and @Word64#@s are defined out-of-line. We just give the prototype
584 of these primops here:
585
586 \begin{code}
587 #ifdef HAVE_LONG_LONG
588 I_ stg_gtWord64 PROTO((StgWord64, StgWord64));
589 I_ stg_geWord64 PROTO((StgWord64, StgWord64));
590 I_ stg_eqWord64 PROTO((StgWord64, StgWord64));
591 I_ stg_neWord64 PROTO((StgWord64, StgWord64));
592 I_ stg_ltWord64 PROTO((StgWord64, StgWord64));
593 I_ stg_leWord64 PROTO((StgWord64, StgWord64));
594
595 I_ stg_gtInt64 PROTO((StgInt64, StgInt64));
596 I_ stg_geInt64 PROTO((StgInt64, StgInt64));
597 I_ stg_eqInt64 PROTO((StgInt64, StgInt64));
598 I_ stg_neInt64 PROTO((StgInt64, StgInt64));
599 I_ stg_ltInt64 PROTO((StgInt64, StgInt64));
600 I_ stg_leInt64 PROTO((StgInt64, StgInt64));
601
602 LW_ stg_remWord64 PROTO((StgWord64, StgWord64));
603 LW_ stg_quotWord64 PROTO((StgWord64, StgWord64));
604
605 LI_ stg_remInt64 PROTO((StgInt64, StgInt64));
606 LI_ stg_quotInt64 PROTO((StgInt64, StgInt64));
607 LI_ stg_negateInt64 PROTO((StgInt64));
608 LI_ stg_plusInt64 PROTO((StgInt64, StgInt64));
609 LI_ stg_minusInt64 PROTO((StgInt64, StgInt64));
610 LI_ stg_timesInt64 PROTO((StgInt64, StgInt64));
611
612 LW_ stg_and64 PROTO((StgWord64, StgWord64));
613 LW_ stg_or64 PROTO((StgWord64, StgWord64));
614 LW_ stg_xor64 PROTO((StgWord64, StgWord64));
615 LW_ stg_not64 PROTO((StgWord64));
616
617 LW_ stg_shiftL64 PROTO((StgWord64, StgInt));
618 LW_ stg_shiftRL64 PROTO((StgWord64, StgInt));
619 LI_ stg_iShiftL64 PROTO((StgInt64, StgInt));
620 LI_ stg_iShiftRL64 PROTO((StgInt64, StgInt));
621 LI_ stg_iShiftRA64 PROTO((StgInt64, StgInt));
622
623 LI_ stg_intToInt64 PROTO((StgInt));
624 I_ stg_int64ToInt PROTO((StgInt64));
625 LW_ stg_int64ToWord64 PROTO((StgInt64));
626
627 LW_ stg_wordToWord64 PROTO((StgWord));
628 W_ stg_word64ToWord PROTO((StgWord64));
629 LI_ stg_word64ToInt64 PROTO((StgWord64));
630 #endif
631 \end{code}
632
633
634 %************************************************************************
635 %*                                                                      *
636 \subsubsection[StgMacros-integer-primops]{Primitive @Integer@-related ops (GMP stuff)}
637 %*                                                                      *
638 %************************************************************************
639
640 Dirty macros we use for the real business.
641
642 INVARIANT: When one of these macros is called, the only live data is
643 tidily on the STG stacks or in the STG registers (the code generator
644 ensures this).  If there are any pointer-arguments, they will be in
645 the first \tr{Ret*} registers (e.g., \tr{da} arg of \tr{gmpTake1Return1}).
646
647 OK, here are the real macros:
648 \begin{code}
649 #define gmpTake1Return1(size_chk_macro, liveness, mpz_op, ar,sr,dr, aa,sa,da)   \
650 { MP_INT arg;                                                                   \
651   MP_INT result;                                                                \
652   I_ space = size_chk_macro(sa);                                                \
653                                                                                 \
654   /* Check that there will be enough heap & make Hp visible to GMP allocator */ \
655   GMP_HEAP_LOOKAHEAD(liveness,space);                                           \
656                                                                                 \
657   /* Now we can initialise (post possible GC) */                                \
658   arg.alloc     = (aa);                                                         \
659   arg.size      = (sa);                                                         \
660   arg.d         = (unsigned long int *) (BYTE_ARR_CTS(da));                     \
661                                                                                 \
662   SAFESTGCALL1(void,(void *, MP_INT *),mpz_init,&result);                       \
663                                                                                 \
664   /* Perform the operation */                                                   \
665   SAFESTGCALL2(void,(void *, MP_INT *, MP_INT *),mpz_op,&result,&arg);          \
666                                                                                 \
667   GMP_HEAP_HANDBACK();          /* restore Hp */                                \
668   (ar) = result.alloc;                                                          \
669   (sr) = result.size;                                                           \
670   (dr) = (B_) (result.d - DATA_HS);                                             \
671   /* pt to *beginning* of object (GMP has been monkeying around in the middle) */ \
672 }
673
674
675 #define gmpTake2Return1(size_chk_macro, liveness, mpz_op, ar,sr,dr, a1,s1,d1, a2,s2,d2)\
676 { MP_INT arg1;                                                                  \
677   MP_INT arg2;                                                                  \
678   MP_INT result;                                                                \
679   I_ space = size_chk_macro(s1,s2);                                             \
680                                                                                 \
681   /* Check that there will be enough heap & make Hp visible to GMP allocator */ \
682   GMP_HEAP_LOOKAHEAD(liveness,space);                                           \
683                                                                                 \
684   /* Now we can initialise (post possible GC) */                                \
685   arg1.alloc    = (a1);                                                         \
686   arg1.size     = (s1);                                                         \
687   arg1.d        = (unsigned long int *) (BYTE_ARR_CTS(d1));                     \
688   arg2.alloc    = (a2);                                                         \
689   arg2.size     = (s2);                                                         \
690   arg2.d        = (unsigned long int *) (BYTE_ARR_CTS(d2));                     \
691                                                                                 \
692   SAFESTGCALL1(void,(void *, MP_INT *),mpz_init,&result);                       \
693                                                                                 \
694   /* Perform the operation */                                                   \
695   SAFESTGCALL3(void,(void *, MP_INT *, MP_INT *, MP_INT *),mpz_op,&result,&arg1,&arg2); \
696                                                                                 \
697   GMP_HEAP_HANDBACK();          /* restore Hp */                                \
698   (ar) = result.alloc;                                                          \
699   (sr) = result.size;                                                           \
700   (dr) = (B_) (result.d - DATA_HS);                                             \
701   /* pt to *beginning* of object (GMP has been monkeying around in the middle) */ \
702 }
703
704 #define gmpTake2Return2(size_chk_macro, liveness, mpz_op, ar1,sr1,dr1, ar2,sr2,dr2, a1,s1,d1, a2,s2,d2) \
705 { MP_INT arg1;                                                                  \
706   MP_INT arg2;                                                                  \
707   MP_INT result1;                                                               \
708   MP_INT result2;                                                               \
709   I_ space = size_chk_macro(s1,s2);                                             \
710                                                                                 \
711   /* Check that there will be enough heap & make Hp visible to GMP allocator */ \
712   GMP_HEAP_LOOKAHEAD(liveness,space);                                           \
713                                                                                 \
714   /* Now we can initialise (post possible GC) */                                \
715   arg1.alloc    = (a1);                                                         \
716   arg1.size     = (s1);                                                         \
717   arg1.d        = (unsigned long int *) (BYTE_ARR_CTS(d1));                     \
718   arg2.alloc    = (a2);                                                         \
719   arg2.size     = (s2);                                                         \
720   arg2.d        = (unsigned long int *) (BYTE_ARR_CTS(d2));                     \
721                                                                                 \
722   SAFESTGCALL1(void,(void *, MP_INT *),mpz_init,&result1);                      \
723   SAFESTGCALL1(void,(void *, MP_INT *),mpz_init,&result2);                      \
724                                                                                 \
725   /* Perform the operation */                                                   \
726   SAFESTGCALL4(void,(void *, MP_INT *, MP_INT *, MP_INT *, MP_INT *),mpz_op,&result1,&result2,&arg1,&arg2); \
727                                                                                 \
728   GMP_HEAP_HANDBACK();          /* restore Hp */                                \
729   (ar1) = result1.alloc;                                                        \
730   (sr1) = result1.size;                                                         \
731   (dr1) = (B_) (result1.d - DATA_HS);                                           \
732   (ar2) = result2.alloc;                                                        \
733   (sr2) = result2.size;                                                         \
734   (dr2) = (B_) (result2.d - DATA_HS);                                           \
735 }
736 \end{code}
737
738 Some handy size-munging macros: sometimes gratuitously {\em conservative}.
739 The \tr{+16} is to allow for the initial allocation of \tr{MP_INT} results.
740 The \tr{__abs} stuff is because negative-ness of GMP things is encoded
741 in their ``size''...
742 \begin{code}
743 #define __abs(a)                (( (a) >= 0 ) ? (a) : (-(a)))
744 #define GMP_SIZE_ONE()          (2 + DATA_HS + 16)
745 #define GMP_SAME_SIZE(a)        (__abs(a) + DATA_HS + 16)
746 #define GMP_MAX_SIZE(a,b)       ((__abs(a) > __abs(b) ? __abs(a) : __abs(b)) + 1 + DATA_HS + 16)
747                                 /* NB: the +1 is for the carry (or whatever) */
748 #define GMP_2MAX_SIZE(a,b)      (2 * GMP_MAX_SIZE(a,b))
749 #define GMP_ADD_SIZES(a,b)      (__abs(a) + __abs(b) + 1 + DATA_HS + 16)
750                                 /* the +1 may just be paranoia */
751 \end{code}
752
753 For the Integer/GMP stuff, we have macros that {\em look ahead} for
754 some space, but don't actually grab it.
755
756 If there are live pointers at the time of the lookahead, the caller
757 must make sure they are in \tr{Ret1}, \tr{Ret2}, ..., so they can be
758 handled normally.  We achieve this by having the code generator {\em
759 always} pass args to may-invoke-GC primitives in registers, using the
760 normal pointers-first policy.  This means that, if we do go to garbage
761 collection, everything is already in the Right Place.
762
763 Saving and restoring Hp register so the MP allocator can see them. If we are
764 performing liftime profiling need to save and restore HpLim as well so that
765 it can be bumped if allocation occurs.
766
767 The second argument to @GMP_HEAP_LOOKAHEAD@ must be an lvalue so that
768 it can be restored from @TSO_ARG1@ after a failed @HEAP_CHK@ in
769 threaded land.
770
771 \begin{code}
772 #define GMP_HEAP_LOOKAHEAD(liveness,n)                  \
773         do {                                            \
774         HEAP_CHK_AND_RESTORE_N(liveness,n,0);           \
775         Hp = Hp - (n);                                  \
776         UN_ALLOC_HEAP(n);       /* Undo ticky-ticky */  \
777         SAVE_Hp = Hp;           /* Hand over the hp */  \
778         DEBUG_SetGMPAllocBudget(n)                      \
779         }while(0)
780
781 #define GMP_HEAP_HANDBACK()                             \
782         Hp = SAVE_Hp;                                   \
783         DEBUG_ResetGMPAllocBudget()
784 \end{code}
785
786 \begin{code}
787 void *stgAllocForGMP   PROTO((size_t size_in_bytes));
788 void *stgReallocForGMP PROTO((void *ptr, size_t old_size, size_t new_size));
789 void stgDeallocForGMP  PROTO((void *ptr, size_t size));
790
791 #ifdef ALLOC_DEBUG
792 extern StgInt DEBUG_GMPAllocBudget;
793 #define DEBUG_SetGMPAllocBudget(n)  DEBUG_GMPAllocBudget = (n);
794 #define DEBUG_ResetGMPAllocBudget() DEBUG_GMPAllocBudget = 0;
795 #else
796 #define DEBUG_SetGMPAllocBudget(n)  /*nothing*/
797 #define DEBUG_ResetGMPAllocBudget() /*nothing*/
798 #endif
799 \end{code}
800
801 The real business (defining Integer primops):
802 \begin{code}
803 #define negateIntegerZh(ar,sr,dr, liveness, aa,sa,da) \
804         gmpTake1Return1(GMP_SAME_SIZE, liveness, mpz_neg, ar,sr,dr, aa,sa,da)
805
806 #define plusIntegerZh(ar,sr,dr, liveness, a1,s1,d1, a2,s2,d2) \
807         gmpTake2Return1(GMP_MAX_SIZE, liveness, mpz_add, ar,sr,dr, a1,s1,d1, a2,s2,d2)
808 #define minusIntegerZh(ar,sr,dr, liveness, a1,s1,d1, a2,s2,d2) \
809         gmpTake2Return1(GMP_MAX_SIZE, liveness, mpz_sub, ar,sr,dr, a1,s1,d1, a2,s2,d2)
810 #define timesIntegerZh(ar,sr,dr, liveness, a1,s1,d1, a2,s2,d2) \
811         gmpTake2Return1(GMP_ADD_SIZES, liveness, mpz_mul, ar,sr,dr, a1,s1,d1, a2,s2,d2)
812
813 /* div, mod, quot, rem are defined w/ quotRem & divMod */
814
815 #define quotRemIntegerZh(ar1,sr1,dr1, ar2,sr2,dr2, liveness, a1,s1,d1, a2,s2,d2) \
816         gmpTake2Return2(GMP_2MAX_SIZE, liveness, mpz_divmod, ar1,sr1,dr1, ar2,sr2,dr2, a1,s1,d1, a2,s2,d2)
817 #define divModIntegerZh(ar1,sr1,dr1, ar2,sr2,dr2, liveness,  a1,s1,d1, a2,s2,d2) \
818         gmpTake2Return2(GMP_2MAX_SIZE, liveness, mpz_mdivmod, ar1,sr1,dr1, ar2,sr2,dr2, a1,s1,d1, a2,s2,d2)
819 \end{code}
820
821 Comparison ops (@<@, @>=@, etc.) are defined in terms of the cmp
822 fellow (returns -ve, 0, or +ve).
823 \begin{code}
824 #define cmpIntegerZh(r, hp, a1,s1,d1, a2,s2,d2) /* calls mpz_cmp */             \
825 { MP_INT arg1;                                                                  \
826   MP_INT arg2;                                                                  \
827   /* Does not allocate memory */                                                \
828                                                                                 \
829   arg1.alloc    = (a1);                                                         \
830   arg1.size     = (s1);                                                         \
831   arg1.d        = (unsigned long int *) (BYTE_ARR_CTS(d1));                     \
832   arg2.alloc    = (a2);                                                         \
833   arg2.size     = (s2);                                                         \
834   arg2.d        = (unsigned long int *) (BYTE_ARR_CTS(d2));                     \
835                                                                                 \
836   (r) = SAFESTGCALL2(I_,(void *, MP_INT *, MP_INT *),mpz_cmp,&arg1,&arg2);      \
837 }
838 \end{code}
839
840 Coercions:
841
842 \begin{code}
843 #define integer2IntZh(r, hp, aa,sa,da)                                          \
844 { MP_INT arg;                                                                   \
845   /* Does not allocate memory */                                                \
846                                                                                 \
847   arg.alloc     = (aa);                                                         \
848   arg.size      = (sa);                                                         \
849   arg.d         = (unsigned long int *) (BYTE_ARR_CTS(da));                     \
850                                                                                 \
851   (r) = SAFESTGCALL1(I_,(void *, MP_INT *),mpz_get_si,&arg);                    \
852 }
853
854 /* Since we're forced to know a little bit about MP_INT layout to do this with
855    pre-allocated heap, we just inline the whole of mpz_init_set_si here.
856         ** DIRE WARNING.  if mpz_init_set_si changes, so does this! ***
857 */
858
859 #define int2IntegerZh(ar,sr,dr, hp, i)                                          \
860 { StgInt val; /* to snaffle arg to avoid aliasing */                            \
861                                                                                 \
862   val = (i);  /* snaffle... */                                                  \
863                                                                                 \
864   SET_DATA_HDR((hp),ArrayOfData_info,CCC,DATA_VHS+MIN_MP_INT_SIZE,0);           \
865                                                                                 \
866   if      ((val) < 0) { (sr) = -1; (hp)[DATA_HS] = -(val); }                    \
867   else if ((val) > 0) { (sr) =  1; (hp)[DATA_HS] =  (val); }                    \
868   else /* val==0 */   { (sr) =  0; }                                            \
869   (ar) = 1;                                                                     \
870   (dr) = (B_)(hp);              /* dr is an StgByteArray */                     \
871 }
872
873 #define word2IntegerZh(ar,sr,dr, hp, i)                                         \
874 { StgWord val; /* to snaffle arg to avoid aliasing */                           \
875                                                                                 \
876   val = (i);  /* snaffle... */                                                  \
877                                                                                 \
878   SET_DATA_HDR((hp),ArrayOfData_info,CCC,DATA_VHS+MIN_MP_INT_SIZE,0);           \
879                                                                                 \
880   if ((val) != 0)     { (sr) =  1; (hp)[DATA_HS] =  (val); }                    \
881   else /* val==0 */   { (sr) =  0; }                                            \
882   (ar) = 1;                                                                     \
883   (dr) = (B_)(hp);              /* dr is an StgByteArray */                     \
884 }
885
886 #define integer2WordZh(r, hp, aa,sa,da)                                         \
887 { MP_INT arg;                                                                   \
888   /* Does not allocate memory */                                                \
889                                                                                 \
890   arg.alloc     = (aa);                                                         \
891   arg.size      = (sa);                                                         \
892   arg.d         = (unsigned long int *) (BYTE_ARR_CTS(da));                     \
893                                                                                 \
894   (r) = SAFESTGCALL1(I_,(void *, MP_INT *),mpz_get_ui,&arg);                    \
895 }
896
897 #define integerToInt64Zh(r, hp, aa,sa,da)                                       \
898 { unsigned long int* d;                                                         \
899   StgInt64 res;                                                                 \
900   /* Allocates memory. Chummy with gmp rep. */                                  \
901                                                                                 \
902   d             = (unsigned long int *) (BYTE_ARR_CTS(da));                     \
903                                                                                 \
904   if ( (aa) == 0)      { (res)=(LI_)0; }                                        \
905   else if ( (aa) == 1) { (res)=(LI_)d[0]; }                                     \
906   else                 { (res)=(LI_)d[0] + (LI_)d[1] * 0x100000000LL; }         \
907   (r)=(LI_)( (sa) < 0 ? -res : res);                                            \
908 }
909
910 #define integerToWord64Zh(r, hp, aa,sa,da)                                      \
911 { unsigned long int* d;                                                         \
912   StgWord64 res;                                                                \
913   /* Allocates memory. Chummy with gmp rep. */                                  \
914                                                                                 \
915   d             = (unsigned long int *) (BYTE_ARR_CTS(da));                     \
916                                                                                 \
917   if ( (aa) == 0)      { (res)=(LW_)0; }                                        \
918   else if ( (aa) == 1) { (res)=(LW_)d[0]; }                                     \
919   else                 { (res)=(LW_)d[0] + (LW_)d[1] * 0x100000000ULL; }        \
920   (r) = (res);                                                                  \
921 }
922
923 #define int64ToIntegerZh(ar,sr,dr, hp, li)                                      \
924 { StgInt64 val; /* to snaffle arg to avoid aliasing */                          \
925   StgWord hi;                                                           \
926   int neg=0;                                                            \
927                                                                                 \
928   val = (li);  /* snaffle... */                                                 \
929                                                                                 \
930   SET_DATA_HDR((hp),ArrayOfData_info,CCC,DATA_VHS+MIN_MP_INT_SIZE,0);           \
931                                                                                 \
932   if ( val < 0LL ) {                                                            \
933     neg = 1;                                                                    \
934     val = -val;                                                                 \
935   }                                                                             \
936   hi = (W_)((LW_)val / 0x100000000ULL);                                         \
937   if ((LW_)(val) >= 0x100000000ULL)  { (sr) = 2; (ar) = 2; (hp)[DATA_HS] =  ((W_)val); (hp)[DATA_HS+1] = (hi); } \
938   else if ((val) != 0) { (sr) = 1; (ar) = 1; (hp)[DATA_HS] =  ((W_)val);  }     \
939   else /* val==0 */    { (sr) = 0; (ar) = 1; }                                  \
940   (sr) = ( neg ? -(sr) : (sr) );                                                \
941   (dr) = (B_)(hp);              /* dr is an StgByteArray */                     \
942 }
943
944 #define word64ToIntegerZh(ar,sr,dr, hp, lw)                                     \
945 { StgWord64 val; /* to snaffle arg to avoid aliasing */                         \
946   StgWord hi;                                                                   \
947                                                                                 \
948   val = (lw);  /* snaffle... */                                                 \
949                                                                                 \
950   SET_DATA_HDR((hp),ArrayOfData_info,CCC,DATA_VHS+MIN_MP_INT_SIZE,0);           \
951                                                                                 \
952   hi = (W_)((LW_)val / 0x100000000ULL);                                         \
953   if ((val) >= 0x100000000ULL ) { (sr) = 2; (ar) = 2; (hp)[DATA_HS] =  ((W_)val); (hp)[DATA_HS+1] = (hi); } \
954   else if ((val) != 0)          { (sr) = 1; (ar) = 1; (hp)[DATA_HS] =  ((W_)val); } \
955   else /* val==0 */             { (sr) = 0; (ar) = 1; }                         \
956   (dr) = (B_)(hp);              /* dr is an StgByteArray */                     \
957 }
958
959
960
961 \end{code}
962
963 Then there are a few oddments to make life easier:
964 \begin{code}
965 /*
966    DIRE WARNING.
967    The "str" argument must be a literal C string.
968
969         addr2Integer( ..., "foo")   OK!
970
971         x = "foo";
972         addr2Integer( ..., x)       NO! NO!
973 */
974
975 #define addr2IntegerZh(ar,sr,dr, liveness, str)                                 \
976 { MP_INT result;                                                                \
977   /* taking the number of bytes/8 as the number of words of lookahead           \
978      is plenty conservative */                                                  \
979   I_ space = GMP_SAME_SIZE(sizeof(str) / 8 + 1);                                \
980                                                                                 \
981   GMP_HEAP_LOOKAHEAD(liveness, space);                                          \
982                                                                                 \
983   /* Perform the operation */                                                   \
984   if (SAFESTGCALL3(I_,(void *, MP_INT *, char *, int), mpz_init_set_str,&result,(str),/*base*/10)) \
985       abort();                                                                  \
986                                                                                 \
987   GMP_HEAP_HANDBACK();          /* restore Hp */                                \
988   (ar) = result.alloc;                                                          \
989   (sr) = result.size;                                                           \
990   (dr) = (B_) (result.d - DATA_HS);                                             \
991   /* pt to *beginning* of object (GMP has been monkeying around in the middle) */ \
992 }
993 \end{code}
994
995 Encoding and decoding float-ish things is pretty Integer-ish.  We use
996 these pretty magical support functions, essentially stolen from Lennart:
997 \begin{code}
998 StgFloat  __encodeFloat  PROTO((MP_INT *, I_));
999 void      __decodeFloat  PROTO((MP_INT * /*result1*/,
1000                                 I_ * /*result2*/,
1001                                 StgFloat));
1002
1003 StgDouble __encodeDouble PROTO((MP_INT *, I_));
1004 void      __decodeDouble PROTO((MP_INT * /*result1*/,
1005                                 I_ * /*result2*/,
1006                                 StgDouble));
1007 \end{code}
1008
1009 Some floating-point format info, made with the \tr{enquire} program
1010 (version~4.3) [comes with gcc].
1011 \begin{code}
1012 /* this should be done by CPU architecture, insofar as possible [WDP] */
1013
1014 #if sparc_TARGET_ARCH   \
1015  || alpha_TARGET_ARCH   \
1016  || hppa1_1_TARGET_ARCH \
1017  || i386_TARGET_ARCH    \
1018  || m68k_TARGET_ARCH    \
1019  || mipsel_TARGET_ARCH  \
1020  || mipseb_TARGET_ARCH  \
1021  || powerpc_TARGET_ARCH \
1022  || rs6000_TARGET_ARCH
1023
1024 /* yes, it is IEEE floating point */
1025 #include "ieee-flpt.h"
1026
1027 #if alpha_TARGET_ARCH   \
1028  || i386_TARGET_ARCH            \
1029  || mipsel_TARGET_ARCH
1030
1031 #undef BIGENDIAN /* little-endian weirdos... */
1032 #else
1033 #define BIGENDIAN 1
1034 #endif
1035
1036 #else /* unknown floating-point format */
1037
1038 ******* ERROR *********** Any ideas about floating-point format?
1039
1040 #endif /* unknown floating-point */
1041 \end{code}
1042
1043 \begin{code}
1044 #if alpha_TARGET_ARCH
1045 #define encodeFloatZh(r, hp, aa,sa,da, expon)   encodeDoubleZh(r, hp, aa,sa,da, expon)
1046 #else
1047 #define encodeFloatZh(r, hp, aa,sa,da, expon)   \
1048 { MP_INT arg;                                   \
1049   /* Does not allocate memory */                \
1050                                                 \
1051   arg.alloc     = aa;                           \
1052   arg.size      = sa;                           \
1053   arg.d         = (unsigned long int *) (BYTE_ARR_CTS(da)); \
1054                                                 \
1055   r = SAFESTGCALL2(StgFloat,(void *, MP_INT *, I_), __encodeFloat,&arg,(expon));        \
1056 }
1057 #endif /* ! alpha */
1058
1059 #define encodeDoubleZh(r, hp, aa,sa,da, expon)  \
1060 { MP_INT arg;                                   \
1061   /* Does not allocate memory */                \
1062                                                 \
1063   arg.alloc     = aa;                           \
1064   arg.size      = sa;                           \
1065   arg.d         = (unsigned long int *) (BYTE_ARR_CTS(da)); \
1066                                                 \
1067   r = SAFESTGCALL2(StgDouble,(void *, MP_INT *, I_), __encodeDouble,&arg,(expon));\
1068 }
1069
1070 #if alpha_TARGET_ARCH
1071 #define decodeFloatZh(exponr, ar,sr,dr, hp, f)  decodeDoubleZh(exponr, ar,sr,dr, hp, f)
1072 #else
1073 #define decodeFloatZh(exponr, ar,sr,dr, hp, f)                          \
1074 { MP_INT mantissa;                                                      \
1075   I_ exponent;                                                          \
1076   StgFloat arg = (f);                                                   \
1077                                                                         \
1078   /* Be prepared to tell Lennart-coded __decodeFloat    */              \
1079   /* where mantissa.d can be put (it does not care about the rest) */   \
1080   SET_DATA_HDR(hp,ArrayOfData_info,CCC,DATA_VHS+MIN_MP_INT_SIZE,0);     \
1081   mantissa.d = (hp) + DATA_HS;                                          \
1082                                                                         \
1083   /* Perform the operation */                                           \
1084   SAFESTGCALL3(void,(void *, MP_INT *, I_ *, StgFloat),__decodeFloat,&mantissa,&exponent,arg);          \
1085   exponr= exponent;                                                     \
1086   ar    = mantissa.alloc;                                               \
1087   sr    = mantissa.size;                                                \
1088   dr    = (B_)(hp);                                                     \
1089 }
1090 #endif /* !alpha */
1091
1092 #define decodeDoubleZh(exponr, ar,sr,dr, hp, f)                         \
1093 { MP_INT mantissa;                                                      \
1094   I_ exponent;                                                          \
1095   StgDouble arg = (f);                                                  \
1096                                                                         \
1097   /* Be prepared to tell Lennart-coded __decodeDouble   */              \
1098   /* where mantissa.d can be put (it does not care about the rest) */   \
1099   SET_DATA_HDR(hp,ArrayOfData_info,CCC,DATA_VHS+MIN_MP_INT_SIZE,0);     \
1100   mantissa.d = (hp) + DATA_HS;                                          \
1101                                                                         \
1102   /* Perform the operation */                                           \
1103   SAFESTGCALL3(void,(void *, MP_INT *, I_ *, StgDouble),__decodeDouble,&mantissa,&exponent,arg);                \
1104   exponr= exponent;                                                     \
1105   ar    = mantissa.alloc;                                               \
1106   sr    = mantissa.size;                                                \
1107   dr    = (B_)(hp);                                                     \
1108 }
1109 \end{code}
1110
1111 %************************************************************************
1112 %*                                                                      *
1113 \subsubsection[StgMacros-mv-floats]{Moving floats and doubles around (e.g., to/from stacks)}
1114 %*                                                                      *
1115 %************************************************************************
1116
1117 With GCC, we use magic non-standard inlining; for other compilers, we
1118 just use functions (see also \tr{runtime/prims/PrimArith.lc}).
1119
1120 (The @OMIT_...@ is only used in compiling some of the RTS, none of
1121 which uses these anyway.)
1122
1123 \begin{code}
1124 #if alpha_TARGET_ARCH   \
1125  || i386_TARGET_ARCH    \
1126  || m68k_TARGET_ARCH
1127
1128 #define ASSIGN_FLT(dst, src) *(StgFloat *)(dst) = (src);
1129 #define PK_FLT(src) (*(StgFloat *)(src))
1130
1131 #define ASSIGN_DBL(dst, src) *(StgDouble *)(dst) = (src);
1132 #define PK_DBL(src) (*(StgDouble *)(src))
1133
1134 #else   /* not m68k || alpha || i[34]86 */
1135
1136 /* Special handling for machines with troublesome alignment constraints */
1137
1138 #define FLOAT_ALIGNMENT_TROUBLES    TRUE
1139
1140 #if ! defined(__GNUC__) || ! defined(__STG_GCC_REGS__)
1141
1142 void        ASSIGN_DBL PROTO((W_ [], StgDouble));
1143 StgDouble   PK_DBL     PROTO((W_ []));
1144 void        ASSIGN_FLT PROTO((W_ [], StgFloat));
1145 StgFloat    PK_FLT     PROTO((W_ []));
1146
1147 #else /* yes, its __GNUC__ && we really want them */
1148
1149 #if sparc_TARGET_ARCH
1150
1151 #define ASSIGN_FLT(dst, src) *(StgFloat *)(dst) = (src);
1152 #define PK_FLT(src) (*(StgFloat *)(src))
1153
1154 #define ASSIGN_DBL(dst,src) \
1155       __asm__("st %2,%0\n\tst %R2,%1" : "=m" (((P_)(dst))[0]), \
1156         "=m" (((P_)(dst))[1]) : "f" (src));
1157
1158 #define PK_DBL(src) \
1159     ( { register double d; \
1160       __asm__("ld %1,%0\n\tld %2,%R0" : "=f" (d) : \
1161         "m" (((P_)(src))[0]), "m" (((P_)(src))[1])); d; \
1162     } )
1163
1164 #else /* ! sparc */
1165
1166 /* (not very) forward prototype declarations */
1167 void        ASSIGN_DBL PROTO((W_ [], StgDouble));
1168 StgDouble   PK_DBL     PROTO((W_ []));
1169 void        ASSIGN_FLT PROTO((W_ [], StgFloat));
1170 StgFloat    PK_FLT     PROTO((W_ []));
1171
1172 extern STG_INLINE
1173 void
1174 ASSIGN_DBL(W_ p_dest[], StgDouble src)
1175 {
1176     double_thing y;
1177     y.d = src;
1178     p_dest[0] = y.du.dhi;
1179     p_dest[1] = y.du.dlo;
1180 }
1181
1182 /* GCC also works with this version, but it generates
1183    the same code as the previous one, and is not ANSI
1184
1185 #define ASSIGN_DBL( p_dest, src ) \
1186         *p_dest = ((double_thing) src).du.dhi; \
1187         *(p_dest+1) = ((double_thing) src).du.dlo \
1188 */
1189
1190 extern STG_INLINE
1191 StgDouble
1192 PK_DBL(W_ p_src[])
1193 {
1194     double_thing y;
1195     y.du.dhi = p_src[0];
1196     y.du.dlo = p_src[1];
1197     return(y.d);
1198 }
1199
1200 extern STG_INLINE
1201 void
1202 ASSIGN_FLT(W_ p_dest[], StgFloat src)
1203 {
1204     float_thing y;
1205     y.f = src;
1206     *p_dest = y.fu;
1207 }
1208
1209 extern STG_INLINE
1210 StgFloat
1211 PK_FLT(W_ p_src[])
1212 {
1213     float_thing y;
1214     y.fu = *p_src;
1215     return(y.f);
1216 }
1217
1218 #endif /* ! sparc */
1219
1220 #endif /* __GNUC__ */
1221
1222 #endif /* not __m68k__ */
1223
1224 #if HAVE_LONG_LONG
1225 extern STG_INLINE
1226 void
1227 ASSIGN_Word64(W_ p_dest[], StgWord64 src)
1228 {
1229     word64_thing y;
1230     y.w = src;
1231     p_dest[0] = y.wu.dhi;
1232     p_dest[1] = y.wu.dlo;
1233 }
1234
1235 extern STG_INLINE
1236 StgWord64
1237 PK_Word64(W_ p_src[])
1238 {
1239     word64_thing y;
1240     y.wu.dhi = p_src[0];
1241     y.wu.dlo = p_src[1];
1242     return(y.w);
1243 }
1244
1245 extern STG_INLINE
1246 void
1247 ASSIGN_Int64(W_ p_dest[], StgInt64 src)
1248 {
1249     int64_thing y;
1250     y.i = src;
1251     p_dest[0] = y.iu.dhi;
1252     p_dest[1] = y.iu.dlo;
1253 }
1254
1255 extern STG_INLINE
1256 StgInt64
1257 PK_Int64(W_ p_src[])
1258 {
1259     int64_thing y;
1260     y.iu.dhi = p_src[0];
1261     y.iu.dlo = p_src[1];
1262     return(y.i);
1263 }
1264 #endif
1265
1266 \end{code}
1267
1268 %************************************************************************
1269 %*                                                                      *
1270 \subsubsection[StgMacros-array-primops]{Primitive arrays}
1271 %*                                                                      *
1272 %************************************************************************
1273
1274 We regularly use this macro to fish the ``contents'' part
1275 out of a DATA or TUPLE closure, which is what is used for
1276 non-ptr and ptr arrays (respectively).
1277
1278 BYTE_ARR_CTS returns a @C_ *@!
1279
1280 We {\em ASSUME} we can use the same macro for both!!
1281 \begin{code}
1282
1283 #ifdef DEBUG
1284 #define BYTE_ARR_CTS(a)                                 \
1285  ({ ASSERT(INFO_PTR(a) == (W_) ArrayOfData_info);       \
1286     ((C_ *) (((StgPtr) (a))+DATA_HS)); })
1287 #define PTRS_ARR_CTS(a)                                 \
1288  ({ ASSERT((INFO_PTR(a) == (W_) ArrayOfPtrs_info)       \
1289         || (INFO_PTR(a) == (W_) ImMutArrayOfPtrs_info));\
1290     ((a)+MUTUPLE_HS);} )
1291 #else
1292 #define BYTE_ARR_CTS(a)         ((char *) (((StgPtr) (a))+DATA_HS))
1293 #define PTRS_ARR_CTS(a)         ((a)+MUTUPLE_HS)
1294 #endif
1295
1296 /* sigh */
1297 extern I_ genSymZh(STG_NO_ARGS);
1298 extern I_ resetGenSymZh(STG_NO_ARGS);
1299 extern I_ incSeqWorldZh(STG_NO_ARGS);
1300
1301 extern I_ byteArrayHasNUL__ PROTO((const char *, I_));
1302 \end{code}
1303
1304 OK, the easy ops first: (all except \tr{newArr*}:
1305
1306 (OLD:) VERY IMPORTANT! The read/write/index primitive ops
1307 on @ByteArray#@s index the array using a {\em BYTE} offset, even
1308 if the thing begin gotten out is a multi-byte @Int#@, @Float#@ etc.
1309 This is because you might be trying to take apart a C struct, where
1310 the offset from the start of the struct isn't a multiple of the
1311 size of the thing you're getting.  Hence the @(char *)@ casts.
1312
1313 EVEN MORE IMPORTANT! The above is a lie.  The offsets for BlahArrays
1314 are in Blahs.  WDP 95/08
1315
1316 In the case of messing with @StgAddrs@ (@A_@), which are really \tr{void *},
1317 we cast to @P_@, because you can't index off an uncast \tr{void *}.
1318
1319 In the case of @Array#@ (which contain pointers), the offset is in units
1320 of one ptr (not bytes).
1321
1322 \begin{code}
1323 #define sameMutableArrayZh(r,a,b)       r=(I_)((a)==(b))
1324 #define sameMutableByteArrayZh(r,a,b)   r=(I_)((B_)(a)==(B_)(b))
1325
1326 #define readArrayZh(r,a,i)       r=((PP_) PTRS_ARR_CTS(a))[(i)]
1327
1328 #define readCharArrayZh(r,a,i)   indexCharOffAddrZh(r,BYTE_ARR_CTS(a),i)
1329 #define readIntArrayZh(r,a,i)    indexIntOffAddrZh(r,BYTE_ARR_CTS(a),i)
1330 #define readWordArrayZh(r,a,i)   indexWordOffAddrZh(r,BYTE_ARR_CTS(a),i)
1331 #define readInt64ArrayZh(r,a,i)  indexInt64OffAddrZh(r,BYTE_ARR_CTS(a),i)
1332 #define readWord64ArrayZh(r,a,i) indexWord64OffAddrZh(r,BYTE_ARR_CTS(a),i)
1333 #define readAddrArrayZh(r,a,i)   indexAddrOffAddrZh(r,BYTE_ARR_CTS(a),i)
1334 #define readFloatArrayZh(r,a,i)  indexFloatOffAddrZh(r,BYTE_ARR_CTS(a),i)
1335 #define readDoubleArrayZh(r,a,i) indexDoubleOffAddrZh(r,BYTE_ARR_CTS(a),i)
1336
1337 /* result ("r") arg ignored in write macros! */
1338 #define writeArrayZh(a,i,v)     ((PP_) PTRS_ARR_CTS(a))[(i)]=(v)
1339
1340 #define writeCharArrayZh(a,i,v)   ((C_ *)(BYTE_ARR_CTS(a)))[i] = (v)
1341 #define writeIntArrayZh(a,i,v)    ((I_ *)(BYTE_ARR_CTS(a)))[i] = (v)
1342 #define writeWordArrayZh(a,i,v)   ((W_ *)(BYTE_ARR_CTS(a)))[i] = (v)
1343 #define writeInt64ArrayZh(a,i,v)  ((LI_ *)(BYTE_ARR_CTS(a)))[i] = (v)
1344 #define writeWord64ArrayZh(a,i,v) ((LW_ *)(BYTE_ARR_CTS(a)))[i] = (v)
1345 #define writeAddrArrayZh(a,i,v)   ((PP_)(BYTE_ARR_CTS(a)))[i] = (v)
1346 #define writeFloatArrayZh(a,i,v)  \
1347         ASSIGN_FLT((P_) (((StgFloat *)(BYTE_ARR_CTS(a))) + i),v)
1348 #define writeDoubleArrayZh(a,i,v) \
1349         ASSIGN_DBL((P_) (((StgDouble *)(BYTE_ARR_CTS(a))) + i),v)
1350
1351 #define indexArrayZh(r,a,i)       r=((PP_) PTRS_ARR_CTS(a))[(i)]
1352
1353 #define indexCharArrayZh(r,a,i)   indexCharOffAddrZh(r,BYTE_ARR_CTS(a),i)
1354 #define indexIntArrayZh(r,a,i)    indexIntOffAddrZh(r,BYTE_ARR_CTS(a),i)
1355 #define indexWordArrayZh(r,a,i)   indexWordOffAddrZh(r,BYTE_ARR_CTS(a),i)
1356 #define indexAddrArrayZh(r,a,i)   indexAddrOffAddrZh(r,BYTE_ARR_CTS(a),i)
1357 #define indexFloatArrayZh(r,a,i)  indexFloatOffAddrZh(r,BYTE_ARR_CTS(a),i)
1358 #define indexDoubleArrayZh(r,a,i) indexDoubleOffAddrZh(r,BYTE_ARR_CTS(a),i)
1359 #define indexInt64ArrayZh(r,a,i)  indexInt64OffAddrZh(r,BYTE_ARR_CTS(a),i)
1360 #define indexWord64ArrayZh(r,a,i) indexWord64OffAddrZh(r,BYTE_ARR_CTS(a),i)
1361
1362 #define indexCharOffForeignObjZh(r,fo,i)   indexCharOffAddrZh(r,ForeignObj_CLOSURE_DATA(fo),i)
1363 #define indexIntOffForeignObjZh(r,fo,i)    indexIntOffAddrZh(r,ForeignObj_CLOSURE_DATA(fo),i)
1364 #define indexWordOffForeignObjZh(r,fo,i)   indexWordOffAddrZh(r,ForeignObj_CLOSURE_DATA(fo),i)
1365 #define indexAddrOffForeignObjZh(r,fo,i)   indexAddrOffAddrZh(r,ForeignObj_CLOSURE_DATA(fo),i)
1366 #define indexFloatOffForeignObjZh(r,fo,i)  indexFloatOffAddrZh(r,ForeignObj_CLOSURE_DATA(fo),i)
1367 #define indexDoubleOffForeignObjZh(r,fo,i) indexDoubleOffAddrZh(r,ForeignObj_CLOSURE_DATA(fo),i)
1368 #define indexInt64OffForeignObjZh(r,fo,i)  indexInt64OffAddrZh(r,ForeignObj_CLOSURE_DATA(fo),i)
1369 #define indexWord64OffForeignObjZh(r,fo,i) indexWord64OffAddrZh(r,ForeignObj_CLOSURE_DATA(fo),i)
1370
1371 #define indexCharOffAddrZh(r,a,i)   r= ((C_ *)(a))[i]
1372 #define indexIntOffAddrZh(r,a,i)    r= ((I_ *)(a))[i]
1373 #define indexWordOffAddrZh(r,a,i)   r= ((W_ *)(a))[i]
1374 #define indexAddrOffAddrZh(r,a,i)   r= ((PP_)(a))[i]
1375 #define indexFloatOffAddrZh(r,a,i)  r= PK_FLT((P_) (((StgFloat *)(a)) + i))
1376 #define indexDoubleOffAddrZh(r,a,i) r= PK_DBL((P_) (((StgDouble *)(a)) + i))
1377 #define indexInt64OffAddrZh(r,a,i)  r= ((LI_ *)(a))[i]
1378 #define indexWord64OffAddrZh(r,a,i) r= ((LW_ *)(a))[i]
1379
1380 #define writeCharOffAddrZh(a,i,v)    ((C_ *)(a))[i] = (v)
1381 #define writeIntOffAddrZh(a,i,v)     ((I_ *)(a))[i] = (v)
1382 #define writeWordOffAddrZh(a,i,v)    ((W_ *)(a))[i] = (v)
1383 #define writeAddrOffAddrZh(a,i,v)    ((PP_)(a))[i] = (v)
1384 #define writeFloatOffAddrZh(a,i,v)   ASSIGN_FLT((P_) (((StgFloat *)(a)) + i),v)
1385 #define writeDoubleOffAddrZh(a,i,v)  ASSIGN_DBL((P_) (((StgDouble *)(a)) + i),v)
1386 #define writeInt64OffAddrZh(a,i,v)   ((LI_ *)(a))[i] = (v)
1387 #define writeWord64OffAddrZh(a,i,v)  ((LW_ *)(a))[i] = (v)
1388
1389
1390 /* Freezing arrays-of-ptrs requires changing an info table, for the
1391    benefit of the generational collector.  It needs to scavenge mutable
1392    objects, even if they are in old space.  When they become immutable,
1393    they can be removed from this scavenge list.  */
1394 #define unsafeFreezeArrayZh(r,a)                                \
1395         do {                                            \
1396         P_ result;                                      \
1397         result=(P_) (a);                                \
1398         FREEZE_MUT_HDR(result,ImMutArrayOfPtrs_info);   \
1399         r = result;                                     \
1400         }while(0)
1401
1402 #define unsafeFreezeByteArrayZh(r,a)    r=(B_)(a)
1403
1404 #define sizeofByteArrayZh(r,a)        r=(W_)sizeof(W_)*(W_)(DATA_CLOSURE_SIZE(a)-DATA_VHS)
1405 #define sizeofMutableByteArrayZh(r,a) r=(W_)sizeof(W_)*(W_)(DATA_CLOSURE_SIZE(a)-DATA_VHS)
1406 \end{code}
1407
1408 Now the \tr{newArr*} ops:
1409
1410 \begin{code}
1411 /*
1412 --------------------
1413 Will: ToDo: we need to find suitable places to put this comment, and the
1414 "in-general" one which follows.
1415
1416 ************ Nota Bene.  The "n" in this macro is guaranteed to
1417 be a register, *not* (say) Node[1].  That means that it is guaranteed
1418 to survive GC, provided only that the register is kept unaltered.
1419 This is important, because "n" is used after the HEAP_CHK.
1420
1421 In general, *all* parameters to these primitive-op macros are always
1422 registers.  (Will: For exactly *which* primitive-op macros is this guaranteed?
1423 Exactly those which can trigger GC?)
1424 ------------------------
1425
1426 NOTE: the above may now be OLD (WDP 94/02/10)
1427 */
1428 \end{code}
1429
1430 For char arrays, the size is in {\em BYTES}.
1431
1432 \begin{code}
1433 #define newCharArrayZh(r,liveness,n)    newByteArray(r,liveness,(n) * sizeof(C_))
1434 #define newIntArrayZh(r,liveness,n)     newByteArray(r,liveness,(n) * sizeof(I_))
1435 #define newWordArrayZh(r,liveness,n)    newByteArray(r,liveness,(n) * sizeof(W_))
1436 #define newInt64ArrayZh(r,liveness,n)   newByteArray(r,liveness,(n) * sizeof(LI_))
1437 #define newWord64ArrayZh(r,liveness,n)  newByteArray(r,liveness,(n) * sizeof(LW_))
1438 #define newAddrArrayZh(r,liveness,n)    newByteArray(r,liveness,(n) * sizeof(P_))
1439 #define newFloatArrayZh(r,liveness,n)   newByteArray(r,liveness,(n) * sizeof(StgFloat))
1440 #define newDoubleArrayZh(r,liveness,n)  newByteArray(r,liveness,(n) * sizeof(StgDouble))
1441
1442 #define newByteArray(r,liveness,n)                              \
1443 {                                                               \
1444   P_ result;                                                    \
1445   I_ size;                                                      \
1446                                                                 \
1447   HEAP_CHK(liveness,DATA_HS+BYTES_TO_STGWORDS(n),0);            \
1448   size = BYTES_TO_STGWORDS(n);                                  \
1449   ALLOC_PRIM(DATA_HS,size,0,DATA_HS+size) /* ticky ticky */;    \
1450   CC_ALLOC(CCC,DATA_HS+size,ARR_K);                             \
1451                                                                 \
1452   result = Hp-(DATA_HS+size)+1;                                 \
1453   SET_DATA_HDR(result,ArrayOfData_info,CCC,DATA_VHS+size,0);    \
1454   r = (B_) result;                                              \
1455 }
1456 \end{code}
1457
1458 Arrays of pointers need to be initialised; uses \tr{TUPLES}!
1459 The initialisation value is guaranteed to be in a register,
1460 and will be indicated by the liveness mask, so it's ok to do
1461 a \tr{HEAP_CHK}, which may trigger GC.
1462
1463 \begin{code}
1464 /* The new array initialization routine for the NCG */
1465 void newArrZh_init PROTO((P_ result, I_ n, P_ init));
1466
1467 #define newArrayZh(r,liveness,n,init)                   \
1468 {                                                       \
1469   P_ p;                                                 \
1470   P_ result;                                            \
1471                                                         \
1472   HEAP_CHK(liveness, MUTUPLE_HS+(n),0);                 \
1473   ALLOC_PRIM(MUTUPLE_HS,(n),0,MUTUPLE_HS+(n)) /* ticky ticky */; \
1474   CC_ALLOC(CCC,MUTUPLE_HS+(n),ARR_K); /* cc prof */     \
1475                                                         \
1476   result = Hp + 1 - (MUTUPLE_HS+(n));                   \
1477   SET_MUTUPLE_HDR(result,ArrayOfPtrs_info,CCC,MUTUPLE_VHS+(n),0) \
1478   for (p = result+MUTUPLE_HS; p < (result+MUTUPLE_HS+(n)); p++) { \
1479         *p = (W_) (init);                               \
1480   }                                                     \
1481                                                         \
1482   r = result;                                           \
1483 }
1484 \end{code}
1485
1486 %************************************************************************
1487 %*                                                                      *
1488 \subsubsection[StgMacros-SynchVar-primops]{Synchronizing Variables PrimOps}
1489 %*                                                                      *
1490 %************************************************************************
1491
1492 \begin{code}
1493 ED_(PrelBase_Z91Z93_closure);
1494
1495 #define sameMVarZh(r,a,b)       r=(I_)((a)==(b))
1496
1497 #define newSynchVarZh(r, hp)                            \
1498 {                                                       \
1499   ALLOC_PRIM(MUTUPLE_HS,3,0,MUTUPLE_HS+3) /* ticky ticky */; \
1500   CC_ALLOC(CCC,MUTUPLE_HS+3,ARR_K); /* cc prof */       \
1501   SET_SVAR_HDR(hp,EmptySVar_info,CCC);                  \
1502   SVAR_HEAD(hp) = SVAR_TAIL(hp) = SVAR_VALUE(hp) = PrelBase_Z91Z93_closure;     \
1503   r = hp;                                               \
1504 }
1505 \end{code}
1506
1507 \begin{code}
1508 #ifdef CONCURRENT
1509
1510 void Yield PROTO((W_));
1511
1512 #define takeMVarZh(r, liveness, node)                   \
1513 {                                                       \
1514   while (INFO_PTR(node) != (W_) FullSVar_info) {        \
1515     if (SVAR_HEAD(node) == PrelBase_Z91Z93_closure)             \
1516       SVAR_HEAD(node) = CurrentTSO;                     \
1517     else                                                \
1518       TSO_LINK(SVAR_TAIL(node)) = CurrentTSO;           \
1519     TSO_LINK(CurrentTSO) = (P_) PrelBase_Z91Z93_closure;                \
1520     SVAR_TAIL(node) = CurrentTSO;                       \
1521     DO_YIELD(liveness << 1);                            \
1522   }                                                     \
1523   SET_INFO_PTR(node, EmptySVar_info);                   \
1524   r = SVAR_VALUE(node);                                 \
1525   SVAR_VALUE(node) = PrelBase_Z91Z93_closure;                           \
1526 }
1527
1528 #else
1529
1530 #define takeMVarZh(r, liveness, node)                   \
1531 {                                                       \
1532   if (INFO_PTR(node) != (W_) FullSVar_info) {           \
1533     /* Don't wrap the calls; we're done with STG land */\
1534     fflush(stdout);                                     \
1535     fprintf(stderr, "takeMVar#: MVar is empty.\n");     \
1536     EXIT(EXIT_FAILURE);                                 \
1537   }                                                     \
1538   SET_INFO_PTR(node, EmptySVar_info);                   \
1539   r = SVAR_VALUE(node);                                 \
1540   SVAR_VALUE(node) = PrelBase_Z91Z93_closure;                           \
1541 }
1542
1543 #endif
1544 \end{code}
1545
1546 \begin{code}
1547 #ifdef CONCURRENT
1548
1549 #ifdef GRAN
1550
1551 /* Only difference to the !GRAN def: RunnableThreadsHd has been replaced by */
1552 /* ThreadQueueHd i.e. the tso is added at the end of the thread queue on */
1553 /* the CurrentProc. This means we have an implicit context switch after */
1554 /* putMVar even if unfair scheduling is used in GranSim (default)!  -- HWL */
1555
1556 #define putMVarZh(node, value)                          \
1557 {                                                       \
1558   P_ tso;                                               \
1559   if (INFO_PTR(node) == (W_) FullSVar_info) {           \
1560     /* Don't wrap the calls; we're done with STG land */\
1561     fflush(stdout);                                     \
1562     fprintf(stderr, "putMVar#: MVar already full.\n");  \
1563     EXIT(EXIT_FAILURE);                                 \
1564   }                                                     \
1565   SET_INFO_PTR(node, FullSVar_info);                    \
1566   SVAR_VALUE(node) = value;                             \
1567   tso = SVAR_HEAD(node);                                \
1568   if (tso != (P_) PrelBase_Z91Z93_closure) {                            \
1569     if (DO_QP_PROF)                                     \
1570       STGCALL3(void,(void *, char *, P_, P_),QP_Event2,do_qp_prof > 1 ? "RA" : "RG",tso,CurrentTSO);    \
1571     if (ThreadQueueHd == PrelBase_Z91Z93_closure)               \
1572       ThreadQueueHd = tso;                      \
1573     else                                                \
1574       TSO_LINK(ThreadQueueTl) = tso;            \
1575     ThreadQueueTl = tso;                                \
1576     SVAR_HEAD(node) = TSO_LINK(tso);                    \
1577     TSO_LINK(tso) = (P_) PrelBase_Z91Z93_closure;                       \
1578     if(SVAR_HEAD(node) == (P_) PrelBase_Z91Z93_closure)                 \
1579       SVAR_TAIL(node) = (P_) PrelBase_Z91Z93_closure;           \
1580   }                                                     \
1581 }
1582
1583 #else /* !GRAN */
1584
1585 #define putMVarZh(node, value)                          \
1586 {                                                       \
1587   P_ tso;                                               \
1588   if (INFO_PTR(node) == (W_) FullSVar_info) {           \
1589     /* Don't wrap the calls; we're done with STG land */\
1590     fflush(stdout);                                     \
1591     fprintf(stderr, "putMVar#: MVar already full.\n");  \
1592     EXIT(EXIT_FAILURE);                                 \
1593   }                                                     \
1594   SET_INFO_PTR(node, FullSVar_info);                    \
1595   SVAR_VALUE(node) = value;                             \
1596   tso = SVAR_HEAD(node);                                \
1597   if (tso != (P_) PrelBase_Z91Z93_closure) {                            \
1598     if (DO_QP_PROF)                                     \
1599       STGCALL3(void,(void *, char *, P_, P_),QP_Event2,do_qp_prof > 1 ? "RA" : "RG",tso,CurrentTSO);    \
1600     if (RunnableThreadsHd == PrelBase_Z91Z93_closure)                   \
1601       RunnableThreadsHd = tso;                          \
1602     else                                                \
1603       TSO_LINK(RunnableThreadsTl) = tso;                \
1604     RunnableThreadsTl = tso;                            \
1605     SVAR_HEAD(node) = TSO_LINK(tso);                    \
1606     TSO_LINK(tso) = (P_) PrelBase_Z91Z93_closure;                       \
1607     if(SVAR_HEAD(node) == (P_) PrelBase_Z91Z93_closure)                 \
1608       SVAR_TAIL(node) = (P_) PrelBase_Z91Z93_closure;           \
1609   }                                                     \
1610 }
1611
1612 #endif  /* GRAN */
1613
1614 #else
1615
1616 #define putMVarZh(node, value)                          \
1617 {                                                       \
1618   P_ tso;                                               \
1619   if (INFO_PTR(node) == (W_) FullSVar_info) {           \
1620     /* Don't wrap the calls; we're done with STG land */\
1621     fflush(stdout);                                     \
1622     fprintf(stderr, "putMVar#: MVar already full.\n");  \
1623     EXIT(EXIT_FAILURE);                                 \
1624   }                                                     \
1625   SET_INFO_PTR(node, FullSVar_info);                    \
1626   SVAR_VALUE(node) = value;                             \
1627 }
1628
1629 #endif
1630 \end{code}
1631
1632 \begin{code}
1633 #ifdef CONCURRENT
1634
1635 #define readIVarZh(r, liveness, node)                   \
1636 {                                                       \
1637   if (INFO_PTR(node) != (W_) ImMutArrayOfPtrs_info) {   \
1638     if (SVAR_HEAD(node) == PrelBase_Z91Z93_closure)             \
1639       SVAR_HEAD(node) = CurrentTSO;                     \
1640     else                                                \
1641       TSO_LINK(SVAR_TAIL(node)) = CurrentTSO;           \
1642     TSO_LINK(CurrentTSO) = (P_) PrelBase_Z91Z93_closure;                \
1643     SVAR_TAIL(node) = CurrentTSO;                       \
1644     DO_YIELD(liveness << 1);                            \
1645   }                                                     \
1646   r = SVAR_VALUE(node);                                 \
1647 }
1648
1649 #else
1650
1651 #define readIVarZh(r, liveness, node)                   \
1652 {                                                       \
1653   if (INFO_PTR(node) != (W_) ImMutArrayOfPtrs_info) {   \
1654     /* Don't wrap the calls; we're done with STG land */\
1655     fflush(stdout);                                     \
1656     fprintf(stderr, "readIVar#: IVar is empty.\n");     \
1657     EXIT(EXIT_FAILURE);                                 \
1658   }                                                     \
1659   r = SVAR_VALUE(node);                                 \
1660 }
1661
1662 #endif
1663 \end{code}
1664
1665 \begin{code}
1666 #ifdef CONCURRENT
1667
1668 #ifdef GRAN
1669
1670 /* Only difference to the !GRAN def: RunnableThreadsHd has been replaced by */
1671 /* ThreadQueueHd i.e. the tso is added at the end of the thread queue on */
1672 /* the CurrentProc. This means we have an implicit context switch after */
1673 /* writeIVar even if unfair scheduling is used in GranSim (default)!  -- HWL */
1674
1675 #define writeIVarZh(node, value)                        \
1676 {                                                       \
1677   P_ tso;                                               \
1678   if (INFO_PTR(node) == (W_) ImMutArrayOfPtrs_info) {   \
1679     /* Don't wrap the calls; we're done with STG land */\
1680     fflush(stdout);                                     \
1681     fprintf(stderr, "writeIVar#: IVar already full.\n");\
1682     EXIT(EXIT_FAILURE);                                 \
1683   }                                                     \
1684   tso = SVAR_HEAD(node);                                \
1685   if (tso != (P_) PrelBase_Z91Z93_closure) {                            \
1686     if (ThreadQueueHd == PrelBase_Z91Z93_closure)               \
1687       ThreadQueueHd = tso;                      \
1688     else                                                \
1689       TSO_LINK(ThreadQueueTl) = tso;            \
1690     while(TSO_LINK(tso) != PrelBase_Z91Z93_closure) {                   \
1691       if (DO_QP_PROF)                                   \
1692         STGCALL3(void,(void *, char *, P_, P_),QP_Event2,do_qp_prof > 1 ? "RA" : "RG",tso,CurrentTSO);  \
1693       tso = TSO_LINK(tso);                              \
1694     }                                                   \
1695     if (DO_QP_PROF)                                     \
1696       STGCALL3(void,(void *, char *, P_, P_),QP_Event2,do_qp_prof > 1 ? "RA" : "RG",tso,CurrentTSO);    \
1697     ThreadQueueTl = tso;                                \
1698   }                                                     \
1699   /* Don't use freeze, since it's conditional on GC */  \
1700   SET_INFO_PTR(node, ImMutArrayOfPtrs_info);            \
1701   MUTUPLE_CLOSURE_SIZE(node) = (MUTUPLE_VHS+1);         \
1702   SVAR_VALUE(node) = value;                             \
1703 }
1704
1705 #else /* !GRAN */
1706
1707 #define writeIVarZh(node, value)                        \
1708 {                                                       \
1709   P_ tso;                                               \
1710   if (INFO_PTR(node) == (W_) ImMutArrayOfPtrs_info) {   \
1711     /* Don't wrap the calls; we're done with STG land */\
1712     fflush(stdout);                                     \
1713     fprintf(stderr, "writeIVar#: IVar already full.\n");\
1714     EXIT(EXIT_FAILURE);                                 \
1715   }                                                     \
1716   tso = SVAR_HEAD(node);                                \
1717   if (tso != (P_) PrelBase_Z91Z93_closure) {                            \
1718     if (RunnableThreadsHd == PrelBase_Z91Z93_closure)                   \
1719       RunnableThreadsHd = tso;                          \
1720     else                                                \
1721       TSO_LINK(RunnableThreadsTl) = tso;                \
1722     while(TSO_LINK(tso) != PrelBase_Z91Z93_closure) {                   \
1723       if (DO_QP_PROF)                                   \
1724         STGCALL3(void,(void *, char *, P_, P_),QP_Event2,do_qp_prof > 1 ? "RA" : "RG",tso,CurrentTSO);  \
1725       tso = TSO_LINK(tso);                              \
1726     }                                                   \
1727     if (DO_QP_PROF)                                     \
1728       STGCALL3(void,(void *, char *, P_, P_),QP_Event2,do_qp_prof > 1 ? "RA" : "RG",tso,CurrentTSO);    \
1729     RunnableThreadsTl = tso;                            \
1730   }                                                     \
1731   /* Don't use freeze, since it's conditional on GC */  \
1732   SET_INFO_PTR(node, ImMutArrayOfPtrs_info);            \
1733   MUTUPLE_CLOSURE_SIZE(node) = (MUTUPLE_VHS+1);         \
1734   SVAR_VALUE(node) = value;                             \
1735 }
1736
1737 #endif  /* GRAN */
1738
1739 #else
1740
1741 #define writeIVarZh(node, value)                        \
1742 {                                                       \
1743   P_ tso;                                               \
1744   if (INFO_PTR(node) == (W_) ImMutArrayOfPtrs_info) {   \
1745     /* Don't wrap the calls; we're done with STG land */\
1746     fflush(stdout);                                     \
1747     fprintf(stderr, "writeIVar#: IVar already full.\n");\
1748     EXIT(EXIT_FAILURE);                                 \
1749   }                                                     \
1750   /* Don't use freeze, since it's conditional on GC */  \
1751   SET_INFO_PTR(node, ImMutArrayOfPtrs_info);            \
1752   MUTUPLE_CLOSURE_SIZE(node) = (MUTUPLE_VHS+1);         \
1753   SVAR_VALUE(node) = value;                             \
1754 }
1755
1756 #endif
1757 \end{code}
1758
1759 %************************************************************************
1760 %*                                                                      *
1761 \subsubsection[StgMacros-Wait-primops]{Delay/Wait PrimOps}
1762 %*                                                                      *
1763 %************************************************************************
1764
1765 \begin{code}
1766 #ifdef CONCURRENT
1767
1768 /* ToDo: for GRAN */
1769
1770 #define delayZh(liveness, us)                           \
1771   {                                                     \
1772     if (WaitingThreadsTl == PrelBase_Z91Z93_closure)            \
1773       WaitingThreadsHd = CurrentTSO;                    \
1774     else                                                \
1775       TSO_LINK(WaitingThreadsTl) = CurrentTSO;          \
1776     WaitingThreadsTl = CurrentTSO;                      \
1777     TSO_LINK(CurrentTSO) = PrelBase_Z91Z93_closure;                     \
1778     TSO_EVENT(CurrentTSO) = (W_) ((us) < 1 ? 1 : (us)); \
1779     DO_YIELD(liveness << 1);                            \
1780   }
1781
1782 #else
1783
1784 #define delayZh(liveness, us)                           \
1785   {                                                     \
1786     fflush(stdout);                                     \
1787     fprintf(stderr, "delay#: unthreaded build.\n");     \
1788     EXIT(EXIT_FAILURE);                                 \
1789   }
1790
1791 #endif
1792
1793 #ifdef CONCURRENT
1794
1795 /* ToDo: something for GRAN */
1796
1797 #define waitReadZh(liveness, fd)                        \
1798   {                                                     \
1799     if (WaitingThreadsTl == PrelBase_Z91Z93_closure)            \
1800       WaitingThreadsHd = CurrentTSO;                    \
1801     else                                                \
1802       TSO_LINK(WaitingThreadsTl) = CurrentTSO;          \
1803     WaitingThreadsTl = CurrentTSO;                      \
1804     TSO_LINK(CurrentTSO) = PrelBase_Z91Z93_closure;                     \
1805     TSO_EVENT(CurrentTSO) = (W_) (-(fd));               \
1806     DO_YIELD(liveness << 1);                            \
1807   }
1808
1809 #else
1810
1811 #define waitReadZh(liveness, fd)                        \
1812   {                                                     \
1813     fflush(stdout);                                     \
1814     fprintf(stderr, "waitRead#: unthreaded build.\n");  \
1815     EXIT(EXIT_FAILURE);                                 \
1816   }
1817
1818 #endif
1819
1820 #ifdef CONCURRENT
1821
1822 /* ToDo: something for GRAN */
1823
1824 #ifdef HAVE_SYS_TYPES_H
1825 #include <sys/types.h>
1826 #endif  HAVE_SYS_TYPES_H */
1827
1828 #define waitWriteZh(liveness, fd)                       \
1829   {                                                     \
1830     if (WaitingThreadsTl == PrelBase_Z91Z93_closure)            \
1831       WaitingThreadsHd = CurrentTSO;                    \
1832     else                                                \
1833       TSO_LINK(WaitingThreadsTl) = CurrentTSO;          \
1834     WaitingThreadsTl = CurrentTSO;                      \
1835     TSO_LINK(CurrentTSO) = PrelBase_Z91Z93_closure;                     \
1836     TSO_EVENT(CurrentTSO) = (W_) (-(fd+FD_SETSIZE));    \
1837     DO_YIELD(liveness << 1);                            \
1838   }
1839
1840 #else
1841
1842 #define waitWriteZh(liveness, fd)                       \
1843   {                                                     \
1844     fflush(stdout);                                     \
1845     fprintf(stderr, "waitWrite#: unthreaded build.\n"); \
1846     EXIT(EXIT_FAILURE);                                 \
1847   }
1848
1849 #endif
1850
1851 \end{code}
1852
1853 %************************************************************************
1854 %*                                                                      *
1855 \subsubsection[StgMacros-IO-primops]{Primitive I/O, error-handling primops}
1856 %*                                                                      *
1857 %************************************************************************
1858
1859 \begin{code}
1860 extern P_ TopClosure;
1861 EXTFUN(ErrorIO_innards);
1862 EXTFUN(__std_entry_error__);
1863
1864 #define errorIOZh(a)            \
1865     do { TopClosure=(a);        \
1866          (void) SAFESTGCALL1(I_,(void *, FILE *),fflush,stdout); \
1867          (void) SAFESTGCALL1(I_,(void *, FILE *),fflush,stderr); \
1868          JMP_(ErrorIO_innards); \
1869     } while(0)
1870
1871 /* These are now, I believe, unused. (8/98 SOF) */
1872 #if !defined(CALLER_SAVES_SYSTEM)
1873 /* can use the macros */
1874 #define stg_getc(stream)        getc((FILE *) (stream))
1875 #define stg_putc(c,stream)      putc((c),((FILE *) (stream)))
1876 #else
1877 /* must not use the macros (they contain embedded calls to _filbuf/whatnot) */
1878 #define stg_getc(stream)        SAFESTGCALL1(I_,(void *, FILE *),fgetc,(FILE *) (stream))
1879 #define stg_putc(c,stream)      SAFESTGCALL2(I_,(void *, char, FILE *),fputc,(c),((FILE *) (stream)))
1880 #endif
1881
1882 int initialize_virtual_timer(int us);
1883 int install_segv_handler(STG_NO_ARGS);
1884 int install_vtalrm_handler(STG_NO_ARGS);
1885 void initUserSignals(STG_NO_ARGS);
1886 void blockUserSignals(STG_NO_ARGS);
1887 void unblockUserSignals(STG_NO_ARGS);
1888 IF_RTS(void blockVtAlrmSignal(STG_NO_ARGS);)
1889 IF_RTS(void unblockVtAlrmSignal(STG_NO_ARGS);)
1890 IF_RTS(void AwaitEvent(I_ delta);)
1891
1892 #if  defined(_POSIX_SOURCE) && !defined(nextstep3_TARGET_OS)
1893         /* For nextstep3_TARGET_OS comment see stgdefs.h. CaS */
1894 extern I_ sig_install PROTO((I_, I_, sigset_t *));
1895 #define stg_sig_ignore(s,m)     SAFESTGCALL3(I_,(void *, I_, I_),sig_install,s,STG_SIG_IGN,(sigset_t *)m)
1896 #define stg_sig_default(s,m)    SAFESTGCALL3(I_,(void *, I_, I_),sig_install,s,STG_SIG_DFL,(sigset_t *)m)
1897 #define stg_sig_catch(s,sp,m)   SAFESTGCALL3(I_,(void *, I_, I_),sig_install,s,sp,(sigset_t *)m)
1898 #else
1899 extern I_ sig_install PROTO((I_, I_));
1900 #define stg_sig_ignore(s,m)     SAFESTGCALL2(I_,(void *, I_, I_),sig_install,s,STG_SIG_IGN)
1901 #define stg_sig_default(s,m)    SAFESTGCALL2(I_,(void *, I_, I_),sig_install,s,STG_SIG_DFL)
1902 #define stg_sig_catch(s,sp,m)   SAFESTGCALL2(I_,(void *, I_, I_),sig_install,s,sp)
1903 #endif
1904
1905 #define STG_SIG_DFL     (-1)
1906 #define STG_SIG_IGN     (-2)
1907 #define STG_SIG_ERR     (-3)
1908
1909 StgInt getErrorHandler(STG_NO_ARGS);
1910 #ifndef PAR
1911 void   raiseError PROTO((StgStablePtr handler));
1912 StgInt catchError PROTO((StgStablePtr newErrorHandler));
1913 #endif
1914 void decrementErrorCount(STG_NO_ARGS);
1915
1916 #define stg_catchError(sp)        SAFESTGCALL1(I_,(void *, StgStablePtr),catchError,sp)
1917 #define stg_decrementErrorCount() SAFESTGCALL0(void,(void *),decrementErrorCount)
1918 \end{code}
1919
1920 %************************************************************************
1921 %*                                                                      *
1922 \subsubsection[StgMacros-stable-ptr]{Primitive ops for manipulating stable pointers}
1923 %*                                                                      *
1924 %************************************************************************
1925
1926
1927 The type of these should be:
1928
1929 \begin{verbatim}
1930 makeStablePointer#  :: a -> State# _RealWorld -> StateAndStablePtr# _RealWorld a
1931 deRefStablePointer# :: StablePtr# a -> State# _RealWorld -> StateAndPtr _RealWorld a
1932 \end{verbatim}
1933
1934 Since world-tokens are no longer explicitly passed around, the
1935 implementations have a few less arguments/results.
1936
1937 The simpler one is @deRefStablePointer#@ (which is only a primop
1938 because it is more polymorphic than is allowed of a ccall).
1939
1940 \begin{code}
1941 #ifdef PAR
1942
1943 #define deRefStablePtrZh(ri,sp)                                     \
1944 do {                                                                \
1945     fflush(stdout);                                                 \
1946     fprintf(stderr, "deRefStablePtr#: no stable pointer support.\n");\
1947     EXIT(EXIT_FAILURE);                                             \
1948 } while(0)
1949
1950 #else /* !PAR */
1951
1952 extern StgPtr _deRefStablePointer PROTO((StgInt, StgPtr));
1953
1954 #define deRefStablePtrZh(ri,sp) \
1955    ri = SAFESTGCALL2(I_,(void *, I_, P_),_deRefStablePointer,sp,StorageMgrInfo.StablePointerTable);
1956 \end{code}
1957
1958 Declarations for other stable pointer operations.
1959
1960 \begin{code}
1961 void    freeStablePointer       PROTO((I_ stablePtr));
1962
1963 void    enterStablePtr          PROTO((StgStablePtr, StgFunPtr));
1964 void    performIO               PROTO((StgStablePtr));
1965 I_      enterInt                PROTO((StgStablePtr));
1966 I_      enterFloat              PROTO((StgStablePtr));
1967 P_      deRefStablePointer      PROTO((StgStablePtr));
1968 IF_RTS(I_ catchSoftHeapOverflow PROTO((StgStablePtr, I_));)
1969 IF_RTS(I_ getSoftHeapOverflowHandler(STG_NO_ARGS);)
1970 IF_RTS(extern StgStablePtr softHeapOverflowHandler;)
1971 IF_RTS(void shutdownHaskell(STG_NO_ARGS);)
1972
1973 EXTFUN(stopPerformIODirectReturn);
1974 EXTFUN(startPerformIO);
1975 EXTFUN(stopEnterIntDirectReturn);
1976 EXTFUN(startEnterInt);
1977 EXTFUN(stopEnterFloatDirectReturn);
1978 EXTFUN(startEnterFloat);
1979
1980 void enterStablePtr PROTO((StgStablePtr stableIndex, StgFunPtr startCode));
1981
1982 char* createAdjustor PROTO((int cc,StgStablePtr hptr, StgFunPtr wptr));
1983 void freeAdjustor PROTO((void* ptr));
1984
1985 #endif /* !PAR */
1986
1987 IF_RTS(extern I_ ErrorIO_call_count;)
1988 \end{code}
1989
1990 Somewhat harder is @makeStablePointer#@ --- it is usually simple but
1991 if we're unlucky, it will have to allocate a new table and copy the
1992 old bit over.  Since we might, very occasionally, have to call the
1993 garbage collector, this has to be a macro... sigh!
1994
1995 NB @newSP@ is required because it is entirely possible that
1996 @stablePtr@ and @unstablePtr@ are aliases and so we can't do the
1997 assignment to @stablePtr@ until we've finished with @unstablePtr@.
1998
1999 Another obscure piece of coding is the recalculation of the size of
2000 the table.  We do this just in case Jim's threads decide they want to
2001 context switch---in which case any stack-allocated variables may get
2002 trashed.  (If only there was a special heap check which didn't
2003 consider context switching...)
2004
2005 \begin{code}
2006 #ifndef PAR
2007
2008 /* Calculate SP Table size from number of pointers */
2009 #define SPTSizeFromNoPtrs( newNP ) (DYN_VHS + 1 + 2 * (newNP))
2010
2011 /* Calculate number of pointers in new table from number in old table:
2012    any strictly increasing expression will do here */
2013 #define CalcNewNoSPtrs( i ) ((i)*2 + 100)
2014
2015 void enlargeSPTable PROTO((P_, P_));
2016
2017 #define makeStablePtrZh(stablePtr,liveness,unstablePtr)             \
2018 do {                                                                \
2019   EXTDATA_RO(StablePointerTable_info);                              \
2020   EXTDATA(UnusedSP);                                                \
2021   StgStablePtr newSP;                                               \
2022                                                                     \
2023   if (SPT_EMPTY(StorageMgrInfo.StablePointerTable)) { /* free stack is empty */ \
2024     { /* Variables used before the heap check */                    \
2025       I_ OldNoPtrs = SPT_NoPTRS( StorageMgrInfo.StablePointerTable ); \
2026       I_ NewNoPtrs = CalcNewNoSPtrs( OldNoPtrs );                   \
2027       I_ NewSize = SPTSizeFromNoPtrs( NewNoPtrs );                  \
2028       HEAP_CHK(liveness, _FHS+NewSize, 0);                          \
2029     }                                                               \
2030     { /* Variables used after the heap check - same values */       \
2031       I_ OldNoPtrs = SPT_NoPTRS( StorageMgrInfo.StablePointerTable ); \
2032       I_ NewNoPtrs = CalcNewNoSPtrs( OldNoPtrs );                   \
2033       I_ NewSize = SPTSizeFromNoPtrs( NewNoPtrs );                  \
2034       P_ SPTable = Hp + 1 - (_FHS + NewSize);                       \
2035                                                                     \
2036       CC_ALLOC(CCC, _FHS+NewSize, SPT_K); /* cc prof */             \
2037       SET_DYN_HDR(SPTable,StablePointerTable_info,CCC,NewSize,NewNoPtrs);\
2038       SAFESTGCALL2(void, (void *, P_, P_), enlargeSPTable, SPTable, StorageMgrInfo.StablePointerTable);      \
2039       StorageMgrInfo.StablePointerTable = SPTable;                  \
2040     }                                                               \
2041   }                                                                 \
2042                                                                     \
2043   newSP = SPT_POP(StorageMgrInfo.StablePointerTable);               \
2044   SPT_SPTR(StorageMgrInfo.StablePointerTable, newSP) = unstablePtr; \
2045   CHECK_SPT_CLOSURE( StorageMgrInfo.StablePointerTable );           \
2046   stablePtr = newSP;                                                \
2047 } while (0)
2048
2049 #else
2050
2051 #define makeStablePtrZh(stablePtr,liveness,unstablePtr)             \
2052 do {                                                                \
2053     fflush(stdout);                                                 \
2054     fprintf(stderr, "makeStablePtr#: no stable pointer support.\n");\
2055     EXIT(EXIT_FAILURE);                                             \
2056 } while(0)
2057
2058 #endif /* !PAR */
2059 \end{code}
2060
2061 %************************************************************************
2062 %*                                                                      *
2063 \subsubsection[StgMacros-unsafePointerEquality]{Primitive `op' for breaking referential transparency}
2064 %*                                                                      *
2065 %************************************************************************
2066
2067 The type of this is @reallyUnsafePtrEquality :: a -> a -> Int#@ so we
2068 can expect three parameters: the two arguments and a "register" to put
2069 the result into.
2070
2071 Message to Will: This primop breaks referential transparency so badly
2072 you might want to leave it out.  On the other hand, if you hide it
2073 away in an appropriate monad, it's perfectly safe. [ADR]
2074
2075 Note that this primop is non-deterministic: different results can be
2076 obtained depending on just what the garbage collector (and code
2077 optimiser??) has done.  However, we can guarantee that if two objects
2078 are pointer-equal, they have the same denotation --- the converse most
2079 certainly doesn't hold.
2080
2081 ToDo ADR: The degree of non-determinism could be greatly reduced by
2082 following indirections.
2083
2084 \begin{code}
2085 #define reallyUnsafePtrEqualityZh(r,a,b) r=((StgPtr)(a) == (StgPtr)(b))
2086 \end{code}
2087
2088 %************************************************************************
2089 %*                                                                      *
2090 \subsubsection[StgMacros-parallel-primop]{Primitive `op' for sparking (etc)}
2091 %*                                                                      *
2092 %************************************************************************
2093
2094 Assuming local sparking in some form, we can now inline the spark request.
2095
2096 We build a doubly-linked list in the heap, so that we can handle FIFO
2097 or LIFO scheduling as we please.
2098
2099 Anything with tag >= 0 is in WHNF, so we discard it.
2100
2101 \begin{code}
2102 #ifdef CONCURRENT
2103
2104 ED_(PrelBase_Z91Z93_closure);
2105 ED_(True_closure);
2106
2107 #if defined(GRAN)
2108 #define parZh(r,node)                           \
2109         PARZh(r,node,1,0,0,0,0,0)
2110
2111 #define parAtZh(r,node,where,identifier,gran_info,size_info,par_info,rest) \
2112         parATZh(r,node,where,identifier,gran_info,size_info,par_info,rest,1)
2113
2114 #define parAtAbsZh(r,node,proc,identifier,gran_info,size_info,par_info,rest) \
2115         parATZh(r,node,proc,identifier,gran_info,size_info,par_info,rest,2)
2116
2117 #define parAtRelZh(r,node,proc,identifier,gran_info,size_info,par_info,rest) \
2118         parATZh(r,node,proc,identifier,gran_info,size_info,par_info,rest,3)
2119
2120 #define parAtForNowZh(r,node,where,identifier,gran_info,size_info,par_info,rest)        \
2121         parATZh(r,node,where,identifier,gran_info,size_info,par_info,rest,0)
2122
2123 #define parATZh(r,node,where,identifier,gran_info,size_info,par_info,rest,local)        \
2124 {                                                       \
2125   sparkq result;                                                \
2126   if (SHOULD_SPARK(node)) {                             \
2127     SaveAllStgRegs();                                   \
2128     { sparkq result;                                            \
2129       result = NewSpark((P_)node,identifier,gran_info,size_info,par_info,local);        \
2130       if (local==2) {         /* special case for parAtAbs */   \
2131         GranSimSparkAtAbs(result,(I_)where,identifier);\
2132       } else if (local==3) {  /* special case for parAtRel */   \
2133         GranSimSparkAtAbs(result,(I_)(CurrentProc+where),identifier);   \
2134       } else {       \
2135         GranSimSparkAt(result,where,identifier);        \
2136       }        \
2137       context_switch = 1;                               \
2138     }                                                   \
2139     RestoreAllStgRegs();                                \
2140   } else if (do_qp_prof) {                              \
2141     I_ tid = threadId++;                                \
2142     SAFESTGCALL2(void,(I_, P_),QP_Event0,tid,node);     \
2143   }                                                     \
2144   r = 1; /* return code for successful spark -- HWL */  \
2145 }
2146
2147 #define parLocalZh(r,node,identifier,gran_info,size_info,par_info,rest) \
2148         PARZh(r,node,rest,identifier,gran_info,size_info,par_info,1)
2149
2150 #define parGlobalZh(r,node,identifier,gran_info,size_info,par_info,rest) \
2151         PARZh(r,node,rest,identifier,gran_info,size_info,par_info,0)
2152
2153 #if 1
2154
2155 #define PARZh(r,node,rest,identifier,gran_info,size_info,par_info,local) \
2156 {                                                       \
2157   if (SHOULD_SPARK(node)) {                             \
2158     SaveAllStgRegs();                                   \
2159     { sparkq result;                                            \
2160       result = NewSpark((P_)node,identifier,gran_info,size_info,par_info,local);\
2161       add_to_spark_queue(result);                               \
2162       GranSimSpark(local,(P_)node);                                     \
2163       context_switch = 1;                               \
2164     }                                                   \
2165     RestoreAllStgRegs();                                \
2166   } else if (do_qp_prof) {                              \
2167     I_ tid = threadId++;                                \
2168     SAFESTGCALL2(void,(I_, P_),QP_Event0,tid,node);     \
2169   }                                                     \
2170   r = 1; /* return code for successful spark -- HWL */  \
2171 }
2172
2173 #else
2174
2175 #define PARZh(r,node,rest,identifier,gran_info,size_info,par_info,local) \
2176 {                                                       \
2177   sparkq result;                                                \
2178   if (SHOULD_SPARK(node)) {                             \
2179     result = NewSpark((P_)node,identifier,gran_info,size_info,par_info,local);\
2180     ADD_TO_SPARK_QUEUE(result);                         \
2181     SAFESTGCALL2(void,(W_),GranSimSpark,local,(P_)node);        \
2182     /* context_switch = 1;  not needed any more -- HWL */       \
2183   } else if (do_qp_prof) {                              \
2184     I_ tid = threadId++;                                \
2185     SAFESTGCALL2(void,(I_, P_),QP_Event0,tid,node);     \
2186   }                                                     \
2187   r = 1; /* return code for successful spark -- HWL */  \
2188 }
2189
2190 #endif 
2191
2192 #define copyableZh(r,node)                              \
2193   /* copyable not yet implemented!! */
2194
2195 #define noFollowZh(r,node)                              \
2196   /* noFollow not yet implemented!! */
2197
2198 #else  /* !GRAN */
2199
2200 extern I_ required_thread_count;
2201
2202 #ifdef PAR
2203 #define COUNT_SPARK     TSO_GLOBALSPARKS(CurrentTSO)++; sparksCreated++
2204 #else
2205 #define COUNT_SPARK
2206 #endif
2207
2208 /* 
2209    Note that we must bump the required thread count NOW, rather
2210    than when the thread is actually created.  
2211  */
2212
2213 #define forkZh(r,liveness,node)                         \
2214 {                                                       \
2215   while (PendingSparksTl[REQUIRED_POOL] == PendingSparksLim[REQUIRED_POOL]) \
2216     DO_YIELD((liveness << 1) | 1);                      \
2217   COUNT_SPARK;                                          \
2218   if (SHOULD_SPARK(node)) {                             \
2219     *PendingSparksTl[REQUIRED_POOL]++ = (P_)(node);     \
2220   } else if (DO_QP_PROF) {                              \
2221     I_ tid = threadId++;                                \
2222     SAFESTGCALL2(void,(I_, P_),QP_Event0,tid,node);     \
2223   }                                                     \
2224   required_thread_count++;                              \
2225   context_switch = 1;                                   \
2226   r = 1; /* Should not be necessary */                  \
2227 }
2228
2229 #define parZh(r,node)                                   \
2230 {                                                       \
2231   COUNT_SPARK;                                          \
2232   if (SHOULD_SPARK(node) &&                             \
2233    PendingSparksTl[ADVISORY_POOL] < PendingSparksLim[ADVISORY_POOL]) {  \
2234     *PendingSparksTl[ADVISORY_POOL]++ = (P_)(node);     \
2235   } else {                                              \
2236     sparksIgnored++;                                    \
2237     if (DO_QP_PROF) {                                   \
2238       I_ tid = threadId++;                              \
2239       SAFESTGCALL2(void,(I_, P_),QP_Event0,tid,node);   \
2240     }                                                   \
2241   }                                                     \
2242   r = 1; /* Should not be necessary */                  \
2243 }
2244
2245 #endif  /* GRAN */ 
2246
2247 #endif  /* CONCURRENT */
2248 \end{code}
2249
2250 The following seq# code should only be used in unoptimized code.
2251 Be warned: it's a potential bug-farm.
2252 [SOF 8/98: 
2253   Yes, it completely fails to work for function values, since a PAP 
2254   closure will be constructed when the arg satisfaction check fails.
2255   This PAP closure will add the magic values that gets pushed on the B stack 
2256   before entering the 'seqee' (new word!), as Jim is just about to tell
2257   us about. Let's hear what he's got to say:
2258 ]
2259
2260 First we push two words on the B stack: the current value of RetReg 
2261 (which may or may not be live), and a continuation snatched largely out
2262 of thin air (it's a point within this code block).  Then we set RetReg
2263 to the special polymorphic return code for seq, load up Node with the
2264 closure to be evaluated, and we're off.  When the eval returns to the
2265 polymorphic seq return point, the two words are popped off the B stack,
2266 RetReg is restored, and we jump to the continuation, completing the
2267 primop and going on our merry way.
2268
2269 [ To workaround the shortcoming of not being able to deal with partially
2270   applied values, we explicitly prohibit this at the Haskell source level
2271   (i.e., we don't define an Eval instance for (->) ). 
2272 ]
2273
2274 \begin{code}
2275
2276 ED_RO_(vtbl_seq);
2277
2278 #define seqZh(r,liveness,node)              \
2279   ({                                        \
2280     __label__ cont;                         \
2281     /* STK_CHK(liveness,0,2,0,0,0,0); */    \
2282     /* SpB -= BREL(2); */                   \
2283     SpB[BREL(0)] = (W_) RetReg;             \
2284     SpB[BREL(1)] = (W_) &&cont;             \
2285     RetReg = (StgRetAddr) vtbl_seq;         \
2286     Node = node;                            \
2287     ENT_VIA_NODE();                         \
2288     InfoPtr = (D_)(INFO_PTR(Node));         \
2289     JMP_(ENTRY_CODE(InfoPtr));              \
2290     cont:                                   \
2291     r = 1; /* Should be unnecessary */      \
2292   })
2293
2294 \end{code}
2295
2296 %************************************************************************
2297 %*                                                                      *
2298 \subsubsection[StgMacros-foreign-objects]{Foreign Objects}
2299 %*                                                                      *
2300 %************************************************************************
2301
2302 [Based on previous MallocPtr comments -- SOF]
2303
2304 This macro is used to construct a ForeignObj on the heap.
2305
2306 What this does is plug the pointer (which will be in a local
2307 variable) together with its finalising/free routine, into a fresh heap
2308 object and then sets a result (which will be a register) to point
2309 to the fresh heap object.
2310
2311 To accommodate per-object finalisation, augment the macro with a
2312 finalisation routine argument. Nothing spectacular, just plug the
2313 pointer to the routine into the ForeignObj -- SOF 4/96
2314
2315 Question: what's this "SET_ACTIVITY" stuff - should I be doing this
2316 too?  (It's if you want to use the SPAT profiling tools to
2317 characterize program behavior by ``activity'' -- tail-calling,
2318 heap-checking, etc. -- see Ticky.lh.  It is quite specialized.
2319 WDP 95/1)
2320
2321 (Swapped first two arguments to make it come into line with what appears
2322 to be `standard' format, return register then liveness mask. -- SOF 4/96)
2323
2324 \begin{code}
2325 #ifndef PAR
2326
2327 StgInt eqForeignObj PROTO((StgForeignObj p1, StgForeignObj p2));
2328 StgInt eqStablePtr  PROTO((StgStablePtr  p1, StgStablePtr p2));
2329
2330 #define makeForeignObjZh(r, liveness, mptr, finalise)    \
2331 do {                                                     \
2332   P_ result;                                             \
2333                                                          \
2334   HEAP_CHK((W_)liveness, _FHS + ForeignObj_SIZE,0);              \
2335   CC_ALLOC(CCC,_FHS + ForeignObj_SIZE,ForeignObj_K); /* cc prof */   \
2336                                                                    \
2337   result = Hp + 1 - (_FHS + ForeignObj_SIZE);                      \
2338   SET_ForeignObj_HDR(result,ForeignObj_info,CCC,_FHS + ForeignObj_SIZE,0); \
2339   ForeignObj_CLOSURE_DATA(result)      = (P_)mptr;                 \
2340   ForeignObj_CLOSURE_FINALISER(result) = (P_)finalise;             \
2341   ForeignObj_CLOSURE_LINK(result) = StorageMgrInfo.ForeignObjList; \
2342   StorageMgrInfo.ForeignObjList = result;                          \
2343                                                         \
2344                                                         \
2345  /*fprintf(stderr,"DEBUG: ForeignObj(0x%x) = <0x%x, 0x%x, 0x%x, 0x%x>\n",       \
2346       result,                                           \
2347       result[0],result[1],                              \
2348       result[2],result[3]);*/                           \
2349                                                         \
2350   CHECK_ForeignObj_CLOSURE( result );                   \
2351   VALIDATE_ForeignObjList( StorageMgrInfo.ForeignObjList ); \
2352                                                         \
2353   (r) = (P_) result;                                    \
2354 } while (0)
2355
2356 #define writeForeignObjZh(res,datum)    ((PP_) ForeignObj_CLOSURE_DATA(res)) = ((P_)datum)
2357
2358 #else
2359 #define makeForeignObjZh(r, liveness, mptr, finalise)               \
2360 do {                                                                \
2361     fflush(stdout);                                                 \
2362     fprintf(stderr, "makeForeignObj#: no foreign object support.\n");\
2363     EXIT(EXIT_FAILURE);                                             \
2364 } while(0)
2365
2366 #define writeForeignObjZh(res,datum)    \
2367 do {                                                                \
2368     fflush(stdout);                                                 \
2369     fprintf(stderr, "writeForeignObj#: no foreign object support.\n");\
2370     EXIT(EXIT_FAILURE);                                             \
2371 } while(0)
2372
2373 #endif /* !PAR */
2374 \end{code}
2375
2376
2377 End-of-file's multi-slurp protection:
2378 \begin{code}
2379 #endif /* ! STGMACROS_H */
2380 \end{code}