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 * ---------------------------------------------------------------------------*/
40 import __gmpz_tdiv_qr;
41 import __gmpz_fdiv_qr;
42 import __gmpz_divexact;
47 import base_GHCziIOBase_NestedAtomically_closure;
48 import pthread_mutex_lock;
49 import pthread_mutex_unlock;
51 import EnterCriticalSection;
52 import LeaveCriticalSection;
54 /*-----------------------------------------------------------------------------
57 Basically just new*Array - the others are all inline macros.
59 The size arg is always passed in R1, and the result returned in R1.
61 The slow entry point is for returning from a heap check, the saved
62 size argument must be re-loaded from the stack.
63 -------------------------------------------------------------------------- */
65 /* for objects that are *less* than the size of a word, make sure we
66 * round up to the nearest word for the size of the array.
71 W_ words, payload_words, n, p;
72 MAYBE_GC(NO_PTRS,newByteArrayzh_fast);
74 payload_words = ROUNDUP_BYTES_TO_WDS(n);
75 words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
76 ("ptr" p) = foreign "C" allocateLocal(MyCapability() "ptr",words) [];
77 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
78 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
79 StgArrWords_words(p) = payload_words;
83 newPinnedByteArrayzh_fast
85 W_ words, payload_words, n, p;
87 MAYBE_GC(NO_PTRS,newPinnedByteArrayzh_fast);
89 payload_words = ROUNDUP_BYTES_TO_WDS(n);
91 // We want an 8-byte aligned array. allocatePinned() gives us
92 // 8-byte aligned memory by default, but we want to align the
93 // *goods* inside the ArrWords object, so we have to check the
94 // size of the ArrWords header and adjust our size accordingly.
95 words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
96 if ((SIZEOF_StgArrWords & 7) != 0) {
100 ("ptr" p) = foreign "C" allocatePinned(words) [];
101 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
103 // Again, if the ArrWords header isn't a multiple of 8 bytes, we
104 // have to push the object forward one word so that the goods
105 // fall on an 8-byte boundary.
106 if ((SIZEOF_StgArrWords & 7) != 0) {
110 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
111 StgArrWords_words(p) = payload_words;
117 W_ words, n, init, arr, p;
118 /* Args: R1 = words, R2 = initialisation value */
121 MAYBE_GC(R2_PTR,newArrayzh_fast);
123 words = BYTES_TO_WDS(SIZEOF_StgMutArrPtrs) + n;
124 ("ptr" arr) = foreign "C" allocateLocal(MyCapability() "ptr",words) [R2];
125 TICK_ALLOC_PRIM(SIZEOF_StgMutArrPtrs, WDS(n), 0);
127 SET_HDR(arr, stg_MUT_ARR_PTRS_DIRTY_info, W_[CCCS]);
128 StgMutArrPtrs_ptrs(arr) = n;
130 // Initialise all elements of the the array with the value in R2
132 p = arr + SIZEOF_StgMutArrPtrs;
134 if (p < arr + WDS(words)) {
143 unsafeThawArrayzh_fast
145 // SUBTLETY TO DO WITH THE OLD GEN MUTABLE LIST
147 // A MUT_ARR_PTRS lives on the mutable list, but a MUT_ARR_PTRS_FROZEN
148 // normally doesn't. However, when we freeze a MUT_ARR_PTRS, we leave
149 // it on the mutable list for the GC to remove (removing something from
150 // the mutable list is not easy, because the mut_list is only singly-linked).
152 // So that we can tell whether a MUT_ARR_PTRS_FROZEN is on the mutable list,
153 // when we freeze it we set the info ptr to be MUT_ARR_PTRS_FROZEN0
154 // to indicate that it is still on the mutable list.
156 // So, when we thaw a MUT_ARR_PTRS_FROZEN, we must cope with two cases:
157 // either it is on a mut_list, or it isn't. We adopt the convention that
158 // the closure type is MUT_ARR_PTRS_FROZEN0 if it is on the mutable list,
159 // and MUT_ARR_PTRS_FROZEN otherwise. In fact it wouldn't matter if
160 // we put it on the mutable list more than once, but it would get scavenged
161 // multiple times during GC, which would be unnecessarily slow.
163 if (StgHeader_info(R1) != stg_MUT_ARR_PTRS_FROZEN0_info) {
164 SET_INFO(R1,stg_MUT_ARR_PTRS_DIRTY_info);
165 recordMutable(R1, R1);
166 // must be done after SET_INFO, because it ASSERTs closure_MUTABLE()
169 SET_INFO(R1,stg_MUT_ARR_PTRS_DIRTY_info);
174 /* -----------------------------------------------------------------------------
176 -------------------------------------------------------------------------- */
181 /* Args: R1 = initialisation value */
183 ALLOC_PRIM( SIZEOF_StgMutVar, R1_PTR, newMutVarzh_fast);
185 mv = Hp - SIZEOF_StgMutVar + WDS(1);
186 SET_HDR(mv,stg_MUT_VAR_DIRTY_info,W_[CCCS]);
187 StgMutVar_var(mv) = R1;
192 atomicModifyMutVarzh_fast
195 /* Args: R1 :: MutVar#, R2 :: a -> (a,b) */
197 /* If x is the current contents of the MutVar#, then
198 We want to make the new contents point to
202 and the return value is
206 obviously we can share (f x).
208 z = [stg_ap_2 f x] (max (HS + 2) MIN_UPD_SIZE)
209 y = [stg_sel_0 z] (max (HS + 1) MIN_UPD_SIZE)
210 r = [stg_sel_1 z] (max (HS + 1) MIN_UPD_SIZE)
214 #define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
215 #define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),WDS(MIN_UPD_SIZE-1))
217 #define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(1))
218 #define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),0)
222 #define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
223 #define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),WDS(MIN_UPD_SIZE-2))
225 #define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(2))
226 #define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),0)
229 #define SIZE (THUNK_2_SIZE + THUNK_1_SIZE + THUNK_1_SIZE)
231 HP_CHK_GEN_TICKY(SIZE, R1_PTR & R2_PTR, atomicModifyMutVarzh_fast);
233 #if defined(THREADED_RTS)
234 ACQUIRE_LOCK(atomic_modify_mutvar_mutex "ptr") [R1,R2];
237 x = StgMutVar_var(R1);
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) = R2;
245 StgThunk_payload(z,1) = x;
247 TICK_ALLOC_THUNK_1();
248 CCCS_ALLOC(THUNK_1_SIZE);
249 y = z - THUNK_1_SIZE;
250 SET_HDR(y, stg_sel_0_upd_info, W_[CCCS]);
251 LDV_RECORD_CREATE(y);
252 StgThunk_payload(y,0) = z;
254 StgMutVar_var(R1) = y;
255 foreign "C" dirty_MUT_VAR(BaseReg "ptr", R1 "ptr") [R1];
257 TICK_ALLOC_THUNK_1();
258 CCCS_ALLOC(THUNK_1_SIZE);
259 r = y - THUNK_1_SIZE;
260 SET_HDR(r, stg_sel_1_upd_info, W_[CCCS]);
261 LDV_RECORD_CREATE(r);
262 StgThunk_payload(r,0) = z;
264 #if defined(THREADED_RTS)
265 RELEASE_LOCK(atomic_modify_mutvar_mutex "ptr") [];
271 /* -----------------------------------------------------------------------------
272 Weak Pointer Primitives
273 -------------------------------------------------------------------------- */
275 STRING(stg_weak_msg,"New weak pointer at %p\n")
281 R3 = finalizer (or NULL)
286 R3 = stg_NO_FINALIZER_closure;
289 ALLOC_PRIM( SIZEOF_StgWeak, R1_PTR & R2_PTR & R3_PTR, mkWeakzh_fast );
291 w = Hp - SIZEOF_StgWeak + WDS(1);
292 SET_HDR(w, stg_WEAK_info, W_[CCCS]);
295 StgWeak_value(w) = R2;
296 StgWeak_finalizer(w) = R3;
298 StgWeak_link(w) = W_[weak_ptr_list];
299 W_[weak_ptr_list] = w;
301 IF_DEBUG(weak, foreign "C" debugBelch(stg_weak_msg,w) []);
316 if (GET_INFO(w) == stg_DEAD_WEAK_info) {
317 RET_NP(0,stg_NO_FINALIZER_closure);
323 // A weak pointer is inherently used, so we do not need to call
324 // LDV_recordDead_FILL_SLOP_DYNAMIC():
325 // LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)w);
326 // or, LDV_recordDead():
327 // LDV_recordDead((StgClosure *)w, sizeofW(StgWeak) - sizeofW(StgProfHeader));
328 // Furthermore, when PROFILING is turned on, dead weak pointers are exactly as
329 // large as weak pointers, so there is no need to fill the slop, either.
330 // See stg_DEAD_WEAK_info in StgMiscClosures.hc.
334 // Todo: maybe use SET_HDR() and remove LDV_recordCreate()?
336 SET_INFO(w,stg_DEAD_WEAK_info);
337 LDV_RECORD_CREATE(w);
339 f = StgWeak_finalizer(w);
340 StgDeadWeak_link(w) = StgWeak_link(w);
342 /* return the finalizer */
343 if (f == stg_NO_FINALIZER_closure) {
344 RET_NP(0,stg_NO_FINALIZER_closure);
356 if (GET_INFO(w) == stg_WEAK_info) {
358 val = StgWeak_value(w);
366 /* -----------------------------------------------------------------------------
367 Arbitrary-precision Integer operations.
369 There are some assumptions in this code that mp_limb_t == W_. This is
370 the case for all the platforms that GHC supports, currently.
371 -------------------------------------------------------------------------- */
375 /* arguments: R1 = Int# */
377 W_ val, s, p; /* to avoid aliasing */
380 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, int2Integerzh_fast );
382 p = Hp - SIZEOF_StgArrWords;
383 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
384 StgArrWords_words(p) = 1;
386 /* mpz_set_si is inlined here, makes things simpler */
399 /* returns (# size :: Int#,
408 /* arguments: R1 = Word# */
410 W_ val, s, p; /* to avoid aliasing */
414 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, word2Integerzh_fast);
416 p = Hp - SIZEOF_StgArrWords;
417 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
418 StgArrWords_words(p) = 1;
427 /* returns (# size :: Int#,
428 data :: ByteArray# #)
435 * 'long long' primops for converting to/from Integers.
438 #ifdef SUPPORT_LONG_LONGS
440 int64ToIntegerzh_fast
442 /* arguments: L1 = Int64# */
445 W_ hi, lo, s, neg, words_needed, p;
450 hi = TO_W_(val >> 32);
453 if ( hi != 0 && hi != 0xFFFFFFFF ) {
456 // minimum is one word
460 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(words_needed),
461 NO_PTRS, int64ToIntegerzh_fast );
463 p = Hp - SIZEOF_StgArrWords - WDS(words_needed) + WDS(1);
464 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
465 StgArrWords_words(p) = words_needed;
477 if ( words_needed == 2 ) {
485 } else /* val==0 */ {
493 /* returns (# size :: Int#,
494 data :: ByteArray# #)
498 word64ToIntegerzh_fast
500 /* arguments: L1 = Word64# */
503 W_ hi, lo, s, words_needed, p;
506 hi = TO_W_(val >> 32);
515 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(words_needed),
516 NO_PTRS, word64ToIntegerzh_fast );
518 p = Hp - SIZEOF_StgArrWords - WDS(words_needed) + WDS(1);
519 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
520 StgArrWords_words(p) = words_needed;
530 } else /* val==0 */ {
535 /* returns (# size :: Int#,
536 data :: ByteArray# #)
543 #endif /* SUPPORT_LONG_LONGS */
545 /* ToDo: this is shockingly inefficient */
550 bits8 [SIZEOF_MP_INT];
555 bits8 [SIZEOF_MP_INT];
560 bits8 [SIZEOF_MP_INT];
565 bits8 [SIZEOF_MP_INT];
570 #define FETCH_MP_TEMP(X) \
572 X = BaseReg + (OFFSET_StgRegTable_r ## X);
574 #define FETCH_MP_TEMP(X) /* Nothing */
577 #define GMP_TAKE2_RET1(name,mp_fun) \
582 FETCH_MP_TEMP(mp_tmp1); \
583 FETCH_MP_TEMP(mp_tmp2); \
584 FETCH_MP_TEMP(mp_result1) \
585 FETCH_MP_TEMP(mp_result2); \
587 /* call doYouWantToGC() */ \
588 MAYBE_GC(R2_PTR & R4_PTR, name); \
595 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
596 MP_INT__mp_size(mp_tmp1) = (s1); \
597 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
598 MP_INT__mp_alloc(mp_tmp2) = W_TO_INT(StgArrWords_words(d2)); \
599 MP_INT__mp_size(mp_tmp2) = (s2); \
600 MP_INT__mp_d(mp_tmp2) = BYTE_ARR_CTS(d2); \
602 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
604 /* Perform the operation */ \
605 foreign "C" mp_fun(mp_result1 "ptr",mp_tmp1 "ptr",mp_tmp2 "ptr") []; \
607 RET_NP(TO_W_(MP_INT__mp_size(mp_result1)), \
608 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords); \
611 #define GMP_TAKE1_RET1(name,mp_fun) \
616 FETCH_MP_TEMP(mp_tmp1); \
617 FETCH_MP_TEMP(mp_result1) \
619 /* call doYouWantToGC() */ \
620 MAYBE_GC(R2_PTR, name); \
625 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
626 MP_INT__mp_size(mp_tmp1) = (s1); \
627 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
629 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
631 /* Perform the operation */ \
632 foreign "C" mp_fun(mp_result1 "ptr",mp_tmp1 "ptr") []; \
634 RET_NP(TO_W_(MP_INT__mp_size(mp_result1)), \
635 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords); \
638 #define GMP_TAKE2_RET2(name,mp_fun) \
643 FETCH_MP_TEMP(mp_tmp1); \
644 FETCH_MP_TEMP(mp_tmp2); \
645 FETCH_MP_TEMP(mp_result1) \
646 FETCH_MP_TEMP(mp_result2) \
648 /* call doYouWantToGC() */ \
649 MAYBE_GC(R2_PTR & R4_PTR, name); \
656 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
657 MP_INT__mp_size(mp_tmp1) = (s1); \
658 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
659 MP_INT__mp_alloc(mp_tmp2) = W_TO_INT(StgArrWords_words(d2)); \
660 MP_INT__mp_size(mp_tmp2) = (s2); \
661 MP_INT__mp_d(mp_tmp2) = BYTE_ARR_CTS(d2); \
663 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
664 foreign "C" __gmpz_init(mp_result2 "ptr") []; \
666 /* Perform the operation */ \
667 foreign "C" mp_fun(mp_result1 "ptr",mp_result2 "ptr",mp_tmp1 "ptr",mp_tmp2 "ptr") []; \
669 RET_NPNP(TO_W_(MP_INT__mp_size(mp_result1)), \
670 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords, \
671 TO_W_(MP_INT__mp_size(mp_result2)), \
672 MP_INT__mp_d(mp_result2) - SIZEOF_StgArrWords); \
675 GMP_TAKE2_RET1(plusIntegerzh_fast, __gmpz_add)
676 GMP_TAKE2_RET1(minusIntegerzh_fast, __gmpz_sub)
677 GMP_TAKE2_RET1(timesIntegerzh_fast, __gmpz_mul)
678 GMP_TAKE2_RET1(gcdIntegerzh_fast, __gmpz_gcd)
679 GMP_TAKE2_RET1(quotIntegerzh_fast, __gmpz_tdiv_q)
680 GMP_TAKE2_RET1(remIntegerzh_fast, __gmpz_tdiv_r)
681 GMP_TAKE2_RET1(divExactIntegerzh_fast, __gmpz_divexact)
682 GMP_TAKE2_RET1(andIntegerzh_fast, __gmpz_and)
683 GMP_TAKE2_RET1(orIntegerzh_fast, __gmpz_ior)
684 GMP_TAKE2_RET1(xorIntegerzh_fast, __gmpz_xor)
685 GMP_TAKE1_RET1(complementIntegerzh_fast, __gmpz_com)
687 GMP_TAKE2_RET2(quotRemIntegerzh_fast, __gmpz_tdiv_qr)
688 GMP_TAKE2_RET2(divModIntegerzh_fast, __gmpz_fdiv_qr)
692 mp_tmp_w: W_; // NB. mp_tmp_w is really an here mp_limb_t
698 /* R1 = the first Int#; R2 = the second Int# */
700 FETCH_MP_TEMP(mp_tmp_w);
703 (r) = foreign "C" __gmpn_gcd_1(mp_tmp_w "ptr", 1, R2) [];
706 /* Result parked in R1, return via info-pointer at TOS */
707 jump %ENTRY_CODE(Sp(0));
713 /* R1 = s1; R2 = d1; R3 = the int */
715 (s1) = foreign "C" __gmpn_gcd_1( BYTE_ARR_CTS(R2) "ptr", R1, R3) [];
718 /* Result parked in R1, return via info-pointer at TOS */
719 jump %ENTRY_CODE(Sp(0));
725 /* R1 = s1; R2 = d1; R3 = the int */
726 W_ usize, vsize, v_digit, u_digit;
732 // paraphrased from __gmpz_cmp_si() in the GMP sources
733 if (%gt(v_digit,0)) {
736 if (%lt(v_digit,0)) {
742 if (usize != vsize) {
744 jump %ENTRY_CODE(Sp(0));
749 jump %ENTRY_CODE(Sp(0));
752 u_digit = W_[BYTE_ARR_CTS(R2)];
754 if (u_digit == v_digit) {
756 jump %ENTRY_CODE(Sp(0));
759 if (%gtu(u_digit,v_digit)) { // NB. unsigned: these are mp_limb_t's
765 jump %ENTRY_CODE(Sp(0));
770 /* R1 = s1; R2 = d1; R3 = s2; R4 = d2 */
771 W_ usize, vsize, size, up, vp;
774 // paraphrased from __gmpz_cmp() in the GMP sources
778 if (usize != vsize) {
780 jump %ENTRY_CODE(Sp(0));
785 jump %ENTRY_CODE(Sp(0));
788 if (%lt(usize,0)) { // NB. not <, which is unsigned
794 up = BYTE_ARR_CTS(R2);
795 vp = BYTE_ARR_CTS(R4);
797 (cmp) = foreign "C" __gmpn_cmp(up "ptr", vp "ptr", size) [];
799 if (cmp == 0 :: CInt) {
801 jump %ENTRY_CODE(Sp(0));
804 if (%lt(cmp,0 :: CInt) == %lt(usize,0)) {
809 /* Result parked in R1, return via info-pointer at TOS */
810 jump %ENTRY_CODE(Sp(0));
822 r = W_[R2 + SIZEOF_StgArrWords];
827 /* Result parked in R1, return via info-pointer at TOS */
829 jump %ENTRY_CODE(Sp(0));
841 r = W_[R2 + SIZEOF_StgArrWords];
846 /* Result parked in R1, return via info-pointer at TOS */
848 jump %ENTRY_CODE(Sp(0));
855 FETCH_MP_TEMP(mp_tmp1);
856 FETCH_MP_TEMP(mp_tmp_w);
858 /* arguments: F1 = Float# */
861 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, decodeFloatzh_fast );
863 /* Be prepared to tell Lennart-coded __decodeFloat
864 where mantissa._mp_d can be put (it does not care about the rest) */
865 p = Hp - SIZEOF_StgArrWords;
866 SET_HDR(p,stg_ARR_WORDS_info,W_[CCCS]);
867 StgArrWords_words(p) = 1;
868 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(p);
870 /* Perform the operation */
871 foreign "C" __decodeFloat(mp_tmp1 "ptr",mp_tmp_w "ptr" ,arg) [];
873 /* returns: (Int# (expn), Int#, ByteArray#) */
874 RET_NNP(W_[mp_tmp_w], TO_W_(MP_INT__mp_size(mp_tmp1)), p);
877 #define DOUBLE_MANTISSA_SIZE SIZEOF_DOUBLE
878 #define ARR_SIZE (SIZEOF_StgArrWords + DOUBLE_MANTISSA_SIZE)
884 FETCH_MP_TEMP(mp_tmp1);
885 FETCH_MP_TEMP(mp_tmp_w);
887 /* arguments: D1 = Double# */
890 ALLOC_PRIM( ARR_SIZE, NO_PTRS, decodeDoublezh_fast );
892 /* Be prepared to tell Lennart-coded __decodeDouble
893 where mantissa.d can be put (it does not care about the rest) */
894 p = Hp - ARR_SIZE + WDS(1);
895 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
896 StgArrWords_words(p) = BYTES_TO_WDS(DOUBLE_MANTISSA_SIZE);
897 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(p);
899 /* Perform the operation */
900 foreign "C" __decodeDouble(mp_tmp1 "ptr", mp_tmp_w "ptr",arg) [];
902 /* returns: (Int# (expn), Int#, ByteArray#) */
903 RET_NNP(W_[mp_tmp_w], TO_W_(MP_INT__mp_size(mp_tmp1)), p);
906 /* -----------------------------------------------------------------------------
907 * Concurrency primitives
908 * -------------------------------------------------------------------------- */
912 /* args: R1 = closure to spark */
914 MAYBE_GC(R1_PTR, forkzh_fast);
920 ("ptr" threadid) = foreign "C" createIOThread( MyCapability() "ptr",
921 RtsFlags_GcFlags_initialStkSize(RtsFlags),
923 foreign "C" scheduleThread(MyCapability() "ptr", threadid "ptr") [];
925 // switch at the earliest opportunity
926 CInt[context_switch] = 1 :: CInt;
933 /* args: R1 = cpu, R2 = closure to spark */
935 MAYBE_GC(R2_PTR, forkOnzh_fast);
943 ("ptr" threadid) = foreign "C" createIOThread( MyCapability() "ptr",
944 RtsFlags_GcFlags_initialStkSize(RtsFlags),
946 foreign "C" scheduleThreadOn(MyCapability() "ptr", cpu, threadid "ptr") [];
948 // switch at the earliest opportunity
949 CInt[context_switch] = 1 :: CInt;
956 jump stg_yield_noregs;
971 foreign "C" labelThread(R1 "ptr", R2 "ptr") [];
973 jump %ENTRY_CODE(Sp(0));
976 isCurrentThreadBoundzh_fast
980 (r) = foreign "C" isThreadBound(CurrentTSO) [];
985 /* -----------------------------------------------------------------------------
987 * -------------------------------------------------------------------------- */
991 #define IF_NOT_REG_R1(x)
994 #define IF_NOT_REG_R1(x) x
997 // Catch retry frame ------------------------------------------------------------
999 INFO_TABLE_RET(stg_catch_retry_frame, CATCH_RETRY_FRAME,
1000 #if defined(PROFILING)
1001 W_ unused1, W_ unused2,
1003 W_ unused3, "ptr" W_ unused4, "ptr" W_ unused5)
1005 W_ r, frame, trec, outer;
1006 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1009 trec = StgTSO_trec(CurrentTSO);
1010 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1011 (r) = foreign "C" stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr") [];
1013 /* Succeeded (either first branch or second branch) */
1014 StgTSO_trec(CurrentTSO) = outer;
1015 Sp = Sp + SIZEOF_StgCatchRetryFrame;
1016 IF_NOT_REG_R1(Sp_adj(-1); Sp(0) = rval;)
1017 jump %ENTRY_CODE(Sp(SP_OFF));
1019 /* Did not commit: re-execute */
1021 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1022 StgTSO_trec(CurrentTSO) = new_trec;
1023 if (StgCatchRetryFrame_running_alt_code(frame) != 0::I32) {
1024 R1 = StgCatchRetryFrame_alt_code(frame);
1026 R1 = StgCatchRetryFrame_first_code(frame);
1033 // Atomically frame ------------------------------------------------------------
1035 INFO_TABLE_RET(stg_atomically_frame, ATOMICALLY_FRAME,
1036 #if defined(PROFILING)
1037 W_ unused1, W_ unused2,
1039 "ptr" W_ unused3, "ptr" W_ unused4)
1041 W_ frame, trec, valid, next_invariant, q, outer;
1042 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1045 trec = StgTSO_trec(CurrentTSO);
1046 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1048 if (outer == NO_TREC) {
1049 /* First time back at the atomically frame -- pick up invariants */
1050 ("ptr" q) = foreign "C" stmGetInvariantsToCheck(MyCapability() "ptr", trec "ptr") [];
1051 StgAtomicallyFrame_next_invariant_to_check(frame) = q;
1054 /* Second/subsequent time back at the atomically frame -- abort the
1055 * tx that's checking the invariant and move on to the next one */
1056 StgTSO_trec(CurrentTSO) = outer;
1057 q = StgAtomicallyFrame_next_invariant_to_check(frame);
1058 StgInvariantCheckQueue_my_execution(q) = trec;
1059 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1060 /* Don't free trec -- it's linked from q and will be stashed in the
1061 * invariant if we eventually commit. */
1062 q = StgInvariantCheckQueue_next_queue_entry(q);
1063 StgAtomicallyFrame_next_invariant_to_check(frame) = q;
1067 q = StgAtomicallyFrame_next_invariant_to_check(frame);
1069 if (q != END_INVARIANT_CHECK_QUEUE) {
1070 /* We can't commit yet: another invariant to check */
1071 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", trec "ptr") [];
1072 StgTSO_trec(CurrentTSO) = trec;
1074 next_invariant = StgInvariantCheckQueue_invariant(q);
1075 R1 = StgAtomicInvariant_code(next_invariant);
1080 /* We've got no more invariants to check, try to commit */
1081 (valid) = foreign "C" stmCommitTransaction(MyCapability() "ptr", trec "ptr") [];
1083 /* Transaction was valid: commit succeeded */
1084 StgTSO_trec(CurrentTSO) = NO_TREC;
1085 Sp = Sp + SIZEOF_StgAtomicallyFrame;
1086 IF_NOT_REG_R1(Sp_adj(-1); Sp(0) = rval;)
1087 jump %ENTRY_CODE(Sp(SP_OFF));
1089 /* Transaction was not valid: try again */
1090 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
1091 StgTSO_trec(CurrentTSO) = trec;
1092 StgAtomicallyFrame_next_invariant_to_check(frame) = END_INVARIANT_CHECK_QUEUE;
1093 R1 = StgAtomicallyFrame_code(frame);
1099 INFO_TABLE_RET(stg_atomically_waiting_frame, ATOMICALLY_FRAME,
1100 #if defined(PROFILING)
1101 W_ unused1, W_ unused2,
1103 "ptr" W_ unused3, "ptr" W_ unused4)
1105 W_ frame, trec, valid;
1106 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1110 /* The TSO is currently waiting: should we stop waiting? */
1111 (valid) = foreign "C" stmReWait(MyCapability() "ptr", CurrentTSO "ptr") [];
1113 /* Previous attempt is still valid: no point trying again yet */
1114 IF_NOT_REG_R1(Sp_adj(-2);
1115 Sp(1) = stg_NO_FINALIZER_closure;
1116 Sp(0) = stg_ut_1_0_unreg_info;)
1117 jump stg_block_noregs;
1119 /* Previous attempt is no longer valid: try again */
1120 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
1121 StgTSO_trec(CurrentTSO) = trec;
1122 StgHeader_info(frame) = stg_atomically_frame_info;
1123 R1 = StgAtomicallyFrame_code(frame);
1128 // STM catch frame --------------------------------------------------------------
1136 /* Catch frames are very similar to update frames, but when entering
1137 * one we just pop the frame off the stack and perform the correct
1138 * kind of return to the activation record underneath us on the stack.
1141 INFO_TABLE_RET(stg_catch_stm_frame, CATCH_STM_FRAME,
1142 #if defined(PROFILING)
1143 W_ unused1, W_ unused2,
1145 "ptr" W_ unused3, "ptr" W_ unused4)
1147 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1148 W_ r, frame, trec, outer;
1150 trec = StgTSO_trec(CurrentTSO);
1151 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1152 (r) = foreign "C" stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr") [];
1154 /* Commit succeeded */
1155 StgTSO_trec(CurrentTSO) = outer;
1156 Sp = Sp + SIZEOF_StgCatchSTMFrame;
1157 IF_NOT_REG_R1(Sp_adj(-1); Sp(0) = rval;)
1162 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1163 StgTSO_trec(CurrentTSO) = new_trec;
1164 R1 = StgCatchSTMFrame_code(frame);
1170 // Primop definition ------------------------------------------------------------
1178 // stmStartTransaction may allocate
1179 MAYBE_GC (R1_PTR, atomicallyzh_fast);
1181 /* Args: R1 = m :: STM a */
1182 STK_CHK_GEN(SIZEOF_StgAtomicallyFrame + WDS(1), R1_PTR, atomicallyzh_fast);
1184 old_trec = StgTSO_trec(CurrentTSO);
1186 /* Nested transactions are not allowed; raise an exception */
1187 if (old_trec != NO_TREC) {
1188 R1 = base_GHCziIOBase_NestedAtomically_closure;
1192 /* Set up the atomically frame */
1193 Sp = Sp - SIZEOF_StgAtomicallyFrame;
1196 SET_HDR(frame,stg_atomically_frame_info, W_[CCCS]);
1197 StgAtomicallyFrame_code(frame) = R1;
1198 StgAtomicallyFrame_next_invariant_to_check(frame) = END_INVARIANT_CHECK_QUEUE;
1200 /* Start the memory transcation */
1201 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", old_trec "ptr") [R1];
1202 StgTSO_trec(CurrentTSO) = new_trec;
1204 /* Apply R1 to the realworld token */
1213 /* Args: R1 :: STM a */
1214 /* Args: R2 :: Exception -> STM a */
1215 STK_CHK_GEN(SIZEOF_StgCatchSTMFrame + WDS(1), R1_PTR & R2_PTR, catchSTMzh_fast);
1217 /* Set up the catch frame */
1218 Sp = Sp - SIZEOF_StgCatchSTMFrame;
1221 SET_HDR(frame, stg_catch_stm_frame_info, W_[CCCS]);
1222 StgCatchSTMFrame_handler(frame) = R2;
1223 StgCatchSTMFrame_code(frame) = R1;
1225 /* Start a nested transaction to run the body of the try block in */
1228 cur_trec = StgTSO_trec(CurrentTSO);
1229 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", cur_trec "ptr");
1230 StgTSO_trec(CurrentTSO) = new_trec;
1232 /* Apply R1 to the realworld token */
1243 // stmStartTransaction may allocate
1244 MAYBE_GC (R1_PTR & R2_PTR, catchRetryzh_fast);
1246 /* Args: R1 :: STM a */
1247 /* Args: R2 :: STM a */
1248 STK_CHK_GEN(SIZEOF_StgCatchRetryFrame + WDS(1), R1_PTR & R2_PTR, catchRetryzh_fast);
1250 /* Start a nested transaction within which to run the first code */
1251 trec = StgTSO_trec(CurrentTSO);
1252 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", trec "ptr") [R1,R2];
1253 StgTSO_trec(CurrentTSO) = new_trec;
1255 /* Set up the catch-retry frame */
1256 Sp = Sp - SIZEOF_StgCatchRetryFrame;
1259 SET_HDR(frame, stg_catch_retry_frame_info, W_[CCCS]);
1260 StgCatchRetryFrame_running_alt_code(frame) = 0 :: CInt; // false;
1261 StgCatchRetryFrame_first_code(frame) = R1;
1262 StgCatchRetryFrame_alt_code(frame) = R2;
1264 /* Apply R1 to the realworld token */
1277 MAYBE_GC (NO_PTRS, retryzh_fast); // STM operations may allocate
1279 // Find the enclosing ATOMICALLY_FRAME or CATCH_RETRY_FRAME
1281 StgTSO_sp(CurrentTSO) = Sp;
1282 (frame_type) = foreign "C" findRetryFrameHelper(CurrentTSO "ptr") [];
1283 Sp = StgTSO_sp(CurrentTSO);
1285 trec = StgTSO_trec(CurrentTSO);
1286 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1288 if (frame_type == CATCH_RETRY_FRAME) {
1289 // The retry reaches a CATCH_RETRY_FRAME before the atomic frame
1290 ASSERT(outer != NO_TREC);
1291 // Abort the transaction attempting the current branch
1292 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1293 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
1294 if (!StgCatchRetryFrame_running_alt_code(frame) != 0::I32) {
1295 // Retry in the first branch: try the alternative
1296 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1297 StgTSO_trec(CurrentTSO) = trec;
1298 StgCatchRetryFrame_running_alt_code(frame) = 1 :: CInt; // true;
1299 R1 = StgCatchRetryFrame_alt_code(frame);
1302 // Retry in the alternative code: propagate the retry
1303 StgTSO_trec(CurrentTSO) = outer;
1304 Sp = Sp + SIZEOF_StgCatchRetryFrame;
1305 goto retry_pop_stack;
1309 // We've reached the ATOMICALLY_FRAME: attempt to wait
1310 ASSERT(frame_type == ATOMICALLY_FRAME);
1311 if (outer != NO_TREC) {
1312 // We called retry while checking invariants, so abort the current
1313 // invariant check (merging its TVar accesses into the parents read
1314 // set so we'll wait on them)
1315 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1316 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
1318 StgTSO_trec(CurrentTSO) = trec;
1319 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1321 ASSERT(outer == NO_TREC);
1323 (r) = foreign "C" stmWait(MyCapability() "ptr", CurrentTSO "ptr", trec "ptr") [];
1325 // Transaction was valid: stmWait put us on the TVars' queues, we now block
1326 StgHeader_info(frame) = stg_atomically_waiting_frame_info;
1328 // Fix up the stack in the unregisterised case: the return convention is different.
1329 IF_NOT_REG_R1(Sp_adj(-2);
1330 Sp(1) = stg_NO_FINALIZER_closure;
1331 Sp(0) = stg_ut_1_0_unreg_info;)
1332 R3 = trec; // passing to stmWaitUnblock()
1333 jump stg_block_stmwait;
1335 // Transaction was not valid: retry immediately
1336 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1337 StgTSO_trec(CurrentTSO) = trec;
1338 R1 = StgAtomicallyFrame_code(frame);
1349 /* Args: R1 = invariant closure */
1350 MAYBE_GC (R1_PTR, checkzh_fast);
1352 trec = StgTSO_trec(CurrentTSO);
1354 foreign "C" stmAddInvariantToCheck(MyCapability() "ptr",
1358 jump %ENTRY_CODE(Sp(0));
1367 /* Args: R1 = initialisation value */
1369 MAYBE_GC (R1_PTR, newTVarzh_fast);
1371 ("ptr" tv) = foreign "C" stmNewTVar(MyCapability() "ptr", new_value "ptr") [];
1382 /* Args: R1 = TVar closure */
1384 MAYBE_GC (R1_PTR, readTVarzh_fast); // Call to stmReadTVar may allocate
1385 trec = StgTSO_trec(CurrentTSO);
1387 ("ptr" result) = foreign "C" stmReadTVar(MyCapability() "ptr", trec "ptr", tvar "ptr") [];
1399 /* Args: R1 = TVar closure */
1400 /* R2 = New value */
1402 MAYBE_GC (R1_PTR & R2_PTR, writeTVarzh_fast); // Call to stmWriteTVar may allocate
1403 trec = StgTSO_trec(CurrentTSO);
1406 foreign "C" stmWriteTVar(MyCapability() "ptr", trec "ptr", tvar "ptr", new_value "ptr") [];
1408 jump %ENTRY_CODE(Sp(0));
1412 /* -----------------------------------------------------------------------------
1415 * take & putMVar work as follows. Firstly, an important invariant:
1417 * If the MVar is full, then the blocking queue contains only
1418 * threads blocked on putMVar, and if the MVar is empty then the
1419 * blocking queue contains only threads blocked on takeMVar.
1422 * MVar empty : then add ourselves to the blocking queue
1423 * MVar full : remove the value from the MVar, and
1424 * blocking queue empty : return
1425 * blocking queue non-empty : perform the first blocked putMVar
1426 * from the queue, and wake up the
1427 * thread (MVar is now full again)
1429 * putMVar is just the dual of the above algorithm.
1431 * How do we "perform a putMVar"? Well, we have to fiddle around with
1432 * the stack of the thread waiting to do the putMVar. See
1433 * stg_block_putmvar and stg_block_takemvar in HeapStackCheck.c for
1434 * the stack layout, and the PerformPut and PerformTake macros below.
1436 * It is important that a blocked take or put is woken up with the
1437 * take/put already performed, because otherwise there would be a
1438 * small window of vulnerability where the thread could receive an
1439 * exception and never perform its take or put, and we'd end up with a
1442 * -------------------------------------------------------------------------- */
1446 /* args: R1 = MVar closure */
1448 if (StgMVar_value(R1) == stg_END_TSO_QUEUE_closure) {
1460 ALLOC_PRIM ( SIZEOF_StgMVar, NO_PTRS, newMVarzh_fast );
1462 mvar = Hp - SIZEOF_StgMVar + WDS(1);
1463 SET_HDR(mvar,stg_MVAR_DIRTY_info,W_[CCCS]);
1464 // MVARs start dirty: generation 0 has no mutable list
1465 StgMVar_head(mvar) = stg_END_TSO_QUEUE_closure;
1466 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1467 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1472 /* If R1 isn't available, pass it on the stack */
1474 #define PerformTake(tso, value) \
1475 W_[StgTSO_sp(tso) + WDS(1)] = value; \
1476 W_[StgTSO_sp(tso) + WDS(0)] = stg_gc_unpt_r1_info;
1478 #define PerformTake(tso, value) \
1479 W_[StgTSO_sp(tso) + WDS(1)] = value; \
1480 W_[StgTSO_sp(tso) + WDS(0)] = stg_ut_1_0_unreg_info;
1483 #define PerformPut(tso,lval) \
1484 StgTSO_sp(tso) = StgTSO_sp(tso) + WDS(3); \
1485 lval = W_[StgTSO_sp(tso) - WDS(1)];
1489 W_ mvar, val, info, tso;
1491 /* args: R1 = MVar closure */
1494 #if defined(THREADED_RTS)
1495 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1497 info = GET_INFO(mvar);
1500 if (info == stg_MVAR_CLEAN_info) {
1501 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr");
1504 /* If the MVar is empty, put ourselves on its blocking queue,
1505 * and wait until we're woken up.
1507 if (StgMVar_value(mvar) == stg_END_TSO_QUEUE_closure) {
1508 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1509 StgMVar_head(mvar) = CurrentTSO;
1511 StgTSO_link(StgMVar_tail(mvar)) = CurrentTSO;
1513 StgTSO_link(CurrentTSO) = stg_END_TSO_QUEUE_closure;
1514 StgTSO_why_blocked(CurrentTSO) = BlockedOnMVar::I16;
1515 StgTSO_block_info(CurrentTSO) = mvar;
1516 StgMVar_tail(mvar) = CurrentTSO;
1518 jump stg_block_takemvar;
1521 /* we got the value... */
1522 val = StgMVar_value(mvar);
1524 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure)
1526 /* There are putMVar(s) waiting...
1527 * wake up the first thread on the queue
1529 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1531 /* actually perform the putMVar for the thread that we just woke up */
1532 tso = StgMVar_head(mvar);
1533 PerformPut(tso,StgMVar_value(mvar));
1536 #if defined(GRAN) || defined(PAR)
1537 /* ToDo: check 2nd arg (mvar) is right */
1538 ("ptr" tso) = foreign "C" unblockOne(StgMVar_head(mvar),mvar) [];
1539 StgMVar_head(mvar) = tso;
1541 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr",
1542 StgMVar_head(mvar) "ptr") [];
1543 StgMVar_head(mvar) = tso;
1546 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1547 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1550 #if defined(THREADED_RTS)
1551 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1553 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1559 /* No further putMVars, MVar is now empty */
1560 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1562 #if defined(THREADED_RTS)
1563 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1565 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1575 W_ mvar, val, info, tso;
1577 /* args: R1 = MVar closure */
1581 #if defined(THREADED_RTS)
1582 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1584 info = GET_INFO(mvar);
1587 if (StgMVar_value(mvar) == stg_END_TSO_QUEUE_closure) {
1588 #if defined(THREADED_RTS)
1589 unlockClosure(mvar, info);
1591 /* HACK: we need a pointer to pass back,
1592 * so we abuse NO_FINALIZER_closure
1594 RET_NP(0, stg_NO_FINALIZER_closure);
1597 if (info == stg_MVAR_CLEAN_info) {
1598 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr");
1601 /* we got the value... */
1602 val = StgMVar_value(mvar);
1604 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1606 /* There are putMVar(s) waiting...
1607 * wake up the first thread on the queue
1609 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1611 /* actually perform the putMVar for the thread that we just woke up */
1612 tso = StgMVar_head(mvar);
1613 PerformPut(tso,StgMVar_value(mvar));
1616 #if defined(GRAN) || defined(PAR)
1617 /* ToDo: check 2nd arg (mvar) is right */
1618 ("ptr" tso) = foreign "C" unblockOne(StgMVar_head(mvar) "ptr", mvar "ptr") [];
1619 StgMVar_head(mvar) = tso;
1621 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr",
1622 StgMVar_head(mvar) "ptr") [];
1623 StgMVar_head(mvar) = tso;
1626 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1627 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1629 #if defined(THREADED_RTS)
1630 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1632 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1637 /* No further putMVars, MVar is now empty */
1638 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1639 #if defined(THREADED_RTS)
1640 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1642 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1654 /* args: R1 = MVar, R2 = value */
1657 #if defined(THREADED_RTS)
1658 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [R2];
1660 info = GET_INFO(mvar);
1663 if (info == stg_MVAR_CLEAN_info) {
1664 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr");
1667 if (StgMVar_value(mvar) != stg_END_TSO_QUEUE_closure) {
1668 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1669 StgMVar_head(mvar) = CurrentTSO;
1671 StgTSO_link(StgMVar_tail(mvar)) = CurrentTSO;
1673 StgTSO_link(CurrentTSO) = stg_END_TSO_QUEUE_closure;
1674 StgTSO_why_blocked(CurrentTSO) = BlockedOnMVar::I16;
1675 StgTSO_block_info(CurrentTSO) = mvar;
1676 StgMVar_tail(mvar) = CurrentTSO;
1678 jump stg_block_putmvar;
1681 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1683 /* There are takeMVar(s) waiting: wake up the first one
1685 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1687 /* actually perform the takeMVar */
1688 tso = StgMVar_head(mvar);
1689 PerformTake(tso, R2);
1692 #if defined(GRAN) || defined(PAR)
1693 /* ToDo: check 2nd arg (mvar) is right */
1694 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr",mvar "ptr") [];
1695 StgMVar_head(mvar) = tso;
1697 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr") [];
1698 StgMVar_head(mvar) = tso;
1701 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1702 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1705 #if defined(THREADED_RTS)
1706 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1708 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1710 jump %ENTRY_CODE(Sp(0));
1714 /* No further takes, the MVar is now full. */
1715 StgMVar_value(mvar) = R2;
1717 #if defined(THREADED_RTS)
1718 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1720 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1722 jump %ENTRY_CODE(Sp(0));
1725 /* ToDo: yield afterward for better communication performance? */
1733 /* args: R1 = MVar, R2 = value */
1736 #if defined(THREADED_RTS)
1737 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [R2];
1739 info = GET_INFO(mvar);
1742 if (StgMVar_value(mvar) != stg_END_TSO_QUEUE_closure) {
1743 #if defined(THREADED_RTS)
1744 unlockClosure(mvar, info);
1749 if (info == stg_MVAR_CLEAN_info) {
1750 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr");
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, R2);
1764 #if defined(GRAN) || defined(PAR)
1765 /* ToDo: check 2nd arg (mvar) is right */
1766 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr",mvar "ptr") [];
1767 StgMVar_head(mvar) = tso;
1769 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr") [];
1770 StgMVar_head(mvar) = tso;
1773 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1774 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1777 #if defined(THREADED_RTS)
1778 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1780 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1785 /* No further takes, the MVar is now full. */
1786 StgMVar_value(mvar) = R2;
1788 #if defined(THREADED_RTS)
1789 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1791 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1796 /* ToDo: yield afterward for better communication performance? */
1800 /* -----------------------------------------------------------------------------
1801 Stable pointer primitives
1802 ------------------------------------------------------------------------- */
1804 makeStableNamezh_fast
1808 ALLOC_PRIM( SIZEOF_StgStableName, R1_PTR, makeStableNamezh_fast );
1810 (index) = foreign "C" lookupStableName(R1 "ptr") [];
1812 /* Is there already a StableName for this heap object?
1813 * stable_ptr_table is a pointer to an array of snEntry structs.
1815 if ( snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry) == NULL ) {
1816 sn_obj = Hp - SIZEOF_StgStableName + WDS(1);
1817 SET_HDR(sn_obj, stg_STABLE_NAME_info, W_[CCCS]);
1818 StgStableName_sn(sn_obj) = index;
1819 snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry) = sn_obj;
1821 sn_obj = snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry);
1828 makeStablePtrzh_fast
1832 MAYBE_GC(R1_PTR, makeStablePtrzh_fast);
1833 ("ptr" sp) = foreign "C" getStablePtr(R1 "ptr") [];
1837 deRefStablePtrzh_fast
1839 /* Args: R1 = the stable ptr */
1842 r = snEntry_addr(W_[stable_ptr_table] + sp*SIZEOF_snEntry);
1846 /* -----------------------------------------------------------------------------
1847 Bytecode object primitives
1848 ------------------------------------------------------------------------- */
1858 W_ bco, bitmap_arr, bytes, words;
1862 words = BYTES_TO_WDS(SIZEOF_StgBCO) + StgArrWords_words(bitmap_arr);
1865 ALLOC_PRIM( bytes, R1_PTR&R2_PTR&R3_PTR&R5_PTR, newBCOzh_fast );
1867 bco = Hp - bytes + WDS(1);
1868 SET_HDR(bco, stg_BCO_info, W_[CCCS]);
1870 StgBCO_instrs(bco) = R1;
1871 StgBCO_literals(bco) = R2;
1872 StgBCO_ptrs(bco) = R3;
1873 StgBCO_arity(bco) = HALF_W_(R4);
1874 StgBCO_size(bco) = HALF_W_(words);
1876 // Copy the arity/bitmap info into the BCO
1880 if (i < StgArrWords_words(bitmap_arr)) {
1881 StgBCO_bitmap(bco,i) = StgArrWords_payload(bitmap_arr,i);
1892 // R1 = the BCO# for the AP
1896 // This function is *only* used to wrap zero-arity BCOs in an
1897 // updatable wrapper (see ByteCodeLink.lhs). An AP thunk is always
1898 // saturated and always points directly to a FUN or BCO.
1899 ASSERT(%INFO_TYPE(%GET_STD_INFO(R1)) == HALF_W_(BCO) &&
1900 StgBCO_arity(R1) == HALF_W_(0));
1902 HP_CHK_GEN_TICKY(SIZEOF_StgAP, R1_PTR, mkApUpd0zh_fast);
1903 TICK_ALLOC_UP_THK(0, 0);
1904 CCCS_ALLOC(SIZEOF_StgAP);
1906 ap = Hp - SIZEOF_StgAP + WDS(1);
1907 SET_HDR(ap, stg_AP_info, W_[CCCS]);
1909 StgAP_n_args(ap) = HALF_W_(0);
1915 unpackClosurezh_fast
1917 /* args: R1 = closure to analyze */
1918 // TODO: Consider the absence of ptrs or nonptrs as a special case ?
1920 W_ info, ptrs, nptrs, p, ptrs_arr, nptrs_arr;
1921 info = %GET_STD_INFO(UNTAG(R1));
1923 // Some closures have non-standard layout, so we omit those here.
1925 type = TO_W_(%INFO_TYPE(info));
1926 switch [0 .. N_CLOSURE_TYPES] type {
1927 case THUNK_SELECTOR : {
1932 case THUNK, THUNK_1_0, THUNK_0_1, THUNK_2_0, THUNK_1_1,
1933 THUNK_0_2, THUNK_STATIC, AP, PAP, AP_STACK, BCO : {
1939 ptrs = TO_W_(%INFO_PTRS(info));
1940 nptrs = TO_W_(%INFO_NPTRS(info));
1945 W_ ptrs_arr_sz, nptrs_arr_sz;
1946 nptrs_arr_sz = SIZEOF_StgArrWords + WDS(nptrs);
1947 ptrs_arr_sz = SIZEOF_StgMutArrPtrs + WDS(ptrs);
1949 ALLOC_PRIM (ptrs_arr_sz + nptrs_arr_sz, R1_PTR, unpackClosurezh_fast);
1954 ptrs_arr = Hp - nptrs_arr_sz - ptrs_arr_sz + WDS(1);
1955 nptrs_arr = Hp - nptrs_arr_sz + WDS(1);
1957 SET_HDR(ptrs_arr, stg_MUT_ARR_PTRS_FROZEN_info, W_[CCCS]);
1958 StgMutArrPtrs_ptrs(ptrs_arr) = ptrs;
1962 W_[ptrs_arr + SIZEOF_StgMutArrPtrs + WDS(p)] = StgClosure_payload(clos,p);
1967 SET_HDR(nptrs_arr, stg_ARR_WORDS_info, W_[CCCS]);
1968 StgArrWords_words(nptrs_arr) = nptrs;
1972 W_[BYTE_ARR_CTS(nptrs_arr) + WDS(p)] = StgClosure_payload(clos, p+ptrs);
1976 RET_NPP(info, ptrs_arr, nptrs_arr);
1979 /* -----------------------------------------------------------------------------
1980 Thread I/O blocking primitives
1981 -------------------------------------------------------------------------- */
1983 /* Add a thread to the end of the blocked queue. (C-- version of the C
1984 * macro in Schedule.h).
1986 #define APPEND_TO_BLOCKED_QUEUE(tso) \
1987 ASSERT(StgTSO_link(tso) == END_TSO_QUEUE); \
1988 if (W_[blocked_queue_hd] == END_TSO_QUEUE) { \
1989 W_[blocked_queue_hd] = tso; \
1991 StgTSO_link(W_[blocked_queue_tl]) = tso; \
1993 W_[blocked_queue_tl] = tso;
1999 foreign "C" barf("waitRead# on threaded RTS") never returns;
2002 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2003 StgTSO_why_blocked(CurrentTSO) = BlockedOnRead::I16;
2004 StgTSO_block_info(CurrentTSO) = R1;
2005 // No locking - we're not going to use this interface in the
2006 // threaded RTS anyway.
2007 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2008 jump stg_block_noregs;
2016 foreign "C" barf("waitWrite# on threaded RTS") never returns;
2019 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2020 StgTSO_why_blocked(CurrentTSO) = BlockedOnWrite::I16;
2021 StgTSO_block_info(CurrentTSO) = R1;
2022 // No locking - we're not going to use this interface in the
2023 // threaded RTS anyway.
2024 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2025 jump stg_block_noregs;
2030 STRING(stg_delayzh_malloc_str, "delayzh_fast")
2033 #ifdef mingw32_HOST_OS
2041 foreign "C" barf("delay# on threaded RTS") never returns;
2044 /* args: R1 (microsecond delay amount) */
2045 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2046 StgTSO_why_blocked(CurrentTSO) = BlockedOnDelay::I16;
2048 #ifdef mingw32_HOST_OS
2050 /* could probably allocate this on the heap instead */
2051 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2052 stg_delayzh_malloc_str);
2053 (reqID) = foreign "C" addDelayRequest(R1);
2054 StgAsyncIOResult_reqID(ares) = reqID;
2055 StgAsyncIOResult_len(ares) = 0;
2056 StgAsyncIOResult_errCode(ares) = 0;
2057 StgTSO_block_info(CurrentTSO) = ares;
2059 /* Having all async-blocked threads reside on the blocked_queue
2060 * simplifies matters, so change the status to OnDoProc put the
2061 * delayed thread on the blocked_queue.
2063 StgTSO_why_blocked(CurrentTSO) = BlockedOnDoProc::I16;
2064 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2065 jump stg_block_async_void;
2071 (time) = foreign "C" getourtimeofday() [R1];
2072 divisor = TO_W_(RtsFlags_MiscFlags_tickInterval(RtsFlags))*1000;
2073 target = ((R1 + divisor - 1) / divisor) /* divide rounding up */
2074 + time + 1; /* Add 1 as getourtimeofday rounds down */
2075 StgTSO_block_info(CurrentTSO) = target;
2077 /* Insert the new thread in the sleeping queue. */
2079 t = W_[sleeping_queue];
2081 if (t != END_TSO_QUEUE && StgTSO_block_info(t) < target) {
2087 StgTSO_link(CurrentTSO) = t;
2089 W_[sleeping_queue] = CurrentTSO;
2091 StgTSO_link(prev) = CurrentTSO;
2093 jump stg_block_noregs;
2095 #endif /* !THREADED_RTS */
2099 #ifdef mingw32_HOST_OS
2100 STRING(stg_asyncReadzh_malloc_str, "asyncReadzh_fast")
2107 foreign "C" barf("asyncRead# on threaded RTS") never returns;
2110 /* args: R1 = fd, R2 = isSock, R3 = len, R4 = buf */
2111 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2112 StgTSO_why_blocked(CurrentTSO) = BlockedOnRead::I16;
2114 /* could probably allocate this on the heap instead */
2115 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2116 stg_asyncReadzh_malloc_str)
2118 (reqID) = foreign "C" addIORequest(R1, 0/*FALSE*/,R2,R3,R4 "ptr") [];
2119 StgAsyncIOResult_reqID(ares) = reqID;
2120 StgAsyncIOResult_len(ares) = 0;
2121 StgAsyncIOResult_errCode(ares) = 0;
2122 StgTSO_block_info(CurrentTSO) = ares;
2123 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2124 jump stg_block_async;
2128 STRING(stg_asyncWritezh_malloc_str, "asyncWritezh_fast")
2135 foreign "C" barf("asyncWrite# on threaded RTS") never returns;
2138 /* args: R1 = fd, R2 = isSock, R3 = len, R4 = buf */
2139 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2140 StgTSO_why_blocked(CurrentTSO) = BlockedOnWrite::I16;
2142 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2143 stg_asyncWritezh_malloc_str)
2145 (reqID) = foreign "C" addIORequest(R1, 1/*TRUE*/,R2,R3,R4 "ptr") [];
2147 StgAsyncIOResult_reqID(ares) = reqID;
2148 StgAsyncIOResult_len(ares) = 0;
2149 StgAsyncIOResult_errCode(ares) = 0;
2150 StgTSO_block_info(CurrentTSO) = ares;
2151 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2152 jump stg_block_async;
2156 STRING(stg_asyncDoProczh_malloc_str, "asyncDoProczh_fast")
2163 foreign "C" barf("asyncDoProc# on threaded RTS") never returns;
2166 /* args: R1 = proc, R2 = param */
2167 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2168 StgTSO_why_blocked(CurrentTSO) = BlockedOnDoProc::I16;
2170 /* could probably allocate this on the heap instead */
2171 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2172 stg_asyncDoProczh_malloc_str)
2174 (reqID) = foreign "C" addDoProcRequest(R1 "ptr",R2 "ptr") [];
2175 StgAsyncIOResult_reqID(ares) = reqID;
2176 StgAsyncIOResult_len(ares) = 0;
2177 StgAsyncIOResult_errCode(ares) = 0;
2178 StgTSO_block_info(CurrentTSO) = ares;
2179 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2180 jump stg_block_async;
2185 // noDuplicate# tries to ensure that none of the thunks under
2186 // evaluation by the current thread are also under evaluation by
2187 // another thread. It relies on *both* threads doing noDuplicate#;
2188 // the second one will get blocked if they are duplicating some work.
2191 SAVE_THREAD_STATE();
2192 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
2193 foreign "C" threadPaused (MyCapability() "ptr", CurrentTSO "ptr") [];
2195 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
2196 jump stg_threadFinished;
2198 LOAD_THREAD_STATE();
2199 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
2200 jump %ENTRY_CODE(Sp(0));
2204 getApStackValzh_fast
2206 W_ ap_stack, offset, val, ok;
2208 /* args: R1 = AP_STACK, R2 = offset */
2212 if (%INFO_PTR(ap_stack) == stg_AP_STACK_info) {
2214 val = StgAP_STACK_payload(ap_stack,offset);