1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2004
5 * Out-of-line primitive operations
7 * This file contains the implementations of all the primitive
8 * operations ("primops") which are not expanded inline. See
9 * ghc/compiler/prelude/primops.txt.pp for a list of all the primops;
10 * this file contains code for most of those with the attribute
13 * Entry convention: the entry convention for a primop is that all the
14 * args are in Stg registers (R1, R2, etc.). This is to make writing
15 * the primops easier. (see compiler/codeGen/CgCallConv.hs).
17 * Return convention: results from a primop are generally returned
18 * using the ordinary unboxed tuple return convention. The C-- parser
19 * implements the RET_xxxx() macros to perform unboxed-tuple returns
20 * based on the prevailing return convention.
22 * This file is written in a subset of C--, extended with various
23 * features specific to GHC. It is compiled by GHC directly. For the
24 * syntax of .cmm files, see the parser in ghc/compiler/cmm/CmmParse.y.
26 * ---------------------------------------------------------------------------*/
31 #ifndef mingw32_HOST_OS
41 import __gmpz_tdiv_qr;
42 import __gmpz_fdiv_qr;
43 import __gmpz_divexact;
49 import pthread_mutex_lock;
50 import pthread_mutex_unlock;
52 import base_ControlziExceptionziBase_nestedAtomically_closure;
53 import EnterCriticalSection;
54 import LeaveCriticalSection;
55 import ghczmprim_GHCziBool_False_closure;
57 /*-----------------------------------------------------------------------------
60 Basically just new*Array - the others are all inline macros.
62 The size arg is always passed in R1, and the result returned in R1.
64 The slow entry point is for returning from a heap check, the saved
65 size argument must be re-loaded from the stack.
66 -------------------------------------------------------------------------- */
68 /* for objects that are *less* than the size of a word, make sure we
69 * round up to the nearest word for the size of the array.
74 W_ words, payload_words, n, p;
75 MAYBE_GC(NO_PTRS,newByteArrayzh_fast);
77 payload_words = ROUNDUP_BYTES_TO_WDS(n);
78 words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
79 ("ptr" p) = foreign "C" allocateLocal(MyCapability() "ptr",words) [];
80 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
81 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
82 StgArrWords_words(p) = payload_words;
86 newPinnedByteArrayzh_fast
88 W_ words, payload_words, n, p;
90 MAYBE_GC(NO_PTRS,newPinnedByteArrayzh_fast);
92 payload_words = ROUNDUP_BYTES_TO_WDS(n);
94 // We want an 8-byte aligned array. allocatePinned() gives us
95 // 8-byte aligned memory by default, but we want to align the
96 // *goods* inside the ArrWords object, so we have to check the
97 // size of the ArrWords header and adjust our size accordingly.
98 words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
99 if ((SIZEOF_StgArrWords & 7) != 0) {
103 ("ptr" p) = foreign "C" allocatePinned(words) [];
104 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
106 // Again, if the ArrWords header isn't a multiple of 8 bytes, we
107 // have to push the object forward one word so that the goods
108 // fall on an 8-byte boundary.
109 if ((SIZEOF_StgArrWords & 7) != 0) {
113 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
114 StgArrWords_words(p) = payload_words;
120 W_ words, n, init, arr, p;
121 /* Args: R1 = words, R2 = initialisation value */
124 MAYBE_GC(R2_PTR,newArrayzh_fast);
126 words = BYTES_TO_WDS(SIZEOF_StgMutArrPtrs) + n;
127 ("ptr" arr) = foreign "C" allocateLocal(MyCapability() "ptr",words) [R2];
128 TICK_ALLOC_PRIM(SIZEOF_StgMutArrPtrs, WDS(n), 0);
130 SET_HDR(arr, stg_MUT_ARR_PTRS_DIRTY_info, W_[CCCS]);
131 StgMutArrPtrs_ptrs(arr) = n;
133 // Initialise all elements of the the array with the value in R2
135 p = arr + SIZEOF_StgMutArrPtrs;
137 if (p < arr + WDS(words)) {
146 unsafeThawArrayzh_fast
148 // SUBTLETY TO DO WITH THE OLD GEN MUTABLE LIST
150 // A MUT_ARR_PTRS lives on the mutable list, but a MUT_ARR_PTRS_FROZEN
151 // normally doesn't. However, when we freeze a MUT_ARR_PTRS, we leave
152 // it on the mutable list for the GC to remove (removing something from
153 // the mutable list is not easy, because the mut_list is only singly-linked).
155 // So that we can tell whether a MUT_ARR_PTRS_FROZEN is on the mutable list,
156 // when we freeze it we set the info ptr to be MUT_ARR_PTRS_FROZEN0
157 // to indicate that it is still on the mutable list.
159 // So, when we thaw a MUT_ARR_PTRS_FROZEN, we must cope with two cases:
160 // either it is on a mut_list, or it isn't. We adopt the convention that
161 // the closure type is MUT_ARR_PTRS_FROZEN0 if it is on the mutable list,
162 // and MUT_ARR_PTRS_FROZEN otherwise. In fact it wouldn't matter if
163 // we put it on the mutable list more than once, but it would get scavenged
164 // multiple times during GC, which would be unnecessarily slow.
166 if (StgHeader_info(R1) != stg_MUT_ARR_PTRS_FROZEN0_info) {
167 SET_INFO(R1,stg_MUT_ARR_PTRS_DIRTY_info);
168 recordMutable(R1, R1);
169 // must be done after SET_INFO, because it ASSERTs closure_MUTABLE()
172 SET_INFO(R1,stg_MUT_ARR_PTRS_DIRTY_info);
177 /* -----------------------------------------------------------------------------
179 -------------------------------------------------------------------------- */
184 /* Args: R1 = initialisation value */
186 ALLOC_PRIM( SIZEOF_StgMutVar, R1_PTR, newMutVarzh_fast);
188 mv = Hp - SIZEOF_StgMutVar + WDS(1);
189 SET_HDR(mv,stg_MUT_VAR_DIRTY_info,W_[CCCS]);
190 StgMutVar_var(mv) = R1;
195 atomicModifyMutVarzh_fast
197 W_ mv, f, z, x, y, r, h;
198 /* Args: R1 :: MutVar#, R2 :: a -> (a,b) */
200 /* If x is the current contents of the MutVar#, then
201 We want to make the new contents point to
205 and the return value is
209 obviously we can share (f x).
211 z = [stg_ap_2 f x] (max (HS + 2) MIN_UPD_SIZE)
212 y = [stg_sel_0 z] (max (HS + 1) MIN_UPD_SIZE)
213 r = [stg_sel_1 z] (max (HS + 1) MIN_UPD_SIZE)
217 #define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
218 #define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),WDS(MIN_UPD_SIZE-1))
220 #define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(1))
221 #define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),0)
225 #define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
226 #define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),WDS(MIN_UPD_SIZE-2))
228 #define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(2))
229 #define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),0)
232 #define SIZE (THUNK_2_SIZE + THUNK_1_SIZE + THUNK_1_SIZE)
234 HP_CHK_GEN_TICKY(SIZE, R1_PTR & R2_PTR, atomicModifyMutVarzh_fast);
239 TICK_ALLOC_THUNK_2();
240 CCCS_ALLOC(THUNK_2_SIZE);
241 z = Hp - THUNK_2_SIZE + WDS(1);
242 SET_HDR(z, stg_ap_2_upd_info, W_[CCCS]);
243 LDV_RECORD_CREATE(z);
244 StgThunk_payload(z,0) = f;
246 TICK_ALLOC_THUNK_1();
247 CCCS_ALLOC(THUNK_1_SIZE);
248 y = z - THUNK_1_SIZE;
249 SET_HDR(y, stg_sel_0_upd_info, W_[CCCS]);
250 LDV_RECORD_CREATE(y);
251 StgThunk_payload(y,0) = z;
253 TICK_ALLOC_THUNK_1();
254 CCCS_ALLOC(THUNK_1_SIZE);
255 r = y - THUNK_1_SIZE;
256 SET_HDR(r, stg_sel_1_upd_info, W_[CCCS]);
257 LDV_RECORD_CREATE(r);
258 StgThunk_payload(r,0) = z;
261 x = StgMutVar_var(mv);
262 StgThunk_payload(z,1) = x;
264 (h) = foreign "C" cas(mv + SIZEOF_StgHeader + OFFSET_StgMutVar_var, x, y) [];
265 if (h != x) { goto retry; }
267 StgMutVar_var(mv) = y;
270 if (GET_INFO(mv) == stg_MUT_VAR_CLEAN_info) {
271 foreign "C" dirty_MUT_VAR(BaseReg "ptr", mv "ptr") [];
277 /* -----------------------------------------------------------------------------
278 Weak Pointer Primitives
279 -------------------------------------------------------------------------- */
281 STRING(stg_weak_msg,"New weak pointer at %p\n")
287 R3 = finalizer (or NULL)
292 R3 = stg_NO_FINALIZER_closure;
295 ALLOC_PRIM( SIZEOF_StgWeak, R1_PTR & R2_PTR & R3_PTR, mkWeakzh_fast );
297 w = Hp - SIZEOF_StgWeak + WDS(1);
298 SET_HDR(w, stg_WEAK_info, W_[CCCS]);
301 StgWeak_value(w) = R2;
302 StgWeak_finalizer(w) = R3;
304 StgWeak_link(w) = W_[weak_ptr_list];
305 W_[weak_ptr_list] = w;
307 IF_DEBUG(weak, foreign "C" debugBelch(stg_weak_msg,w) []);
322 if (GET_INFO(w) == stg_DEAD_WEAK_info) {
323 RET_NP(0,stg_NO_FINALIZER_closure);
329 // A weak pointer is inherently used, so we do not need to call
330 // LDV_recordDead_FILL_SLOP_DYNAMIC():
331 // LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)w);
332 // or, LDV_recordDead():
333 // LDV_recordDead((StgClosure *)w, sizeofW(StgWeak) - sizeofW(StgProfHeader));
334 // Furthermore, when PROFILING is turned on, dead weak pointers are exactly as
335 // large as weak pointers, so there is no need to fill the slop, either.
336 // See stg_DEAD_WEAK_info in StgMiscClosures.hc.
340 // Todo: maybe use SET_HDR() and remove LDV_recordCreate()?
342 SET_INFO(w,stg_DEAD_WEAK_info);
343 LDV_RECORD_CREATE(w);
345 f = StgWeak_finalizer(w);
346 StgDeadWeak_link(w) = StgWeak_link(w);
348 /* return the finalizer */
349 if (f == stg_NO_FINALIZER_closure) {
350 RET_NP(0,stg_NO_FINALIZER_closure);
362 if (GET_INFO(w) == stg_WEAK_info) {
364 val = StgWeak_value(w);
372 /* -----------------------------------------------------------------------------
373 Arbitrary-precision Integer operations.
375 There are some assumptions in this code that mp_limb_t == W_. This is
376 the case for all the platforms that GHC supports, currently.
377 -------------------------------------------------------------------------- */
381 /* arguments: R1 = Int# */
383 W_ val, s, p; /* to avoid aliasing */
386 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, int2Integerzh_fast );
388 p = Hp - SIZEOF_StgArrWords;
389 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
390 StgArrWords_words(p) = 1;
392 /* mpz_set_si is inlined here, makes things simpler */
405 /* returns (# size :: Int#,
414 /* arguments: R1 = Word# */
416 W_ val, s, p; /* to avoid aliasing */
420 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, word2Integerzh_fast);
422 p = Hp - SIZEOF_StgArrWords;
423 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
424 StgArrWords_words(p) = 1;
433 /* returns (# size :: Int#,
434 data :: ByteArray# #)
441 * 'long long' primops for converting to/from Integers.
444 #ifdef SUPPORT_LONG_LONGS
446 int64ToIntegerzh_fast
448 /* arguments: L1 = Int64# */
451 W_ hi, lo, s, neg, words_needed, p;
456 hi = TO_W_(val >> 32);
459 if ( hi == 0 || (hi == 0xFFFFFFFF && lo != 0) ) {
460 // minimum is one word
466 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(words_needed),
467 NO_PTRS, int64ToIntegerzh_fast );
469 p = Hp - SIZEOF_StgArrWords - WDS(words_needed) + WDS(1);
470 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
471 StgArrWords_words(p) = words_needed;
483 if ( words_needed == 2 ) {
491 } else /* val==0 */ {
499 /* returns (# size :: Int#,
500 data :: ByteArray# #)
504 word64ToIntegerzh_fast
506 /* arguments: L1 = Word64# */
509 W_ hi, lo, s, words_needed, p;
512 hi = TO_W_(val >> 32);
521 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(words_needed),
522 NO_PTRS, word64ToIntegerzh_fast );
524 p = Hp - SIZEOF_StgArrWords - WDS(words_needed) + WDS(1);
525 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
526 StgArrWords_words(p) = words_needed;
536 } else /* val==0 */ {
541 /* returns (# size :: Int#,
542 data :: ByteArray# #)
549 #endif /* SUPPORT_LONG_LONGS */
551 /* ToDo: this is shockingly inefficient */
556 bits8 [SIZEOF_MP_INT];
561 bits8 [SIZEOF_MP_INT];
566 bits8 [SIZEOF_MP_INT];
571 bits8 [SIZEOF_MP_INT];
576 #define FETCH_MP_TEMP(X) \
578 X = BaseReg + (OFFSET_StgRegTable_r ## X);
580 #define FETCH_MP_TEMP(X) /* Nothing */
583 #define GMP_TAKE2_RET1(name,mp_fun) \
588 FETCH_MP_TEMP(mp_tmp1); \
589 FETCH_MP_TEMP(mp_tmp2); \
590 FETCH_MP_TEMP(mp_result1) \
591 FETCH_MP_TEMP(mp_result2); \
593 /* call doYouWantToGC() */ \
594 MAYBE_GC(R2_PTR & R4_PTR, name); \
601 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
602 MP_INT__mp_size(mp_tmp1) = (s1); \
603 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
604 MP_INT__mp_alloc(mp_tmp2) = W_TO_INT(StgArrWords_words(d2)); \
605 MP_INT__mp_size(mp_tmp2) = (s2); \
606 MP_INT__mp_d(mp_tmp2) = BYTE_ARR_CTS(d2); \
608 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
610 /* Perform the operation */ \
611 foreign "C" mp_fun(mp_result1 "ptr",mp_tmp1 "ptr",mp_tmp2 "ptr") []; \
613 RET_NP(TO_W_(MP_INT__mp_size(mp_result1)), \
614 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords); \
617 #define GMP_TAKE1_RET1(name,mp_fun) \
622 FETCH_MP_TEMP(mp_tmp1); \
623 FETCH_MP_TEMP(mp_result1) \
625 /* call doYouWantToGC() */ \
626 MAYBE_GC(R2_PTR, name); \
631 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
632 MP_INT__mp_size(mp_tmp1) = (s1); \
633 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
635 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
637 /* Perform the operation */ \
638 foreign "C" mp_fun(mp_result1 "ptr",mp_tmp1 "ptr") []; \
640 RET_NP(TO_W_(MP_INT__mp_size(mp_result1)), \
641 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords); \
644 #define GMP_TAKE2_RET2(name,mp_fun) \
649 FETCH_MP_TEMP(mp_tmp1); \
650 FETCH_MP_TEMP(mp_tmp2); \
651 FETCH_MP_TEMP(mp_result1) \
652 FETCH_MP_TEMP(mp_result2) \
654 /* call doYouWantToGC() */ \
655 MAYBE_GC(R2_PTR & R4_PTR, name); \
662 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
663 MP_INT__mp_size(mp_tmp1) = (s1); \
664 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
665 MP_INT__mp_alloc(mp_tmp2) = W_TO_INT(StgArrWords_words(d2)); \
666 MP_INT__mp_size(mp_tmp2) = (s2); \
667 MP_INT__mp_d(mp_tmp2) = BYTE_ARR_CTS(d2); \
669 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
670 foreign "C" __gmpz_init(mp_result2 "ptr") []; \
672 /* Perform the operation */ \
673 foreign "C" mp_fun(mp_result1 "ptr",mp_result2 "ptr",mp_tmp1 "ptr",mp_tmp2 "ptr") []; \
675 RET_NPNP(TO_W_(MP_INT__mp_size(mp_result1)), \
676 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords, \
677 TO_W_(MP_INT__mp_size(mp_result2)), \
678 MP_INT__mp_d(mp_result2) - SIZEOF_StgArrWords); \
681 GMP_TAKE2_RET1(plusIntegerzh_fast, __gmpz_add)
682 GMP_TAKE2_RET1(minusIntegerzh_fast, __gmpz_sub)
683 GMP_TAKE2_RET1(timesIntegerzh_fast, __gmpz_mul)
684 GMP_TAKE2_RET1(gcdIntegerzh_fast, __gmpz_gcd)
685 GMP_TAKE2_RET1(quotIntegerzh_fast, __gmpz_tdiv_q)
686 GMP_TAKE2_RET1(remIntegerzh_fast, __gmpz_tdiv_r)
687 GMP_TAKE2_RET1(divExactIntegerzh_fast, __gmpz_divexact)
688 GMP_TAKE2_RET1(andIntegerzh_fast, __gmpz_and)
689 GMP_TAKE2_RET1(orIntegerzh_fast, __gmpz_ior)
690 GMP_TAKE2_RET1(xorIntegerzh_fast, __gmpz_xor)
691 GMP_TAKE1_RET1(complementIntegerzh_fast, __gmpz_com)
693 GMP_TAKE2_RET2(quotRemIntegerzh_fast, __gmpz_tdiv_qr)
694 GMP_TAKE2_RET2(divModIntegerzh_fast, __gmpz_fdiv_qr)
698 mp_tmp_w: W_; // NB. mp_tmp_w is really an here mp_limb_t
704 /* R1 = the first Int#; R2 = the second Int# */
706 FETCH_MP_TEMP(mp_tmp_w);
709 (r) = foreign "C" __gmpn_gcd_1(mp_tmp_w "ptr", 1, R2) [];
712 /* Result parked in R1, return via info-pointer at TOS */
713 jump %ENTRY_CODE(Sp(0));
719 /* R1 = s1; R2 = d1; R3 = the int */
721 (s1) = foreign "C" __gmpn_gcd_1( BYTE_ARR_CTS(R2) "ptr", R1, R3) [];
724 /* Result parked in R1, return via info-pointer at TOS */
725 jump %ENTRY_CODE(Sp(0));
731 /* R1 = s1; R2 = d1; R3 = the int */
732 W_ usize, vsize, v_digit, u_digit;
738 // paraphrased from __gmpz_cmp_si() in the GMP sources
739 if (%gt(v_digit,0)) {
742 if (%lt(v_digit,0)) {
748 if (usize != vsize) {
750 jump %ENTRY_CODE(Sp(0));
755 jump %ENTRY_CODE(Sp(0));
758 u_digit = W_[BYTE_ARR_CTS(R2)];
760 if (u_digit == v_digit) {
762 jump %ENTRY_CODE(Sp(0));
765 if (%gtu(u_digit,v_digit)) { // NB. unsigned: these are mp_limb_t's
771 jump %ENTRY_CODE(Sp(0));
776 /* R1 = s1; R2 = d1; R3 = s2; R4 = d2 */
777 W_ usize, vsize, size, up, vp;
780 // paraphrased from __gmpz_cmp() in the GMP sources
784 if (usize != vsize) {
786 jump %ENTRY_CODE(Sp(0));
791 jump %ENTRY_CODE(Sp(0));
794 if (%lt(usize,0)) { // NB. not <, which is unsigned
800 up = BYTE_ARR_CTS(R2);
801 vp = BYTE_ARR_CTS(R4);
803 (cmp) = foreign "C" __gmpn_cmp(up "ptr", vp "ptr", size) [];
805 if (cmp == 0 :: CInt) {
807 jump %ENTRY_CODE(Sp(0));
810 if (%lt(cmp,0 :: CInt) == %lt(usize,0)) {
815 /* Result parked in R1, return via info-pointer at TOS */
816 jump %ENTRY_CODE(Sp(0));
828 r = W_[R2 + SIZEOF_StgArrWords];
833 /* Result parked in R1, return via info-pointer at TOS */
835 jump %ENTRY_CODE(Sp(0));
847 r = W_[R2 + SIZEOF_StgArrWords];
852 /* Result parked in R1, return via info-pointer at TOS */
854 jump %ENTRY_CODE(Sp(0));
861 FETCH_MP_TEMP(mp_tmp1);
862 FETCH_MP_TEMP(mp_tmp_w);
864 /* arguments: F1 = Float# */
867 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, decodeFloatzh_fast );
869 /* Be prepared to tell Lennart-coded __decodeFloat
870 where mantissa._mp_d can be put (it does not care about the rest) */
871 p = Hp - SIZEOF_StgArrWords;
872 SET_HDR(p,stg_ARR_WORDS_info,W_[CCCS]);
873 StgArrWords_words(p) = 1;
874 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(p);
876 /* Perform the operation */
877 foreign "C" __decodeFloat(mp_tmp1 "ptr",mp_tmp_w "ptr" ,arg) [];
879 /* returns: (Int# (expn), Int#, ByteArray#) */
880 RET_NNP(W_[mp_tmp_w], TO_W_(MP_INT__mp_size(mp_tmp1)), p);
883 decodeFloatzuIntzh_fast
887 FETCH_MP_TEMP(mp_tmp1);
888 FETCH_MP_TEMP(mp_tmp_w);
890 /* arguments: F1 = Float# */
893 /* Perform the operation */
894 foreign "C" __decodeFloat_Int(mp_tmp1 "ptr", mp_tmp_w "ptr", arg) [];
896 /* returns: (Int# (mantissa), Int# (exponent)) */
897 RET_NN(W_[mp_tmp1], W_[mp_tmp_w]);
900 #define DOUBLE_MANTISSA_SIZE SIZEOF_DOUBLE
901 #define ARR_SIZE (SIZEOF_StgArrWords + DOUBLE_MANTISSA_SIZE)
907 FETCH_MP_TEMP(mp_tmp1);
908 FETCH_MP_TEMP(mp_tmp_w);
910 /* arguments: D1 = Double# */
913 ALLOC_PRIM( ARR_SIZE, NO_PTRS, decodeDoublezh_fast );
915 /* Be prepared to tell Lennart-coded __decodeDouble
916 where mantissa.d can be put (it does not care about the rest) */
917 p = Hp - ARR_SIZE + WDS(1);
918 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
919 StgArrWords_words(p) = BYTES_TO_WDS(DOUBLE_MANTISSA_SIZE);
920 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(p);
922 /* Perform the operation */
923 foreign "C" __decodeDouble(mp_tmp1 "ptr", mp_tmp_w "ptr",arg) [];
925 /* returns: (Int# (expn), Int#, ByteArray#) */
926 RET_NNP(W_[mp_tmp_w], TO_W_(MP_INT__mp_size(mp_tmp1)), p);
929 decodeDoublezu2Intzh_fast
933 FETCH_MP_TEMP(mp_tmp1);
934 FETCH_MP_TEMP(mp_tmp2);
935 FETCH_MP_TEMP(mp_result1);
936 FETCH_MP_TEMP(mp_result2);
938 /* arguments: D1 = Double# */
941 /* Perform the operation */
942 foreign "C" __decodeDouble_2Int(mp_tmp1 "ptr", mp_tmp2 "ptr",
943 mp_result1 "ptr", mp_result2 "ptr",
947 (Int# (mant sign), Word# (mant high), Word# (mant low), Int# (expn)) */
948 RET_NNNN(W_[mp_tmp1], W_[mp_tmp2], W_[mp_result1], W_[mp_result2]);
951 /* -----------------------------------------------------------------------------
952 * Concurrency primitives
953 * -------------------------------------------------------------------------- */
957 /* args: R1 = closure to spark */
959 MAYBE_GC(R1_PTR, forkzh_fast);
965 ("ptr" threadid) = foreign "C" createIOThread( MyCapability() "ptr",
966 RtsFlags_GcFlags_initialStkSize(RtsFlags),
969 /* start blocked if the current thread is blocked */
970 StgTSO_flags(threadid) =
971 StgTSO_flags(threadid) | (StgTSO_flags(CurrentTSO) &
972 (TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32));
974 foreign "C" scheduleThread(MyCapability() "ptr", threadid "ptr") [];
976 // switch at the earliest opportunity
977 Capability_context_switch(MyCapability()) = 1 :: CInt;
984 /* args: R1 = cpu, R2 = closure to spark */
986 MAYBE_GC(R2_PTR, forkOnzh_fast);
994 ("ptr" threadid) = foreign "C" createIOThread( MyCapability() "ptr",
995 RtsFlags_GcFlags_initialStkSize(RtsFlags),
998 /* start blocked if the current thread is blocked */
999 StgTSO_flags(threadid) =
1000 StgTSO_flags(threadid) | (StgTSO_flags(CurrentTSO) &
1001 (TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32));
1003 foreign "C" scheduleThreadOn(MyCapability() "ptr", cpu, threadid "ptr") [];
1005 // switch at the earliest opportunity
1006 Capability_context_switch(MyCapability()) = 1 :: CInt;
1013 jump stg_yield_noregs;
1028 foreign "C" labelThread(R1 "ptr", R2 "ptr") [];
1030 jump %ENTRY_CODE(Sp(0));
1033 isCurrentThreadBoundzh_fast
1037 (r) = foreign "C" isThreadBound(CurrentTSO) [];
1043 /* args: R1 :: ThreadId# */
1051 if (TO_W_(StgTSO_what_next(tso)) == ThreadRelocated) {
1052 tso = StgTSO__link(tso);
1056 what_next = TO_W_(StgTSO_what_next(tso));
1057 why_blocked = TO_W_(StgTSO_why_blocked(tso));
1058 // Note: these two reads are not atomic, so they might end up
1059 // being inconsistent. It doesn't matter, since we
1060 // only return one or the other. If we wanted to return the
1061 // contents of block_info too, then we'd have to do some synchronisation.
1063 if (what_next == ThreadComplete) {
1064 ret = 16; // NB. magic, matches up with GHC.Conc.threadStatus
1066 if (what_next == ThreadKilled) {
1075 /* -----------------------------------------------------------------------------
1077 * -------------------------------------------------------------------------- */
1081 // Catch retry frame ------------------------------------------------------------
1083 INFO_TABLE_RET(stg_catch_retry_frame, CATCH_RETRY_FRAME,
1084 #if defined(PROFILING)
1085 W_ unused1, W_ unused2,
1087 W_ unused3, P_ unused4, P_ unused5)
1089 W_ r, frame, trec, outer;
1092 trec = StgTSO_trec(CurrentTSO);
1093 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1094 (r) = foreign "C" stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr") [];
1096 /* Succeeded (either first branch or second branch) */
1097 StgTSO_trec(CurrentTSO) = outer;
1098 Sp = Sp + SIZEOF_StgCatchRetryFrame;
1099 jump %ENTRY_CODE(Sp(SP_OFF));
1101 /* Did not commit: re-execute */
1103 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1104 StgTSO_trec(CurrentTSO) = new_trec;
1105 if (StgCatchRetryFrame_running_alt_code(frame) != 0::I32) {
1106 R1 = StgCatchRetryFrame_alt_code(frame);
1108 R1 = StgCatchRetryFrame_first_code(frame);
1115 // Atomically frame ------------------------------------------------------------
1117 INFO_TABLE_RET(stg_atomically_frame, ATOMICALLY_FRAME,
1118 #if defined(PROFILING)
1119 W_ unused1, W_ unused2,
1121 P_ unused3, P_ unused4)
1123 W_ frame, trec, valid, next_invariant, q, outer;
1126 trec = StgTSO_trec(CurrentTSO);
1127 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1129 if (outer == NO_TREC) {
1130 /* First time back at the atomically frame -- pick up invariants */
1131 ("ptr" q) = foreign "C" stmGetInvariantsToCheck(MyCapability() "ptr", trec "ptr") [];
1132 StgAtomicallyFrame_next_invariant_to_check(frame) = q;
1135 /* Second/subsequent time back at the atomically frame -- abort the
1136 * tx that's checking the invariant and move on to the next one */
1137 StgTSO_trec(CurrentTSO) = outer;
1138 q = StgAtomicallyFrame_next_invariant_to_check(frame);
1139 StgInvariantCheckQueue_my_execution(q) = trec;
1140 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1141 /* Don't free trec -- it's linked from q and will be stashed in the
1142 * invariant if we eventually commit. */
1143 q = StgInvariantCheckQueue_next_queue_entry(q);
1144 StgAtomicallyFrame_next_invariant_to_check(frame) = q;
1148 q = StgAtomicallyFrame_next_invariant_to_check(frame);
1150 if (q != END_INVARIANT_CHECK_QUEUE) {
1151 /* We can't commit yet: another invariant to check */
1152 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", trec "ptr") [];
1153 StgTSO_trec(CurrentTSO) = trec;
1155 next_invariant = StgInvariantCheckQueue_invariant(q);
1156 R1 = StgAtomicInvariant_code(next_invariant);
1161 /* We've got no more invariants to check, try to commit */
1162 (valid) = foreign "C" stmCommitTransaction(MyCapability() "ptr", trec "ptr") [];
1164 /* Transaction was valid: commit succeeded */
1165 StgTSO_trec(CurrentTSO) = NO_TREC;
1166 Sp = Sp + SIZEOF_StgAtomicallyFrame;
1167 jump %ENTRY_CODE(Sp(SP_OFF));
1169 /* Transaction was not valid: try again */
1170 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
1171 StgTSO_trec(CurrentTSO) = trec;
1172 StgAtomicallyFrame_next_invariant_to_check(frame) = END_INVARIANT_CHECK_QUEUE;
1173 R1 = StgAtomicallyFrame_code(frame);
1179 INFO_TABLE_RET(stg_atomically_waiting_frame, ATOMICALLY_FRAME,
1180 #if defined(PROFILING)
1181 W_ unused1, W_ unused2,
1183 P_ unused3, P_ unused4)
1185 W_ frame, trec, valid;
1189 /* The TSO is currently waiting: should we stop waiting? */
1190 (valid) = foreign "C" stmReWait(MyCapability() "ptr", CurrentTSO "ptr") [];
1192 /* Previous attempt is still valid: no point trying again yet */
1193 jump stg_block_noregs;
1195 /* Previous attempt is no longer valid: try again */
1196 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
1197 StgTSO_trec(CurrentTSO) = trec;
1198 StgHeader_info(frame) = stg_atomically_frame_info;
1199 R1 = StgAtomicallyFrame_code(frame);
1204 // STM catch frame --------------------------------------------------------------
1208 /* Catch frames are very similar to update frames, but when entering
1209 * one we just pop the frame off the stack and perform the correct
1210 * kind of return to the activation record underneath us on the stack.
1213 INFO_TABLE_RET(stg_catch_stm_frame, CATCH_STM_FRAME,
1214 #if defined(PROFILING)
1215 W_ unused1, W_ unused2,
1217 P_ unused3, P_ unused4)
1219 W_ r, frame, trec, outer;
1221 trec = StgTSO_trec(CurrentTSO);
1222 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1223 (r) = foreign "C" stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr") [];
1225 /* Commit succeeded */
1226 StgTSO_trec(CurrentTSO) = outer;
1227 Sp = Sp + SIZEOF_StgCatchSTMFrame;
1232 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1233 StgTSO_trec(CurrentTSO) = new_trec;
1234 R1 = StgCatchSTMFrame_code(frame);
1240 // Primop definition ------------------------------------------------------------
1248 // stmStartTransaction may allocate
1249 MAYBE_GC (R1_PTR, atomicallyzh_fast);
1251 /* Args: R1 = m :: STM a */
1252 STK_CHK_GEN(SIZEOF_StgAtomicallyFrame + WDS(1), R1_PTR, atomicallyzh_fast);
1254 old_trec = StgTSO_trec(CurrentTSO);
1256 /* Nested transactions are not allowed; raise an exception */
1257 if (old_trec != NO_TREC) {
1258 R1 = base_ControlziExceptionziBase_nestedAtomically_closure;
1262 /* Set up the atomically frame */
1263 Sp = Sp - SIZEOF_StgAtomicallyFrame;
1266 SET_HDR(frame,stg_atomically_frame_info, W_[CCCS]);
1267 StgAtomicallyFrame_code(frame) = R1;
1268 StgAtomicallyFrame_next_invariant_to_check(frame) = END_INVARIANT_CHECK_QUEUE;
1270 /* Start the memory transcation */
1271 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", old_trec "ptr") [R1];
1272 StgTSO_trec(CurrentTSO) = new_trec;
1274 /* Apply R1 to the realworld token */
1283 /* Args: R1 :: STM a */
1284 /* Args: R2 :: Exception -> STM a */
1285 STK_CHK_GEN(SIZEOF_StgCatchSTMFrame + WDS(1), R1_PTR & R2_PTR, catchSTMzh_fast);
1287 /* Set up the catch frame */
1288 Sp = Sp - SIZEOF_StgCatchSTMFrame;
1291 SET_HDR(frame, stg_catch_stm_frame_info, W_[CCCS]);
1292 StgCatchSTMFrame_handler(frame) = R2;
1293 StgCatchSTMFrame_code(frame) = R1;
1295 /* Start a nested transaction to run the body of the try block in */
1298 cur_trec = StgTSO_trec(CurrentTSO);
1299 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", cur_trec "ptr");
1300 StgTSO_trec(CurrentTSO) = new_trec;
1302 /* Apply R1 to the realworld token */
1313 // stmStartTransaction may allocate
1314 MAYBE_GC (R1_PTR & R2_PTR, catchRetryzh_fast);
1316 /* Args: R1 :: STM a */
1317 /* Args: R2 :: STM a */
1318 STK_CHK_GEN(SIZEOF_StgCatchRetryFrame + WDS(1), R1_PTR & R2_PTR, catchRetryzh_fast);
1320 /* Start a nested transaction within which to run the first code */
1321 trec = StgTSO_trec(CurrentTSO);
1322 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", trec "ptr") [R1,R2];
1323 StgTSO_trec(CurrentTSO) = new_trec;
1325 /* Set up the catch-retry frame */
1326 Sp = Sp - SIZEOF_StgCatchRetryFrame;
1329 SET_HDR(frame, stg_catch_retry_frame_info, W_[CCCS]);
1330 StgCatchRetryFrame_running_alt_code(frame) = 0 :: CInt; // false;
1331 StgCatchRetryFrame_first_code(frame) = R1;
1332 StgCatchRetryFrame_alt_code(frame) = R2;
1334 /* Apply R1 to the realworld token */
1347 MAYBE_GC (NO_PTRS, retryzh_fast); // STM operations may allocate
1349 // Find the enclosing ATOMICALLY_FRAME or CATCH_RETRY_FRAME
1351 StgTSO_sp(CurrentTSO) = Sp;
1352 (frame_type) = foreign "C" findRetryFrameHelper(CurrentTSO "ptr") [];
1353 Sp = StgTSO_sp(CurrentTSO);
1355 trec = StgTSO_trec(CurrentTSO);
1356 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1358 if (frame_type == CATCH_RETRY_FRAME) {
1359 // The retry reaches a CATCH_RETRY_FRAME before the atomic frame
1360 ASSERT(outer != NO_TREC);
1361 // Abort the transaction attempting the current branch
1362 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1363 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
1364 if (!StgCatchRetryFrame_running_alt_code(frame) != 0::I32) {
1365 // Retry in the first branch: try the alternative
1366 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1367 StgTSO_trec(CurrentTSO) = trec;
1368 StgCatchRetryFrame_running_alt_code(frame) = 1 :: CInt; // true;
1369 R1 = StgCatchRetryFrame_alt_code(frame);
1372 // Retry in the alternative code: propagate the retry
1373 StgTSO_trec(CurrentTSO) = outer;
1374 Sp = Sp + SIZEOF_StgCatchRetryFrame;
1375 goto retry_pop_stack;
1379 // We've reached the ATOMICALLY_FRAME: attempt to wait
1380 ASSERT(frame_type == ATOMICALLY_FRAME);
1381 if (outer != NO_TREC) {
1382 // We called retry while checking invariants, so abort the current
1383 // invariant check (merging its TVar accesses into the parents read
1384 // set so we'll wait on them)
1385 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1386 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
1388 StgTSO_trec(CurrentTSO) = trec;
1389 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1391 ASSERT(outer == NO_TREC);
1393 (r) = foreign "C" stmWait(MyCapability() "ptr", CurrentTSO "ptr", trec "ptr") [];
1395 // Transaction was valid: stmWait put us on the TVars' queues, we now block
1396 StgHeader_info(frame) = stg_atomically_waiting_frame_info;
1398 // Fix up the stack in the unregisterised case: the return convention is different.
1399 R3 = trec; // passing to stmWaitUnblock()
1400 jump stg_block_stmwait;
1402 // Transaction was not valid: retry immediately
1403 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1404 StgTSO_trec(CurrentTSO) = trec;
1405 R1 = StgAtomicallyFrame_code(frame);
1416 /* Args: R1 = invariant closure */
1417 MAYBE_GC (R1_PTR, checkzh_fast);
1419 trec = StgTSO_trec(CurrentTSO);
1421 foreign "C" stmAddInvariantToCheck(MyCapability() "ptr",
1425 jump %ENTRY_CODE(Sp(0));
1434 /* Args: R1 = initialisation value */
1436 MAYBE_GC (R1_PTR, newTVarzh_fast);
1438 ("ptr" tv) = foreign "C" stmNewTVar(MyCapability() "ptr", new_value "ptr") [];
1449 /* Args: R1 = TVar closure */
1451 MAYBE_GC (R1_PTR, readTVarzh_fast); // Call to stmReadTVar may allocate
1452 trec = StgTSO_trec(CurrentTSO);
1454 ("ptr" result) = foreign "C" stmReadTVar(MyCapability() "ptr", trec "ptr", tvar "ptr") [];
1464 result = StgTVar_current_value(R1);
1465 if (%INFO_PTR(result) == stg_TREC_HEADER_info) {
1477 /* Args: R1 = TVar closure */
1478 /* R2 = New value */
1480 MAYBE_GC (R1_PTR & R2_PTR, writeTVarzh_fast); // Call to stmWriteTVar may allocate
1481 trec = StgTSO_trec(CurrentTSO);
1484 foreign "C" stmWriteTVar(MyCapability() "ptr", trec "ptr", tvar "ptr", new_value "ptr") [];
1486 jump %ENTRY_CODE(Sp(0));
1490 /* -----------------------------------------------------------------------------
1493 * take & putMVar work as follows. Firstly, an important invariant:
1495 * If the MVar is full, then the blocking queue contains only
1496 * threads blocked on putMVar, and if the MVar is empty then the
1497 * blocking queue contains only threads blocked on takeMVar.
1500 * MVar empty : then add ourselves to the blocking queue
1501 * MVar full : remove the value from the MVar, and
1502 * blocking queue empty : return
1503 * blocking queue non-empty : perform the first blocked putMVar
1504 * from the queue, and wake up the
1505 * thread (MVar is now full again)
1507 * putMVar is just the dual of the above algorithm.
1509 * How do we "perform a putMVar"? Well, we have to fiddle around with
1510 * the stack of the thread waiting to do the putMVar. See
1511 * stg_block_putmvar and stg_block_takemvar in HeapStackCheck.c for
1512 * the stack layout, and the PerformPut and PerformTake macros below.
1514 * It is important that a blocked take or put is woken up with the
1515 * take/put already performed, because otherwise there would be a
1516 * small window of vulnerability where the thread could receive an
1517 * exception and never perform its take or put, and we'd end up with a
1520 * -------------------------------------------------------------------------- */
1524 /* args: R1 = MVar closure */
1526 if (StgMVar_value(R1) == stg_END_TSO_QUEUE_closure) {
1538 ALLOC_PRIM ( SIZEOF_StgMVar, NO_PTRS, newMVarzh_fast );
1540 mvar = Hp - SIZEOF_StgMVar + WDS(1);
1541 SET_HDR(mvar,stg_MVAR_DIRTY_info,W_[CCCS]);
1542 // MVARs start dirty: generation 0 has no mutable list
1543 StgMVar_head(mvar) = stg_END_TSO_QUEUE_closure;
1544 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1545 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1550 #define PerformTake(tso, value) \
1551 W_[StgTSO_sp(tso) + WDS(1)] = value; \
1552 W_[StgTSO_sp(tso) + WDS(0)] = stg_gc_unpt_r1_info;
1554 #define PerformPut(tso,lval) \
1555 StgTSO_sp(tso) = StgTSO_sp(tso) + WDS(3); \
1556 lval = W_[StgTSO_sp(tso) - WDS(1)];
1560 W_ mvar, val, info, tso;
1562 /* args: R1 = MVar closure */
1565 #if defined(THREADED_RTS)
1566 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1568 info = GET_INFO(mvar);
1571 if (info == stg_MVAR_CLEAN_info) {
1572 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr") [];
1575 /* If the MVar is empty, put ourselves on its blocking queue,
1576 * and wait until we're woken up.
1578 if (StgMVar_value(mvar) == stg_END_TSO_QUEUE_closure) {
1579 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1580 StgMVar_head(mvar) = CurrentTSO;
1582 foreign "C" setTSOLink(MyCapability() "ptr",
1583 StgMVar_tail(mvar) "ptr",
1586 StgTSO__link(CurrentTSO) = stg_END_TSO_QUEUE_closure;
1587 StgTSO_why_blocked(CurrentTSO) = BlockedOnMVar::I16;
1588 StgTSO_block_info(CurrentTSO) = mvar;
1589 StgMVar_tail(mvar) = CurrentTSO;
1592 jump stg_block_takemvar;
1595 /* we got the value... */
1596 val = StgMVar_value(mvar);
1598 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure)
1600 /* There are putMVar(s) waiting...
1601 * wake up the first thread on the queue
1603 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1605 /* actually perform the putMVar for the thread that we just woke up */
1606 tso = StgMVar_head(mvar);
1607 PerformPut(tso,StgMVar_value(mvar));
1609 if (TO_W_(StgTSO_flags(tso)) & TSO_DIRTY == 0) {
1610 foreign "C" dirty_TSO(MyCapability() "ptr", tso "ptr") [];
1613 ("ptr" tso) = foreign "C" unblockOne_(MyCapability() "ptr",
1614 StgMVar_head(mvar) "ptr", 1) [];
1615 StgMVar_head(mvar) = tso;
1617 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1618 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1621 #if defined(THREADED_RTS)
1622 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1624 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1630 /* No further putMVars, MVar is now empty */
1631 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1633 #if defined(THREADED_RTS)
1634 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1636 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1646 W_ mvar, val, info, tso;
1648 /* args: R1 = MVar closure */
1652 #if defined(THREADED_RTS)
1653 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1655 info = GET_INFO(mvar);
1658 if (StgMVar_value(mvar) == stg_END_TSO_QUEUE_closure) {
1659 #if defined(THREADED_RTS)
1660 unlockClosure(mvar, info);
1662 /* HACK: we need a pointer to pass back,
1663 * so we abuse NO_FINALIZER_closure
1665 RET_NP(0, stg_NO_FINALIZER_closure);
1668 if (info == stg_MVAR_CLEAN_info) {
1669 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr");
1672 /* we got the value... */
1673 val = StgMVar_value(mvar);
1675 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1677 /* There are putMVar(s) waiting...
1678 * wake up the first thread on the queue
1680 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1682 /* actually perform the putMVar for the thread that we just woke up */
1683 tso = StgMVar_head(mvar);
1684 PerformPut(tso,StgMVar_value(mvar));
1685 if (TO_W_(StgTSO_flags(tso)) & TSO_DIRTY == 0) {
1686 foreign "C" dirty_TSO(MyCapability() "ptr", tso "ptr") [];
1689 ("ptr" tso) = foreign "C" unblockOne_(MyCapability() "ptr",
1690 StgMVar_head(mvar) "ptr", 1) [];
1691 StgMVar_head(mvar) = tso;
1693 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1694 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1696 #if defined(THREADED_RTS)
1697 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1699 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1704 /* No further putMVars, MVar is now empty */
1705 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1706 #if defined(THREADED_RTS)
1707 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1709 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1719 W_ mvar, val, info, tso;
1721 /* args: R1 = MVar, R2 = value */
1725 #if defined(THREADED_RTS)
1726 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1728 info = GET_INFO(mvar);
1731 if (info == stg_MVAR_CLEAN_info) {
1732 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr");
1735 if (StgMVar_value(mvar) != stg_END_TSO_QUEUE_closure) {
1736 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1737 StgMVar_head(mvar) = CurrentTSO;
1739 foreign "C" setTSOLink(MyCapability() "ptr",
1740 StgMVar_tail(mvar) "ptr",
1743 StgTSO__link(CurrentTSO) = stg_END_TSO_QUEUE_closure;
1744 StgTSO_why_blocked(CurrentTSO) = BlockedOnMVar::I16;
1745 StgTSO_block_info(CurrentTSO) = mvar;
1746 StgMVar_tail(mvar) = CurrentTSO;
1750 jump stg_block_putmvar;
1753 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1755 /* There are takeMVar(s) waiting: wake up the first one
1757 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1759 /* actually perform the takeMVar */
1760 tso = StgMVar_head(mvar);
1761 PerformTake(tso, val);
1762 if (TO_W_(StgTSO_flags(tso)) & TSO_DIRTY == 0) {
1763 foreign "C" dirty_TSO(MyCapability() "ptr", tso "ptr") [];
1766 ("ptr" tso) = foreign "C" unblockOne_(MyCapability() "ptr",
1767 StgMVar_head(mvar) "ptr", 1) [];
1768 StgMVar_head(mvar) = tso;
1770 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1771 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1774 #if defined(THREADED_RTS)
1775 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1777 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1779 jump %ENTRY_CODE(Sp(0));
1783 /* No further takes, the MVar is now full. */
1784 StgMVar_value(mvar) = val;
1786 #if defined(THREADED_RTS)
1787 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1789 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1791 jump %ENTRY_CODE(Sp(0));
1794 /* ToDo: yield afterward for better communication performance? */
1802 /* args: R1 = MVar, R2 = value */
1805 #if defined(THREADED_RTS)
1806 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [R2];
1808 info = GET_INFO(mvar);
1811 if (StgMVar_value(mvar) != stg_END_TSO_QUEUE_closure) {
1812 #if defined(THREADED_RTS)
1813 unlockClosure(mvar, info);
1818 if (info == stg_MVAR_CLEAN_info) {
1819 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr");
1822 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1824 /* There are takeMVar(s) waiting: wake up the first one
1826 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1828 /* actually perform the takeMVar */
1829 tso = StgMVar_head(mvar);
1830 PerformTake(tso, R2);
1831 if (TO_W_(StgTSO_flags(tso)) & TSO_DIRTY == 0) {
1832 foreign "C" dirty_TSO(MyCapability() "ptr", tso "ptr") [];
1835 ("ptr" tso) = foreign "C" unblockOne_(MyCapability() "ptr",
1836 StgMVar_head(mvar) "ptr", 1) [];
1837 StgMVar_head(mvar) = tso;
1839 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1840 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1843 #if defined(THREADED_RTS)
1844 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1846 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1851 /* No further takes, the MVar is now full. */
1852 StgMVar_value(mvar) = R2;
1854 #if defined(THREADED_RTS)
1855 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1857 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1862 /* ToDo: yield afterward for better communication performance? */
1866 /* -----------------------------------------------------------------------------
1867 Stable pointer primitives
1868 ------------------------------------------------------------------------- */
1870 makeStableNamezh_fast
1874 ALLOC_PRIM( SIZEOF_StgStableName, R1_PTR, makeStableNamezh_fast );
1876 (index) = foreign "C" lookupStableName(R1 "ptr") [];
1878 /* Is there already a StableName for this heap object?
1879 * stable_ptr_table is a pointer to an array of snEntry structs.
1881 if ( snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry) == NULL ) {
1882 sn_obj = Hp - SIZEOF_StgStableName + WDS(1);
1883 SET_HDR(sn_obj, stg_STABLE_NAME_info, W_[CCCS]);
1884 StgStableName_sn(sn_obj) = index;
1885 snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry) = sn_obj;
1887 sn_obj = snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry);
1894 makeStablePtrzh_fast
1898 MAYBE_GC(R1_PTR, makeStablePtrzh_fast);
1899 ("ptr" sp) = foreign "C" getStablePtr(R1 "ptr") [];
1903 deRefStablePtrzh_fast
1905 /* Args: R1 = the stable ptr */
1908 r = snEntry_addr(W_[stable_ptr_table] + sp*SIZEOF_snEntry);
1912 /* -----------------------------------------------------------------------------
1913 Bytecode object primitives
1914 ------------------------------------------------------------------------- */
1924 W_ bco, bitmap_arr, bytes, words;
1928 words = BYTES_TO_WDS(SIZEOF_StgBCO) + StgArrWords_words(bitmap_arr);
1931 ALLOC_PRIM( bytes, R1_PTR&R2_PTR&R3_PTR&R5_PTR, newBCOzh_fast );
1933 bco = Hp - bytes + WDS(1);
1934 SET_HDR(bco, stg_BCO_info, W_[CCCS]);
1936 StgBCO_instrs(bco) = R1;
1937 StgBCO_literals(bco) = R2;
1938 StgBCO_ptrs(bco) = R3;
1939 StgBCO_arity(bco) = HALF_W_(R4);
1940 StgBCO_size(bco) = HALF_W_(words);
1942 // Copy the arity/bitmap info into the BCO
1946 if (i < StgArrWords_words(bitmap_arr)) {
1947 StgBCO_bitmap(bco,i) = StgArrWords_payload(bitmap_arr,i);
1958 // R1 = the BCO# for the AP
1962 // This function is *only* used to wrap zero-arity BCOs in an
1963 // updatable wrapper (see ByteCodeLink.lhs). An AP thunk is always
1964 // saturated and always points directly to a FUN or BCO.
1965 ASSERT(%INFO_TYPE(%GET_STD_INFO(R1)) == HALF_W_(BCO) &&
1966 StgBCO_arity(R1) == HALF_W_(0));
1968 HP_CHK_GEN_TICKY(SIZEOF_StgAP, R1_PTR, mkApUpd0zh_fast);
1969 TICK_ALLOC_UP_THK(0, 0);
1970 CCCS_ALLOC(SIZEOF_StgAP);
1972 ap = Hp - SIZEOF_StgAP + WDS(1);
1973 SET_HDR(ap, stg_AP_info, W_[CCCS]);
1975 StgAP_n_args(ap) = HALF_W_(0);
1981 unpackClosurezh_fast
1983 /* args: R1 = closure to analyze */
1984 // TODO: Consider the absence of ptrs or nonptrs as a special case ?
1986 W_ info, ptrs, nptrs, p, ptrs_arr, nptrs_arr;
1987 info = %GET_STD_INFO(UNTAG(R1));
1989 // Some closures have non-standard layout, so we omit those here.
1991 type = TO_W_(%INFO_TYPE(info));
1992 switch [0 .. N_CLOSURE_TYPES] type {
1993 case THUNK_SELECTOR : {
1998 case THUNK, THUNK_1_0, THUNK_0_1, THUNK_2_0, THUNK_1_1,
1999 THUNK_0_2, THUNK_STATIC, AP, PAP, AP_STACK, BCO : {
2005 ptrs = TO_W_(%INFO_PTRS(info));
2006 nptrs = TO_W_(%INFO_NPTRS(info));
2011 W_ ptrs_arr_sz, nptrs_arr_sz;
2012 nptrs_arr_sz = SIZEOF_StgArrWords + WDS(nptrs);
2013 ptrs_arr_sz = SIZEOF_StgMutArrPtrs + WDS(ptrs);
2015 ALLOC_PRIM (ptrs_arr_sz + nptrs_arr_sz, R1_PTR, unpackClosurezh_fast);
2020 ptrs_arr = Hp - nptrs_arr_sz - ptrs_arr_sz + WDS(1);
2021 nptrs_arr = Hp - nptrs_arr_sz + WDS(1);
2023 SET_HDR(ptrs_arr, stg_MUT_ARR_PTRS_FROZEN_info, W_[CCCS]);
2024 StgMutArrPtrs_ptrs(ptrs_arr) = ptrs;
2028 W_[ptrs_arr + SIZEOF_StgMutArrPtrs + WDS(p)] = StgClosure_payload(clos,p);
2033 SET_HDR(nptrs_arr, stg_ARR_WORDS_info, W_[CCCS]);
2034 StgArrWords_words(nptrs_arr) = nptrs;
2038 W_[BYTE_ARR_CTS(nptrs_arr) + WDS(p)] = StgClosure_payload(clos, p+ptrs);
2042 RET_NPP(info, ptrs_arr, nptrs_arr);
2045 /* -----------------------------------------------------------------------------
2046 Thread I/O blocking primitives
2047 -------------------------------------------------------------------------- */
2049 /* Add a thread to the end of the blocked queue. (C-- version of the C
2050 * macro in Schedule.h).
2052 #define APPEND_TO_BLOCKED_QUEUE(tso) \
2053 ASSERT(StgTSO__link(tso) == END_TSO_QUEUE); \
2054 if (W_[blocked_queue_hd] == END_TSO_QUEUE) { \
2055 W_[blocked_queue_hd] = tso; \
2057 foreign "C" setTSOLink(MyCapability() "ptr", W_[blocked_queue_tl] "ptr", tso) []; \
2059 W_[blocked_queue_tl] = tso;
2065 foreign "C" barf("waitRead# on threaded RTS") never returns;
2068 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2069 StgTSO_why_blocked(CurrentTSO) = BlockedOnRead::I16;
2070 StgTSO_block_info(CurrentTSO) = R1;
2071 // No locking - we're not going to use this interface in the
2072 // threaded RTS anyway.
2073 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2074 jump stg_block_noregs;
2082 foreign "C" barf("waitWrite# on threaded RTS") never returns;
2085 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2086 StgTSO_why_blocked(CurrentTSO) = BlockedOnWrite::I16;
2087 StgTSO_block_info(CurrentTSO) = R1;
2088 // No locking - we're not going to use this interface in the
2089 // threaded RTS anyway.
2090 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2091 jump stg_block_noregs;
2096 STRING(stg_delayzh_malloc_str, "delayzh_fast")
2099 #ifdef mingw32_HOST_OS
2107 foreign "C" barf("delay# on threaded RTS") never returns;
2110 /* args: R1 (microsecond delay amount) */
2111 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2112 StgTSO_why_blocked(CurrentTSO) = BlockedOnDelay::I16;
2114 #ifdef mingw32_HOST_OS
2116 /* could probably allocate this on the heap instead */
2117 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2118 stg_delayzh_malloc_str);
2119 (reqID) = foreign "C" addDelayRequest(R1);
2120 StgAsyncIOResult_reqID(ares) = reqID;
2121 StgAsyncIOResult_len(ares) = 0;
2122 StgAsyncIOResult_errCode(ares) = 0;
2123 StgTSO_block_info(CurrentTSO) = ares;
2125 /* Having all async-blocked threads reside on the blocked_queue
2126 * simplifies matters, so change the status to OnDoProc put the
2127 * delayed thread on the blocked_queue.
2129 StgTSO_why_blocked(CurrentTSO) = BlockedOnDoProc::I16;
2130 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2131 jump stg_block_async_void;
2137 (time) = foreign "C" getourtimeofday() [R1];
2138 divisor = TO_W_(RtsFlags_MiscFlags_tickInterval(RtsFlags));
2142 divisor = divisor * 1000;
2143 target = ((R1 + divisor - 1) / divisor) /* divide rounding up */
2144 + time + 1; /* Add 1 as getourtimeofday rounds down */
2145 StgTSO_block_info(CurrentTSO) = target;
2147 /* Insert the new thread in the sleeping queue. */
2149 t = W_[sleeping_queue];
2151 if (t != END_TSO_QUEUE && StgTSO_block_info(t) < target) {
2153 t = StgTSO__link(t);
2157 StgTSO__link(CurrentTSO) = t;
2159 W_[sleeping_queue] = CurrentTSO;
2161 foreign "C" setTSOLink(MyCapability() "ptr", prev "ptr", CurrentTSO) [];
2163 jump stg_block_noregs;
2165 #endif /* !THREADED_RTS */
2169 #ifdef mingw32_HOST_OS
2170 STRING(stg_asyncReadzh_malloc_str, "asyncReadzh_fast")
2177 foreign "C" barf("asyncRead# on threaded RTS") never returns;
2180 /* args: R1 = fd, R2 = isSock, R3 = len, R4 = buf */
2181 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2182 StgTSO_why_blocked(CurrentTSO) = BlockedOnRead::I16;
2184 /* could probably allocate this on the heap instead */
2185 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2186 stg_asyncReadzh_malloc_str)
2188 (reqID) = foreign "C" addIORequest(R1, 0/*FALSE*/,R2,R3,R4 "ptr") [];
2189 StgAsyncIOResult_reqID(ares) = reqID;
2190 StgAsyncIOResult_len(ares) = 0;
2191 StgAsyncIOResult_errCode(ares) = 0;
2192 StgTSO_block_info(CurrentTSO) = ares;
2193 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2194 jump stg_block_async;
2198 STRING(stg_asyncWritezh_malloc_str, "asyncWritezh_fast")
2205 foreign "C" barf("asyncWrite# on threaded RTS") never returns;
2208 /* args: R1 = fd, R2 = isSock, R3 = len, R4 = buf */
2209 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2210 StgTSO_why_blocked(CurrentTSO) = BlockedOnWrite::I16;
2212 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2213 stg_asyncWritezh_malloc_str)
2215 (reqID) = foreign "C" addIORequest(R1, 1/*TRUE*/,R2,R3,R4 "ptr") [];
2217 StgAsyncIOResult_reqID(ares) = reqID;
2218 StgAsyncIOResult_len(ares) = 0;
2219 StgAsyncIOResult_errCode(ares) = 0;
2220 StgTSO_block_info(CurrentTSO) = ares;
2221 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2222 jump stg_block_async;
2226 STRING(stg_asyncDoProczh_malloc_str, "asyncDoProczh_fast")
2233 foreign "C" barf("asyncDoProc# on threaded RTS") never returns;
2236 /* args: R1 = proc, R2 = param */
2237 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2238 StgTSO_why_blocked(CurrentTSO) = BlockedOnDoProc::I16;
2240 /* could probably allocate this on the heap instead */
2241 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2242 stg_asyncDoProczh_malloc_str)
2244 (reqID) = foreign "C" addDoProcRequest(R1 "ptr",R2 "ptr") [];
2245 StgAsyncIOResult_reqID(ares) = reqID;
2246 StgAsyncIOResult_len(ares) = 0;
2247 StgAsyncIOResult_errCode(ares) = 0;
2248 StgTSO_block_info(CurrentTSO) = ares;
2249 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2250 jump stg_block_async;
2255 // noDuplicate# tries to ensure that none of the thunks under
2256 // evaluation by the current thread are also under evaluation by
2257 // another thread. It relies on *both* threads doing noDuplicate#;
2258 // the second one will get blocked if they are duplicating some work.
2261 SAVE_THREAD_STATE();
2262 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
2263 foreign "C" threadPaused (MyCapability() "ptr", CurrentTSO "ptr") [];
2265 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
2266 jump stg_threadFinished;
2268 LOAD_THREAD_STATE();
2269 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
2270 jump %ENTRY_CODE(Sp(0));
2274 getApStackValzh_fast
2276 W_ ap_stack, offset, val, ok;
2278 /* args: R1 = AP_STACK, R2 = offset */
2282 if (%INFO_PTR(ap_stack) == stg_AP_STACK_info) {
2284 val = StgAP_STACK_payload(ap_stack,offset);
2296 #ifndef THREADED_RTS
2297 RET_NP(0,ghczmprim_GHCziBool_False_closure);
2299 (spark) = foreign "C" findSpark(MyCapability());
2303 RET_NP(0,ghczmprim_GHCziBool_False_closure);