PrimOps.cmm 65.8 KB
Newer Older
1
/* -*- tab-width: 8 -*- */
2 3
/* -----------------------------------------------------------------------------
 *
4
 * (c) The GHC Team, 1998-2012
5 6 7 8 9 10 11 12 13
 *
 * Out-of-line primitive operations
 *
 * This file contains the implementations of all the primitive
 * operations ("primops") which are not expanded inline.  See
 * ghc/compiler/prelude/primops.txt.pp for a list of all the primops;
 * this file contains code for most of those with the attribute
 * out_of_line=True.
 *
14 15 16
 * Entry convention: the entry convention for a primop is the
 * NativeNodeCall convention, and the return convention is
 * NativeReturn.  (see compiler/cmm/CmmCallConv.hs)
17 18 19 20 21 22 23 24 25
 *
 * This file is written in a subset of C--, extended with various
 * features specific to GHC.  It is compiled by GHC directly.  For the
 * syntax of .cmm files, see the parser in ghc/compiler/cmm/CmmParse.y.
 *
 * ---------------------------------------------------------------------------*/

#include "Cmm.h"

26
#ifdef __PIC__
27 28
import pthread_mutex_lock;
import pthread_mutex_unlock;
29
#endif
30
import base_ControlziExceptionziBase_nestedAtomically_closure;
31 32
import EnterCriticalSection;
import LeaveCriticalSection;
Ian Lynagh's avatar
Ian Lynagh committed
33
import ghczmprim_GHCziTypes_False_closure;
34
#if defined(USE_MINIINTERPRETER) || !defined(mingw32_HOST_OS)
35
import sm_mutex;
36
#endif
37

38 39 40 41 42 43 44 45 46 47 48 49 50
/*-----------------------------------------------------------------------------
  Array Primitives

  Basically just new*Array - the others are all inline macros.

  The slow entry point is for returning from a heap check, the saved
  size argument must be re-loaded from the stack.
  -------------------------------------------------------------------------- */

/* for objects that are *less* than the size of a word, make sure we
 * round up to the nearest word for the size of the array.
 */

51
stg_newByteArrayzh ( W_ n )
52
{
53 54 55 56 57
    W_ words, payload_words;
    gcptr p;

    MAYBE_GC_N(stg_newByteArrayzh, n);

58 59
    payload_words = ROUNDUP_BYTES_TO_WDS(n);
    words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
60
    ("ptr" p) = ccall allocate(MyCapability() "ptr",words);
61
    TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
62
    SET_HDR(p, stg_ARR_WORDS_info, CCCS);
63
    StgArrWords_bytes(p) = n;
64
    return (p);
65 66
}

Simon Marlow's avatar
Simon Marlow committed
67 68 69
#define BA_ALIGN 16
#define BA_MASK  (BA_ALIGN-1)

70
stg_newPinnedByteArrayzh ( W_ n )
71
{
72 73 74 75
    W_ words, bytes, payload_words;
    gcptr p;

    MAYBE_GC_N(stg_newPinnedByteArrayzh, n);
76

77
    bytes = n;
78 79 80 81 82 83 84 85 86 87
    /* payload_words is what we will tell the profiler we had to allocate */
    payload_words = ROUNDUP_BYTES_TO_WDS(bytes);
    /* When we actually allocate memory, we need to allow space for the
       header: */
    bytes = bytes + SIZEOF_StgArrWords;
    /* And we want to align to BA_ALIGN bytes, so we need to allow space
       to shift up to BA_ALIGN - 1 bytes: */
    bytes = bytes + BA_ALIGN - 1;
    /* Now we convert to a number of words: */
    words = ROUNDUP_BYTES_TO_WDS(bytes);
Simon Marlow's avatar
Simon Marlow committed
88

89
    ("ptr" p) = ccall allocatePinned(MyCapability() "ptr", words);
Simon Marlow's avatar
Simon Marlow committed
90 91
    TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);

92 93
    /* Now we need to move p forward so that the payload is aligned
       to BA_ALIGN bytes: */
Simon Marlow's avatar
Simon Marlow committed
94 95
    p = p + ((-p - SIZEOF_StgArrWords) & BA_MASK);

96
    SET_HDR(p, stg_ARR_WORDS_info, CCCS);
97
    StgArrWords_bytes(p) = n;
98
    return (p);
Simon Marlow's avatar
Simon Marlow committed
99 100
}

101
stg_newAlignedPinnedByteArrayzh ( W_ n, W_ alignment )
Simon Marlow's avatar
Simon Marlow committed
102
{
103 104
    W_ words, bytes, payload_words;
    gcptr p;
Simon Marlow's avatar
Simon Marlow committed
105

106
    again: MAYBE_GC(again);
Simon Marlow's avatar
Simon Marlow committed
107

108 109 110 111 112
    /* we always supply at least word-aligned memory, so there's no
       need to allow extra space for alignment if the requirement is less
       than a word.  This also prevents mischief with alignment == 0. */
    if (alignment <= SIZEOF_W) { alignment = 1; }

113 114
    bytes = n;

115 116
    /* payload_words is what we will tell the profiler we had to allocate */
    payload_words = ROUNDUP_BYTES_TO_WDS(bytes);
Simon Marlow's avatar
Simon Marlow committed
117

118 119 120 121 122 123 124 125
    /* When we actually allocate memory, we need to allow space for the
       header: */
    bytes = bytes + SIZEOF_StgArrWords;
    /* And we want to align to <alignment> bytes, so we need to allow space
       to shift up to <alignment - 1> bytes: */
    bytes = bytes + alignment - 1;
    /* Now we convert to a number of words: */
    words = ROUNDUP_BYTES_TO_WDS(bytes);
126

127
    ("ptr" p) = ccall allocatePinned(MyCapability() "ptr", words);
128 129
    TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);

130 131 132 133
    /* Now we need to move p forward so that the payload is aligned
       to <alignment> bytes. Note that we are assuming that
       <alignment> is a power of 2, which is technically not guaranteed */
    p = p + ((-p - SIZEOF_StgArrWords) & (alignment - 1));
134

135
    SET_HDR(p, stg_ARR_WORDS_info, CCCS);
136
    StgArrWords_bytes(p) = n;
137
    return (p);
138 139
}

140 141 142 143 144
// RRN: This one does not use the "ticketing" approach because it
// deals in unboxed scalars, not heap pointers.
stg_casIntArrayzh( gcptr arr, W_ ind, W_ old, W_ new )
/* MutableByteArray# s -> Int# -> Int# -> Int# -> State# s -> (# State# s, Int# #) */
{
145 146
    gcptr p;
    W_ h;
147 148 149 150 151 152 153

    p = arr + SIZEOF_StgArrWords + WDS(ind);
    (h) = ccall cas(p, old, new);

    return(h);
}

154 155 156 157

stg_fetchAddIntArrayzh( gcptr arr, W_ ind, W_ incr )
/* MutableByteArray# s -> Int# -> Int# -> State# s -> (# State# s, Int# #) */
{
158 159
    gcptr p;
    W_ h;
160 161

    p = arr + SIZEOF_StgArrWords + WDS(ind);
162
    (h) = ccall atomic_inc(p, incr);
163 164 165 166 167

    return(h);
}


168
stg_newArrayzh ( W_ n /* words */, gcptr init )
169
{
170 171
    W_ words, size;
    gcptr p, arr;
172

173
    again: MAYBE_GC(again);
174

175 176 177 178 179
    // the mark area contains one byte for each 2^MUT_ARR_PTRS_CARD_BITS words
    // in the array, making sure we round up, and then rounding up to a whole
    // number of words.
    size = n + mutArrPtrsCardWords(n);
    words = BYTES_TO_WDS(SIZEOF_StgMutArrPtrs) + size;
180
    ("ptr" arr) = ccall allocate(MyCapability() "ptr",words);
181 182
    TICK_ALLOC_PRIM(SIZEOF_StgMutArrPtrs, WDS(n), 0);

183
    SET_HDR(arr, stg_MUT_ARR_PTRS_DIRTY_info, CCCS);
184
    StgMutArrPtrs_ptrs(arr) = n;
185
    StgMutArrPtrs_size(arr) = size;
186 187 188 189 190

    // Initialise all elements of the the array with the value in R2
    p = arr + SIZEOF_StgMutArrPtrs;
  for:
    if (p < arr + WDS(words)) {
ian@well-typed.com's avatar
ian@well-typed.com committed
191 192 193
        W_[p] = init;
        p = p + WDS(1);
        goto for;
194
    }
195 196 197
    // Initialise the mark bits with 0
  for2:
    if (p < arr + WDS(size)) {
ian@well-typed.com's avatar
ian@well-typed.com committed
198 199 200
        W_[p] = 0;
        p = p + WDS(1);
        goto for2;
201
    }
202

203
    return (arr);
204 205
}

206
stg_unsafeThawArrayzh ( gcptr arr )
207 208 209
{
  // SUBTLETY TO DO WITH THE OLD GEN MUTABLE LIST
  //
ian@well-typed.com's avatar
ian@well-typed.com committed
210
  // A MUT_ARR_PTRS lives on the mutable list, but a MUT_ARR_PTRS_FROZEN
211 212
  // normally doesn't.  However, when we freeze a MUT_ARR_PTRS, we leave
  // it on the mutable list for the GC to remove (removing something from
213
  // the mutable list is not easy).
ian@well-typed.com's avatar
ian@well-typed.com committed
214
  //
215
  // So that we can tell whether a MUT_ARR_PTRS_FROZEN is on the mutable list,
216 217 218
  // when we freeze it we set the info ptr to be MUT_ARR_PTRS_FROZEN0
  // to indicate that it is still on the mutable list.
  //
219 220
  // So, when we thaw a MUT_ARR_PTRS_FROZEN, we must cope with two cases:
  // either it is on a mut_list, or it isn't.  We adopt the convention that
221
  // the closure type is MUT_ARR_PTRS_FROZEN0 if it is on the mutable list,
222 223 224
  // and MUT_ARR_PTRS_FROZEN otherwise.  In fact it wouldn't matter if
  // we put it on the mutable list more than once, but it would get scavenged
  // multiple times during GC, which would be unnecessarily slow.
225
  //
226 227 228
  if (StgHeader_info(arr) != stg_MUT_ARR_PTRS_FROZEN0_info) {
        SET_INFO(arr,stg_MUT_ARR_PTRS_DIRTY_info);
        recordMutable(arr);
ian@well-typed.com's avatar
ian@well-typed.com committed
229 230
        // must be done after SET_INFO, because it ASSERTs closure_MUTABLE()
        return (arr);
231
  } else {
ian@well-typed.com's avatar
ian@well-typed.com committed
232 233
        SET_INFO(arr,stg_MUT_ARR_PTRS_DIRTY_info);
        return (arr);
234 235 236
  }
}

237
// RRN: Uses the ticketed approach; see casMutVar
238
stg_casArrayzh ( gcptr arr, W_ ind, gcptr old, gcptr new )
239
/* MutableArray# s a -> Int# -> a -> a -> State# s -> (# State# s, Int#, Any a #) */
240
{
241 242
    gcptr p, h;
    W_ len;
243 244

    p = arr + SIZEOF_StgMutArrPtrs + WDS(ind);
245
    (h) = ccall cas(p, old, new);
246 247 248
    
    if (h != old) {
        // Failure, return what was there instead of 'old':
249
        return (1,h);
250 251
    } else {
        // Compare and Swap Succeeded:
rrnewton's avatar
rrnewton committed
252 253 254 255
        SET_HDR(arr, stg_MUT_ARR_PTRS_DIRTY_info, CCCS);
        len = StgMutArrPtrs_ptrs(arr);
        // The write barrier.  We must write a byte into the mark table:
        I8[arr + SIZEOF_StgMutArrPtrs + WDS(len) + (ind >> MUT_ARR_PTRS_CARD_BITS )] = 1;
256
        return (0,new);
257 258 259
    }
}

260
stg_newArrayArrayzh ( W_ n /* words */ )
261
{
262 263
    W_ words, size;
    gcptr p, arr;
264

265
    MAYBE_GC_N(stg_newArrayArrayzh, n);
266 267 268 269 270 271

    // the mark area contains one byte for each 2^MUT_ARR_PTRS_CARD_BITS words
    // in the array, making sure we round up, and then rounding up to a whole
    // number of words.
    size = n + mutArrPtrsCardWords(n);
    words = BYTES_TO_WDS(SIZEOF_StgMutArrPtrs) + size;
272
    ("ptr" arr) = ccall allocate(MyCapability() "ptr",words);
273 274 275 276 277 278 279 280 281 282
    TICK_ALLOC_PRIM(SIZEOF_StgMutArrPtrs, WDS(n), 0);

    SET_HDR(arr, stg_MUT_ARR_PTRS_DIRTY_info, W_[CCCS]);
    StgMutArrPtrs_ptrs(arr) = n;
    StgMutArrPtrs_size(arr) = size;

    // Initialise all elements of the array with a pointer to the new array
    p = arr + SIZEOF_StgMutArrPtrs;
  for:
    if (p < arr + WDS(words)) {
ian@well-typed.com's avatar
ian@well-typed.com committed
283 284 285
        W_[p] = arr;
        p = p + WDS(1);
        goto for;
286 287 288 289
    }
    // Initialise the mark bits with 0
  for2:
    if (p < arr + WDS(size)) {
ian@well-typed.com's avatar
ian@well-typed.com committed
290 291 292
        W_[p] = 0;
        p = p + WDS(1);
        goto for2;
293 294
    }

295
    return (arr);
296 297
}

pumpkin's avatar
pumpkin committed
298

299 300 301 302
/* -----------------------------------------------------------------------------
   MutVar primitives
   -------------------------------------------------------------------------- */

303
stg_newMutVarzh ( gcptr init )
304 305 306
{
    W_ mv;

307
    ALLOC_PRIM_P (SIZEOF_StgMutVar, stg_newMutVarzh, init);
308 309

    mv = Hp - SIZEOF_StgMutVar + WDS(1);
310
    SET_HDR(mv,stg_MUT_VAR_DIRTY_info,CCCS);
311
    StgMutVar_var(mv) = init;
ian@well-typed.com's avatar
ian@well-typed.com committed
312

313
    return (mv);
314 315
}

316 317 318 319 320
// RRN: To support the "ticketed" approach, we return the NEW rather
// than old value if the CAS is successful.  This is received in an
// opaque form in the Haskell code, preventing the compiler from
// changing its pointer identity.  The ticket can then be safely used
// in future CAS operations.
321
stg_casMutVarzh ( gcptr mv, gcptr old, gcptr new )
322
 /* MutVar# s a -> a -> a -> State# s -> (# State#, Int#, Any a #) */
Simon Marlow's avatar
Simon Marlow committed
323
{
324
    gcptr h;
Simon Marlow's avatar
Simon Marlow committed
325

326 327
    (h) = ccall cas(mv + SIZEOF_StgHeader + OFFSET_StgMutVar_var,
                          old, new);
Simon Marlow's avatar
Simon Marlow committed
328
    if (h != old) {
329
        return (1,h);
Simon Marlow's avatar
Simon Marlow committed
330
    } else {
331
        if (GET_INFO(mv) == stg_MUT_VAR_CLEAN_info) {
332
           ccall dirty_MUT_VAR(BaseReg "ptr", mv "ptr");
333
        }
334
        return (0,new);
Simon Marlow's avatar
Simon Marlow committed
335 336 337
    }
}

338
stg_atomicModifyMutVarzh ( gcptr mv, gcptr f )
339
{
340
    W_ z, x, y, r, h;
341

ian@well-typed.com's avatar
ian@well-typed.com committed
342
    /* If x is the current contents of the MutVar#, then
343 344 345
       We want to make the new contents point to

         (sel_0 (f x))
ian@well-typed.com's avatar
ian@well-typed.com committed
346

347
       and the return value is
ian@well-typed.com's avatar
ian@well-typed.com committed
348 349

         (sel_1 (f x))
350 351 352 353

        obviously we can share (f x).

         z = [stg_ap_2 f x]  (max (HS + 2) MIN_UPD_SIZE)
ian@well-typed.com's avatar
ian@well-typed.com committed
354
         y = [stg_sel_0 z]   (max (HS + 1) MIN_UPD_SIZE)
355 356 357 358
         r = [stg_sel_1 z]   (max (HS + 1) MIN_UPD_SIZE)
    */

#if MIN_UPD_SIZE > 1
359
#define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
360 361
#define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),WDS(MIN_UPD_SIZE-1))
#else
362
#define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(1))
363 364 365 366
#define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),0)
#endif

#if MIN_UPD_SIZE > 2
367
#define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
368 369
#define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),WDS(MIN_UPD_SIZE-2))
#else
370
#define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(2))
371 372 373 374 375
#define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),0)
#endif

#define SIZE (THUNK_2_SIZE + THUNK_1_SIZE + THUNK_1_SIZE)

376
   HP_CHK_GEN_TICKY(SIZE);
377 378 379 380

   TICK_ALLOC_THUNK_2();
   CCCS_ALLOC(THUNK_2_SIZE);
   z = Hp - THUNK_2_SIZE + WDS(1);
381
   SET_HDR(z, stg_ap_2_upd_info, CCCS);
382
   LDV_RECORD_CREATE(z);
383
   StgThunk_payload(z,0) = f;
384 385 386 387

   TICK_ALLOC_THUNK_1();
   CCCS_ALLOC(THUNK_1_SIZE);
   y = z - THUNK_1_SIZE;
388
   SET_HDR(y, stg_sel_0_upd_info, CCCS);
389
   LDV_RECORD_CREATE(y);
390
   StgThunk_payload(y,0) = z;
391 392 393 394

   TICK_ALLOC_THUNK_1();
   CCCS_ALLOC(THUNK_1_SIZE);
   r = y - THUNK_1_SIZE;
395
   SET_HDR(r, stg_sel_1_upd_info, CCCS);
396
   LDV_RECORD_CREATE(r);
397 398
   StgThunk_payload(r,0) = z;

399 400 401 402
 retry:
   x = StgMutVar_var(mv);
   StgThunk_payload(z,1) = x;
#ifdef THREADED_RTS
403
   (h) = ccall cas(mv + SIZEOF_StgHeader + OFFSET_StgMutVar_var, x, y);
404 405 406
   if (h != x) { goto retry; }
#else
   StgMutVar_var(mv) = y;
407
#endif
408

409
   if (GET_INFO(mv) == stg_MUT_VAR_CLEAN_info) {
410
     ccall dirty_MUT_VAR(BaseReg "ptr", mv "ptr");
411 412
   }

413
   return (r);
414 415 416 417 418 419 420 421
}

/* -----------------------------------------------------------------------------
   Weak Pointer Primitives
   -------------------------------------------------------------------------- */

STRING(stg_weak_msg,"New weak pointer at %p\n")

422 423 424
stg_mkWeakzh ( gcptr key,
               gcptr value,
               gcptr finalizer /* or stg_NO_FINALIZER_closure */ )
425
{
426
  gcptr w;
427

428
  ALLOC_PRIM (SIZEOF_StgWeak)
429 430

  w = Hp - SIZEOF_StgWeak + WDS(1);
431
  SET_HDR(w, stg_WEAK_info, CCCS);
432

433 434 435 436
  StgWeak_key(w)         = key;
  StgWeak_value(w)       = value;
  StgWeak_finalizer(w)   = finalizer;
  StgWeak_cfinalizers(w) = stg_NO_FINALIZER_closure;
437

438
  ACQUIRE_LOCK(sm_mutex);
439 440
  StgWeak_link(w) = generation_weak_ptr_list(W_[g0]);
  generation_weak_ptr_list(W_[g0]) = w;
441
  RELEASE_LOCK(sm_mutex);
442

443
  IF_DEBUG(weak, ccall debugBelch(stg_weak_msg,w));
444

445
  return (w);
446 447
}

448
stg_mkWeakNoFinalizzerzh ( gcptr key, gcptr value )
449
{
450
  jump stg_mkWeakzh (key, value, stg_NO_FINALIZER_closure);
451 452
}

453 454 455 456 457 458 459
STRING(stg_cfinalizer_msg,"Adding a finalizer to %p\n")

stg_addCFinalizzerToWeakzh ( W_ fptr,   // finalizer
                             W_ ptr,
                             W_ flag,   // has environment (0 or 1)
                             W_ eptr,
                             gcptr w )
460
{
461
  W_ c, info;
462

463
  ALLOC_PRIM (SIZEOF_StgCFinalizerList)
464

465 466
  c = Hp - SIZEOF_StgCFinalizerList + WDS(1);
  SET_HDR(c, stg_C_FINALIZER_LIST_info, CCCS);
467

468 469 470 471
  StgCFinalizerList_fptr(c) = fptr;
  StgCFinalizerList_ptr(c) = ptr;
  StgCFinalizerList_eptr(c) = eptr;
  StgCFinalizerList_flag(c) = flag;
472

473 474 475 476 477 478 479 480
  LOCK_CLOSURE(w, info);

  if (info == stg_DEAD_WEAK_info) {
    // Already dead.
    unlockClosure(w, info);
    return (0);
  }

481 482
  StgCFinalizerList_link(c) = StgWeak_cfinalizers(w);
  StgWeak_cfinalizers(w) = c;
483

484
  unlockClosure(w, info);
485

486
  recordMutable(w);
487

488
  IF_DEBUG(weak, ccall debugBelch(stg_cfinalizer_msg,w));
489

490
  return (1);
491
}
492

493
stg_finalizzeWeakzh ( gcptr w )
494
{
495 496 497
  gcptr f, list;
  W_ info;

498
  LOCK_CLOSURE(w, info);
499 500

  // already dead?
501 502
  if (info == stg_DEAD_WEAK_info) {
      unlockClosure(w, info);
503
      return (0,stg_NO_FINALIZER_closure);
504 505
  }

506 507 508
  f    = StgWeak_finalizer(w);
  list = StgWeak_cfinalizers(w);

509 510 511 512 513 514 515 516
  // kill it
#ifdef PROFILING
  // @LDV profiling
  // A weak pointer is inherently used, so we do not need to call
  // LDV_recordDead_FILL_SLOP_DYNAMIC():
  //    LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)w);
  // or, LDV_recordDead():
  //    LDV_recordDead((StgClosure *)w, sizeofW(StgWeak) - sizeofW(StgProfHeader));
ian@well-typed.com's avatar
ian@well-typed.com committed
517
  // Furthermore, when PROFILING is turned on, dead weak pointers are exactly as
518 519 520 521 522 523 524
  // large as weak pointers, so there is no need to fill the slop, either.
  // See stg_DEAD_WEAK_info in StgMiscClosures.hc.
#endif

  //
  // Todo: maybe use SET_HDR() and remove LDV_recordCreate()?
  //
525
  unlockClosure(w, stg_DEAD_WEAK_info);
526

527
  LDV_RECORD_CREATE(w);
528

529 530
  if (list != stg_NO_FINALIZER_closure) {
    ccall runCFinalizers(list);
531 532
  }

533 534
  /* return the finalizer */
  if (f == stg_NO_FINALIZER_closure) {
535
      return (0,stg_NO_FINALIZER_closure);
536
  } else {
537
      return (1,f);
538 539 540
  }
}

541
stg_deRefWeakzh ( gcptr w )
542
{
543
  W_ code, info;
544
  gcptr val;
545

546 547 548 549 550 551 552
  info = GET_INFO(w);

  if (info == stg_WHITEHOLE_info) {
    // w is locked by another thread. Now it's not immediately clear if w is
    // alive or not. We use lockClosure to wait for the info pointer to become
    // something other than stg_WHITEHOLE_info.

553
    LOCK_CLOSURE(w, info);
554 555 556 557
    unlockClosure(w, info);
  }

  if (info == stg_WEAK_info) {
558 559 560 561 562 563
    code = 1;
    val = StgWeak_value(w);
  } else {
    code = 0;
    val = w;
  }
564
  return (code,val);
565 566 567
}

/* -----------------------------------------------------------------------------
568
   Floating point operations.
569 570
   -------------------------------------------------------------------------- */

571
stg_decodeFloatzuIntzh ( F_ arg )
ian@well-typed.com's avatar
ian@well-typed.com committed
572
{
573
    W_ p;
574
    W_ tmp, mp_tmp1, mp_tmp_w, r1, r2;
575

576
    STK_CHK_GEN_N (WDS(2));
577

578
    reserve 2 = tmp {
ian@well-typed.com's avatar
ian@well-typed.com committed
579

580 581 582 583 584 585 586 587 588
      mp_tmp1  = tmp + WDS(1);
      mp_tmp_w = tmp;

      /* Perform the operation */
      ccall __decodeFloat_Int(mp_tmp1 "ptr", mp_tmp_w "ptr", arg);

      r1 = W_[mp_tmp1];
      r2 = W_[mp_tmp_w];
    }
ian@well-typed.com's avatar
ian@well-typed.com committed
589

590
    /* returns: (Int# (mantissa), Int# (exponent)) */
591
    return (r1, r2);
592 593
}

594
stg_decodeDoublezu2Intzh ( D_ arg )
ian@well-typed.com's avatar
ian@well-typed.com committed
595
{
596 597 598
    W_ p, tmp;
    W_ mp_tmp1, mp_tmp2, mp_result1, mp_result2;
    W_ r1, r2, r3, r4;
599

600
    STK_CHK_GEN_N (WDS(4));
601

602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
    reserve 4 = tmp {

      mp_tmp1    = tmp + WDS(3);
      mp_tmp2    = tmp + WDS(2);
      mp_result1 = tmp + WDS(1);
      mp_result2 = tmp;
  
      /* Perform the operation */
      ccall __decodeDouble_2Int(mp_tmp1 "ptr", mp_tmp2 "ptr",
                                      mp_result1 "ptr", mp_result2 "ptr",
                                      arg);

      r1 = W_[mp_tmp1];
      r2 = W_[mp_tmp2];
      r3 = W_[mp_result1];
      r4 = W_[mp_result2];
    }
619 620 621

    /* returns:
       (Int# (mant sign), Word# (mant high), Word# (mant low), Int# (expn)) */
622
    return (r1, r2, r3, r4);
623 624
}

625 626 627 628
/* -----------------------------------------------------------------------------
 * Concurrency primitives
 * -------------------------------------------------------------------------- */

629
stg_forkzh ( gcptr closure )
630
{
631
  MAYBE_GC_P(stg_forkzh, closure);
632

633
  gcptr threadid;
634

ian@well-typed.com's avatar
ian@well-typed.com committed
635 636
  ("ptr" threadid) = ccall createIOThread( MyCapability() "ptr",
                                RtsFlags_GcFlags_initialStkSize(RtsFlags),
637
                                closure "ptr");
638 639

  /* start blocked if the current thread is blocked */
640
  StgTSO_flags(threadid) = %lobits16(
ian@well-typed.com's avatar
ian@well-typed.com committed
641
     TO_W_(StgTSO_flags(threadid)) |
642
     TO_W_(StgTSO_flags(CurrentTSO)) & (TSO_BLOCKEX | TSO_INTERRUPTIBLE));
643

644
  ccall scheduleThread(MyCapability() "ptr", threadid "ptr");
645

646 647
  // context switch soon, but not immediately: we don't want every
  // forkIO to force a context-switch.
648
  Capability_context_switch(MyCapability()) = 1 :: CInt;
ian@well-typed.com's avatar
ian@well-typed.com committed
649

650
  return (threadid);
651 652
}

653
stg_forkOnzh ( W_ cpu, gcptr closure )
654
{
655
again: MAYBE_GC(again);
656

657
  gcptr threadid;
658

ian@well-typed.com's avatar
ian@well-typed.com committed
659 660
  ("ptr" threadid) = ccall createIOThread( MyCapability() "ptr",
                                RtsFlags_GcFlags_initialStkSize(RtsFlags),
661
                                closure "ptr");
662 663

  /* start blocked if the current thread is blocked */
664
  StgTSO_flags(threadid) = %lobits16(
ian@well-typed.com's avatar
ian@well-typed.com committed
665
     TO_W_(StgTSO_flags(threadid)) |
666
     TO_W_(StgTSO_flags(CurrentTSO)) & (TSO_BLOCKEX | TSO_INTERRUPTIBLE));
667

668
  ccall scheduleThreadOn(MyCapability() "ptr", cpu, threadid "ptr");
669

670 671
  // context switch soon, but not immediately: we don't want every
  // forkIO to force a context-switch.
672
  Capability_context_switch(MyCapability()) = 1 :: CInt;
ian@well-typed.com's avatar
ian@well-typed.com committed
673

674
  return (threadid);
675 676
}

677
stg_yieldzh ()
678
{
679 680 681 682 683
  // when we yield to the scheduler, we have to tell it to put the
  // current thread to the back of the queue by setting the
  // context_switch flag.  If we don't do this, it will run the same
  // thread again.
  Capability_context_switch(MyCapability()) = 1 :: CInt;
684
  jump stg_yield_noregs();
685 686
}

687
stg_myThreadIdzh ()
688
{
689
  return (CurrentTSO);
690 691
}

692
stg_labelThreadzh ( gcptr threadid, W_ addr )
693
{
694
#if defined(DEBUG) || defined(TRACING) || defined(DTRACE)
695
  ccall labelThread(MyCapability() "ptr", threadid "ptr", addr "ptr");
696
#endif
697
  return ();
698 699
}

700
stg_isCurrentThreadBoundzh (/* no args */)
701 702
{
  W_ r;
703 704
  (r) = ccall isThreadBound(CurrentTSO);
  return (r);
705 706
}

707
stg_threadStatuszh ( gcptr tso )
708 709 710
{
    W_ why_blocked;
    W_ what_next;
711
    W_ ret, cap, locked;
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728

    what_next   = TO_W_(StgTSO_what_next(tso));
    why_blocked = TO_W_(StgTSO_why_blocked(tso));
    // Note: these two reads are not atomic, so they might end up
    // being inconsistent.  It doesn't matter, since we
    // only return one or the other.  If we wanted to return the
    // contents of block_info too, then we'd have to do some synchronisation.

    if (what_next == ThreadComplete) {
        ret = 16;  // NB. magic, matches up with GHC.Conc.threadStatus
    } else {
        if (what_next == ThreadKilled) {
            ret = 17;
        } else {
            ret = why_blocked;
        }
    }
729 730 731 732 733 734 735 736 737

    cap = TO_W_(Capability_no(StgTSO_cap(tso)));

    if ((TO_W_(StgTSO_flags(tso)) & TSO_LOCKED) != 0) {
        locked = 1;
    } else {
        locked = 0;
    }

738
    return (ret,cap,locked);
739
}
740 741 742 743 744

/* -----------------------------------------------------------------------------
 * TVar primitives
 * -------------------------------------------------------------------------- */

745 746 747
// Catch retry frame -----------------------------------------------------------

#define CATCH_RETRY_FRAME_FIELDS(w_,p_,info_ptr,        \
Simon Marlow's avatar
Simon Marlow committed
748
                                 p1, p2,                \
749 750 751 752
                                 running_alt_code,      \
                                 first_code,            \
                                 alt_code)              \
  w_ info_ptr,                                          \
Simon Marlow's avatar
Simon Marlow committed
753
  PROF_HDR_FIELDS(w_,p1,p2)                             \
754 755 756
  w_ running_alt_code,                                  \
  p_ first_code,                                        \
  p_ alt_code
757 758


759
INFO_TABLE_RET(stg_catch_retry_frame, CATCH_RETRY_FRAME,
760
               CATCH_RETRY_FRAME_FIELDS(W_,P_,
Simon Marlow's avatar
Simon Marlow committed
761
                                        info_ptr, p1, p2,
762 763 764 765
                                        running_alt_code,
                                        first_code,
                                        alt_code))
    return (P_ ret)
766
{
767 768
    W_ r;
    gcptr trec, outer, arg;
769

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
    trec = StgTSO_trec(CurrentTSO);
    outer  = StgTRecHeader_enclosing_trec(trec);
    (r) = ccall stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr");
    if (r != 0) {
        // Succeeded (either first branch or second branch)
        StgTSO_trec(CurrentTSO) = outer;
        return (ret);
    } else {
        // Did not commit: re-execute
        P_ new_trec;
        ("ptr" new_trec) = ccall stmStartTransaction(MyCapability() "ptr",
                                                           outer "ptr");
        StgTSO_trec(CurrentTSO) = new_trec;
        if (running_alt_code != 0) {
            jump stg_ap_v_fast
Simon Marlow's avatar
Simon Marlow committed
785
                (CATCH_RETRY_FRAME_FIELDS(,,info_ptr, p1, p2,
786 787 788 789 790 791
                                          running_alt_code,
                                          first_code,
                                          alt_code))
                (alt_code);
        } else {
            jump stg_ap_v_fast
Simon Marlow's avatar
Simon Marlow committed
792
                (CATCH_RETRY_FRAME_FIELDS(,,info_ptr, p1, p2,
793 794 795 796 797 798 799
                                          running_alt_code,
                                          first_code,
                                          alt_code))
                (first_code);
        }
    }
}
800

Simon Marlow's avatar
Simon Marlow committed
801
// Atomically frame ------------------------------------------------------------
802

803
// This must match StgAtomicallyFrame in Closures.h
Simon Marlow's avatar
Simon Marlow committed
804
#define ATOMICALLY_FRAME_FIELDS(w_,p_,info_ptr,p1,p2,code,next,result)  \
805
  w_ info_ptr,                                                          \
Simon Marlow's avatar
Simon Marlow committed
806
  PROF_HDR_FIELDS(w_,p1,p2)                                             \
807 808 809 810 811
  p_ code,                                                              \
  p_ next,                                                              \
  p_ result


812
INFO_TABLE_RET(stg_atomically_frame, ATOMICALLY_FRAME,
813 814
               // layout of the frame, and bind the field names
               ATOMICALLY_FRAME_FIELDS(W_,P_,
Simon Marlow's avatar
Simon Marlow committed
815
                                       info_ptr, p1, p2,
816 817 818 819
                                       code,
                                       next_invariant,
                                       frame_result))
    return (P_ result) // value returned to the frame
820
{
821 822
  W_ valid;
  gcptr trec, outer, next_invariant, q;
823

824
  trec   = StgTSO_trec(CurrentTSO);
825
  outer  = StgTRecHeader_enclosing_trec(trec);
tharris@microsoft.com's avatar
tharris@microsoft.com committed
826 827 828

  if (outer == NO_TREC) {
    /* First time back at the atomically frame -- pick up invariants */
829 830 831
    ("ptr" next_invariant) =
        ccall stmGetInvariantsToCheck(MyCapability() "ptr", trec "ptr");
    frame_result = result;
832 833

  } else {
tharris@microsoft.com's avatar
tharris@microsoft.com committed
834 835 836
    /* Second/subsequent time back at the atomically frame -- abort the
     * tx that's checking the invariant and move on to the next one */
    StgTSO_trec(CurrentTSO) = outer;
837 838
    StgInvariantCheckQueue_my_execution(next_invariant) = trec;
    ccall stmAbortTransaction(MyCapability() "ptr", trec "ptr");
tharris@microsoft.com's avatar
tharris@microsoft.com committed
839 840
    /* Don't free trec -- it's linked from q and will be stashed in the
     * invariant if we eventually commit. */
841 842
    next_invariant =
       StgInvariantCheckQueue_next_queue_entry(next_invariant);
tharris@microsoft.com's avatar
tharris@microsoft.com committed
843 844 845
    trec = outer;
  }

846
  if (next_invariant != END_INVARIANT_CHECK_QUEUE) {
tharris@microsoft.com's avatar
tharris@microsoft.com committed
847
    /* We can't commit yet: another invariant to check */
848
    ("ptr" trec) = ccall stmStartTransaction(MyCapability() "ptr", trec "ptr");
849
    StgTSO_trec(CurrentTSO) = trec;
850 851
    q = StgInvariantCheckQueue_invariant(next_invariant);
    jump stg_ap_v_fast
Simon Marlow's avatar
Simon Marlow committed
852 853
        (ATOMICALLY_FRAME_FIELDS(,,info_ptr,p1,p2,
                                 code,next_invariant,frame_result))
854
        (StgAtomicInvariant_code(q));
tharris@microsoft.com's avatar
tharris@microsoft.com committed
855 856 857 858

  } else {

    /* We've got no more invariants to check, try to commit */
859
    (valid) = ccall stmCommitTransaction(MyCapability() "ptr", trec "ptr");
tharris@microsoft.com's avatar
tharris@microsoft.com committed
860 861 862
    if (valid != 0) {
      /* Transaction was valid: commit succeeded */
      StgTSO_trec(CurrentTSO) = NO_TREC;
863
      return (frame_result);
tharris@microsoft.com's avatar
tharris@microsoft.com committed
864 865
    } else {
      /* Transaction was not valid: try again */
866
      ("ptr" trec) = ccall stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr");
tharris@microsoft.com's avatar
tharris@microsoft.com committed
867
      StgTSO_trec(CurrentTSO) = trec;
868 869 870 871 872
      next_invariant = END_INVARIANT_CHECK_QUEUE;

      jump stg_ap_v_fast
          // push the StgAtomicallyFrame again: the code generator is
          // clever enough to only assign the fields that have changed.
Simon Marlow's avatar
Simon Marlow committed
873 874
          (ATOMICALLY_FRAME_FIELDS(,,info_ptr,p1,p2,
                                   code,next_invariant,frame_result))
875
          (code);
tharris@microsoft.com's avatar
tharris@microsoft.com committed
876
    }
877 878 879
  }
}

880

881
INFO_TABLE_RET(stg_atomically_waiting_frame, ATOMICALLY_FRAME,
882 883
               // layout of the frame, and bind the field names
               ATOMICALLY_FRAME_FIELDS(W_,P_,
Simon Marlow's avatar
Simon Marlow committed
884
                                       info_ptr, p1, p2,