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

#include "Cmm.h"
25
#include "MachDeps.h"
Simon Marlow's avatar
Simon Marlow committed
26
#include "SMPClosureOps.h"
27

Ben Gamari's avatar
Ben Gamari committed
28
#if defined(__PIC__)
29 30
import pthread_mutex_lock;
import pthread_mutex_unlock;
31
#endif
32
import CLOSURE base_ControlziExceptionziBase_nestedAtomically_closure;
33
import CLOSURE base_GHCziIOziException_heapOverflow_closure;
34 35
import CLOSURE base_GHCziIOziException_blockedIndefinitelyOnMVar_closure;
import CLOSURE base_GHCziIOPort_doubleReadException_closure;
36 37
import AcquireSRWLockExclusive;
import ReleaseSRWLockExclusive;
38
import CLOSURE ghczmprim_GHCziTypes_False_closure;
Ben Gamari's avatar
Ben Gamari committed
39
#if defined(PROFILING)
40 41
import CLOSURE CCS_MAIN;
#endif
42

43 44 45 46 47 48 49 50 51 52 53 54 55
/*-----------------------------------------------------------------------------
  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.
 */

56
stg_newByteArrayzh ( W_ n )
57
{
58 59 60 61 62
    W_ words, payload_words;
    gcptr p;

    MAYBE_GC_N(stg_newByteArrayzh, n);

63
    payload_words = ROUNDUP_BYTES_TO_WDS(n);
siddhanathan's avatar
siddhanathan committed
64
    words = BYTES_TO_WDS(SIZEOF_StgArrBytes) + payload_words;
65 66 67 68
    ("ptr" p) = ccall allocateMightFail(MyCapability() "ptr", words);
    if (p == NULL) {
        jump stg_raisezh(base_GHCziIOziException_heapOverflow_closure);
    }
siddhanathan's avatar
siddhanathan committed
69
    TICK_ALLOC_PRIM(SIZEOF_StgArrBytes,WDS(payload_words),0);
70
    SET_HDR(p, stg_ARR_WORDS_info, CCCS);
siddhanathan's avatar
siddhanathan committed
71
    StgArrBytes_bytes(p) = n;
72
    return (p);
73 74
}

Simon Marlow's avatar
Simon Marlow committed
75 76 77
#define BA_ALIGN 16
#define BA_MASK  (BA_ALIGN-1)

78
stg_newPinnedByteArrayzh ( W_ n )
79
{
80 81 82 83
    W_ words, bytes, payload_words;
    gcptr p;

    MAYBE_GC_N(stg_newPinnedByteArrayzh, n);
84

85
    bytes = n;
86 87 88 89
    /* 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: */
siddhanathan's avatar
siddhanathan committed
90
    bytes = bytes + SIZEOF_StgArrBytes;
91 92
    /* Now we convert to a number of words: */
    words = ROUNDUP_BYTES_TO_WDS(bytes);
Simon Marlow's avatar
Simon Marlow committed
93

94
    ("ptr" p) = ccall allocatePinned(MyCapability() "ptr", words, BA_ALIGN, SIZEOF_StgArrBytes);
95 96 97
    if (p == NULL) {
        jump stg_raisezh(base_GHCziIOziException_heapOverflow_closure);
    }
siddhanathan's avatar
siddhanathan committed
98
    TICK_ALLOC_PRIM(SIZEOF_StgArrBytes,WDS(payload_words),0);
Simon Marlow's avatar
Simon Marlow committed
99

100
    /* No write barrier needed since this is a new allocation. */
101
    SET_HDR(p, stg_ARR_WORDS_info, CCCS);
siddhanathan's avatar
siddhanathan committed
102
    StgArrBytes_bytes(p) = n;
103
    return (p);
Simon Marlow's avatar
Simon Marlow committed
104 105
}

106
stg_newAlignedPinnedByteArrayzh ( W_ n, W_ alignment )
Simon Marlow's avatar
Simon Marlow committed
107
{
108 109
    W_ words, bytes, payload_words;
    gcptr p;
Simon Marlow's avatar
Simon Marlow committed
110

111
    again: MAYBE_GC(again);
Simon Marlow's avatar
Simon Marlow committed
112

113 114 115
    /* 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. */
116
    if (alignment <= SIZEOF_W) { alignment = SIZEOF_W; }
117

118 119
    bytes = n;

120 121
    /* 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
122

123 124
    /* When we actually allocate memory, we need to allow space for the
       header: */
siddhanathan's avatar
siddhanathan committed
125
    bytes = bytes + SIZEOF_StgArrBytes;
126 127
    /* Now we convert to a number of words: */
    words = ROUNDUP_BYTES_TO_WDS(bytes);
128

129
    ("ptr" p) = ccall allocatePinned(MyCapability() "ptr", words, alignment, SIZEOF_StgArrBytes);
130 131 132
    if (p == NULL) {
        jump stg_raisezh(base_GHCziIOziException_heapOverflow_closure);
    }
siddhanathan's avatar
siddhanathan committed
133
    TICK_ALLOC_PRIM(SIZEOF_StgArrBytes,WDS(payload_words),0);
134

135
    /* No write barrier needed since this is a new allocation. */
136
    SET_HDR(p, stg_ARR_WORDS_info, CCCS);
siddhanathan's avatar
siddhanathan committed
137
    StgArrBytes_bytes(p) = n;
138
    return (p);
139 140
}

141 142
stg_isByteArrayPinnedzh ( gcptr ba )
// ByteArray# s -> Int#
143 144
{
    W_ bd, flags;
145
    bd = Bdescr(ba);
146
    // Pinned byte arrays live in blocks with the BF_PINNED flag set.
Gabor Greif's avatar
Gabor Greif committed
147
    // We also consider BF_LARGE objects to be immovable. See #13894.
148
    // See the comment in Storage.c:allocatePinned.
149
    // We also consider BF_COMPACT objects to be immovable. See #14900.
150
    flags = TO_W_(bdescr_flags(bd));
151
    return (flags & (BF_PINNED | BF_LARGE | BF_COMPACT) != 0);
152 153
}

154 155 156 157 158 159
stg_isMutableByteArrayPinnedzh ( gcptr mba )
// MutableByteArray# s -> Int#
{
    jump stg_isByteArrayPinnedzh(mba);
}

160 161
/* Note [LDV profiling and resizing arrays]
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
162
 *
163 164 165
 * As far as the LDV profiler is concerned arrays are "inherently used" which
 * means we don't track their time of use and eventual destruction. We just
 * assume they get used.
166
 *
167 168
 * Thus it is not necessary to call LDV_RECORD_CREATE when resizing them as we
 * used to as the LDV profiler will essentially ignore arrays anyways.
169 170
 */

171 172 173 174
// shrink size of MutableByteArray in-place
stg_shrinkMutableByteArrayzh ( gcptr mba, W_ new_size )
// MutableByteArray# s -> Int# -> State# s -> State# s
{
siddhanathan's avatar
siddhanathan committed
175
   ASSERT(new_size <= StgArrBytes_bytes(mba));
176

177 178
   OVERWRITING_CLOSURE_MUTABLE(mba, (BYTES_TO_WDS(SIZEOF_StgArrBytes) +
                                     ROUNDUP_BYTES_TO_WDS(new_size)));
siddhanathan's avatar
siddhanathan committed
179
   StgArrBytes_bytes(mba) = new_size;
180
   // No need to call LDV_RECORD_CREATE. See Note [LDV profiling and resizing arrays]
181 182 183 184 185 186 187 188 189 190

   return ();
}

// resize MutableByteArray
//
// The returned MutableByteArray is either the original
// MutableByteArray resized in-place or, if not possible, a newly
// allocated (unpinned) MutableByteArray (with the original content
// copied over)
Gabor Greif's avatar
Gabor Greif committed
191
stg_resizzeMutableByteArrayzh ( gcptr mba, W_ new_size )
192 193 194 195 196 197 198 199 200
// MutableByteArray# s -> Int# -> State# s -> (# State# s,MutableByteArray# s #)
{
   W_ new_size_wds;

   ASSERT(new_size >= 0);

   new_size_wds = ROUNDUP_BYTES_TO_WDS(new_size);

   if (new_size_wds <= BYTE_ARR_WDS(mba)) {
201 202
      OVERWRITING_CLOSURE_MUTABLE(mba, (BYTES_TO_WDS(SIZEOF_StgArrBytes) +
                                        new_size_wds));
siddhanathan's avatar
siddhanathan committed
203
      StgArrBytes_bytes(mba) = new_size;
204
      // No need to call LDV_RECORD_CREATE. See Note [LDV profiling and resizing arrays]
205 206 207 208 209 210 211 212 213 214 215 216 217

      return (mba);
   } else {
      (P_ new_mba) = call stg_newByteArrayzh(new_size);

      // maybe at some point in the future we may be able to grow the
      // MBA in-place w/o copying if we know the space after the
      // current MBA is still available, as often we want to grow the
      // MBA shortly after we allocated the original MBA. So maybe no
      // further allocations have occurred by then.

      // copy over old content
      prim %memcpy(BYTE_ARR_CTS(new_mba), BYTE_ARR_CTS(mba),
siddhanathan's avatar
siddhanathan committed
218
                   StgArrBytes_bytes(mba), SIZEOF_W);
219 220 221 222 223

      return (new_mba);
   }
}

224 225 226 227 228 229
// shrink size of SmallMutableArray in-place
stg_shrinkSmallMutableArrayzh ( gcptr mba, W_ new_size )
// SmallMutableArray# s -> Int# -> State# s -> State# s
{
   ASSERT(new_size <= StgSmallMutArrPtrs_ptrs(mba));

230 231
   OVERWRITING_CLOSURE_MUTABLE(mba, (BYTES_TO_WDS(SIZEOF_StgSmallMutArrPtrs) +
                                     new_size));
232
   StgSmallMutArrPtrs_ptrs(mba) = new_size;
233
   // No need to call LDV_RECORD_CREATE. See Note [LDV profiling and resizing arrays]
234 235 236 237

   return ();
}

238 239 240 241 242
// 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# #) */
{
243
    W_ p, h;
244

siddhanathan's avatar
siddhanathan committed
245
    p = arr + SIZEOF_StgArrBytes + WDS(ind);
246
    (h) = prim %cmpxchgW(p, old, new);
247 248 249 250

    return(h);
}

251

252
stg_newArrayzh ( W_ n /* words */, gcptr init )
253
{
254 255
    W_ words, size, p;
    gcptr arr;
256

257
    again: MAYBE_GC(again);
258

259 260 261 262 263
    // 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;
264 265 266 267
    ("ptr" arr) = ccall allocateMightFail(MyCapability() "ptr",words);
    if (arr == NULL) {
        jump stg_raisezh(base_GHCziIOziException_heapOverflow_closure);
    }
tibbe's avatar
tibbe committed
268
    TICK_ALLOC_PRIM(SIZEOF_StgMutArrPtrs, WDS(size), 0);
269

270
    /* No write barrier needed since this is a new allocation. */
271
    SET_HDR(arr, stg_MUT_ARR_PTRS_DIRTY_info, CCCS);
272
    StgMutArrPtrs_ptrs(arr) = n;
273
    StgMutArrPtrs_size(arr) = size;
274

275
    // Initialise all elements of the array with the value in R2
276 277
    p = arr + SIZEOF_StgMutArrPtrs;
  for:
278
    if (p < arr + SIZEOF_StgMutArrPtrs + WDS(n)) (likely: True) {
ian@well-typed.com's avatar
ian@well-typed.com committed
279 280 281
        W_[p] = init;
        p = p + WDS(1);
        goto for;
282 283
    }

284
    return (arr);
285 286
}

287
stg_unsafeThawArrayzh ( gcptr arr )
288
{
289 290 291 292 293 294
    // A MUT_ARR_PTRS always lives on a mut_list, but a MUT_ARR_PTRS_FROZEN
    // doesn't. To decide whether to add the thawed array to a mut_list we check
    // the info table. MUT_ARR_PTRS_FROZEN_DIRTY means it's already on a
    // mut_list so no need to add it again. MUT_ARR_PTRS_FROZEN_CLEAN means it's
    // not and we should add it to a mut_list.
    if (StgHeader_info(arr) != stg_MUT_ARR_PTRS_FROZEN_DIRTY_info) {
295
        SET_INFO(arr,stg_MUT_ARR_PTRS_DIRTY_info);
296
        // must be done after SET_INFO, because it ASSERTs closure_MUTABLE():
297
        recordMutable(arr);
ian@well-typed.com's avatar
ian@well-typed.com committed
298
        return (arr);
tibbe's avatar
tibbe committed
299
    } else {
ian@well-typed.com's avatar
ian@well-typed.com committed
300 301
        SET_INFO(arr,stg_MUT_ARR_PTRS_DIRTY_info);
        return (arr);
tibbe's avatar
tibbe committed
302
    }
303 304
}

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
stg_copyArrayzh ( gcptr src, W_ src_off, gcptr dst, W_ dst_off, W_ n )
{
    copyArray(src, src_off, dst, dst_off, n)
}

stg_copyMutableArrayzh ( gcptr src, W_ src_off, gcptr dst, W_ dst_off, W_ n )
{
    copyMutableArray(src, src_off, dst, dst_off, n)
}

stg_copyArrayArrayzh ( gcptr src, W_ src_off, gcptr dst, W_ dst_off, W_ n )
{
    copyArray(src, src_off, dst, dst_off, n)
}

stg_copyMutableArrayArrayzh ( gcptr src, W_ src_off, gcptr dst, W_ dst_off, W_ n )
{
    copyMutableArray(src, src_off, dst, dst_off, n)
}

325 326
stg_cloneArrayzh ( gcptr src, W_ offset, W_ n )
{
327
    cloneArray(stg_MUT_ARR_PTRS_FROZEN_CLEAN_info, src, offset, n)
328 329 330 331
}

stg_cloneMutableArrayzh ( gcptr src, W_ offset, W_ n )
{
tibbe's avatar
tibbe committed
332
    cloneArray(stg_MUT_ARR_PTRS_DIRTY_info, src, offset, n)
333 334 335 336 337
}

// We have to escape the "z" in the name.
stg_freezzeArrayzh ( gcptr src, W_ offset, W_ n )
{
338
    cloneArray(stg_MUT_ARR_PTRS_FROZEN_CLEAN_info, src, offset, n)
339 340 341 342
}

stg_thawArrayzh ( gcptr src, W_ offset, W_ n )
{
tibbe's avatar
tibbe committed
343
    cloneArray(stg_MUT_ARR_PTRS_DIRTY_info, src, offset, n)
344 345
}

346
// RRN: Uses the ticketed approach; see casMutVar
347
stg_casArrayzh ( gcptr arr, W_ ind, gcptr old, gcptr new )
348
/* MutableArray# s a -> Int# -> a -> a -> State# s -> (# State# s, Int#, Any a #) */
349
{
350 351
    gcptr h;
    W_ p, len;
352 353

    p = arr + SIZEOF_StgMutArrPtrs + WDS(ind);
354
    (h) = prim %cmpxchgW(p, old, new);
355

356 357
    if (h != old) {
        // Failure, return what was there instead of 'old':
358
        return (1,h);
359 360
    } else {
        // Compare and Swap Succeeded:
rrnewton's avatar
rrnewton committed
361 362
        SET_HDR(arr, stg_MUT_ARR_PTRS_DIRTY_info, CCCS);
        len = StgMutArrPtrs_ptrs(arr);
363

rrnewton's avatar
rrnewton committed
364 365
        // 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;
366 367 368 369

        // Concurrent GC write barrier
        updateRemembSetPushPtr(old);

370
        return (0,new);
371 372 373
    }
}

374
stg_newArrayArrayzh ( W_ n /* words */ )
375
{
376 377
    W_ words, size, p;
    gcptr arr;
378

379
    MAYBE_GC_N(stg_newArrayArrayzh, n);
380 381 382 383 384 385

    // 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;
386 387 388 389
    ("ptr" arr) = ccall allocateMightFail(MyCapability() "ptr",words);
    if (arr == NULL) {
        jump stg_raisezh(base_GHCziIOziException_heapOverflow_closure);
    }
tibbe's avatar
tibbe committed
390
    TICK_ALLOC_PRIM(SIZEOF_StgMutArrPtrs, WDS(size), 0);
391 392 393 394 395 396 397 398

    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:
399
    if (p < arr + SIZEOF_StgMutArrPtrs + WDS(n)) (likely: True) {
ian@well-typed.com's avatar
ian@well-typed.com committed
400 401 402
        W_[p] = arr;
        p = p + WDS(1);
        goto for;
403 404
    }

405
    return (arr);
406 407
}

pumpkin's avatar
pumpkin committed
408

409 410 411 412 413 414 415 416 417 418 419 420
/* -----------------------------------------------------------------------------
   SmallArray primitives
   -------------------------------------------------------------------------- */

stg_newSmallArrayzh ( W_ n /* words */, gcptr init )
{
    W_ words, size, p;
    gcptr arr;

    again: MAYBE_GC(again);

    words = BYTES_TO_WDS(SIZEOF_StgSmallMutArrPtrs) + n;
421
    ("ptr" arr) = ccall allocateMightFail(MyCapability() "ptr",words);
422
    if (arr == NULL) (likely: False) {
423 424
        jump stg_raisezh(base_GHCziIOziException_heapOverflow_closure);
    }
425 426
    TICK_ALLOC_PRIM(SIZEOF_StgSmallMutArrPtrs, WDS(n), 0);

427
    /* No write barrier needed since this is a new allocation. */
428 429 430
    SET_HDR(arr, stg_SMALL_MUT_ARR_PTRS_DIRTY_info, CCCS);
    StgSmallMutArrPtrs_ptrs(arr) = n;

431
    // Initialise all elements of the array with the value in R2
432
    p = arr + SIZEOF_StgSmallMutArrPtrs;
433 434 435
    // Avoid the shift for `WDS(n)` in the inner loop
    W_ limit;
    limit = arr + SIZEOF_StgSmallMutArrPtrs + WDS(n);
436
  for:
437
    if (p < limit) (likely: True) {
438 439 440 441 442 443 444 445 446 447 448
        W_[p] = init;
        p = p + WDS(1);
        goto for;
    }

    return (arr);
}

stg_unsafeThawSmallArrayzh ( gcptr arr )
{
    // See stg_unsafeThawArrayzh
449
    if (StgHeader_info(arr) != stg_SMALL_MUT_ARR_PTRS_FROZEN_DIRTY_info) {
450 451 452 453 454 455 456 457 458 459 460 461
        SET_INFO(arr, stg_SMALL_MUT_ARR_PTRS_DIRTY_info);
        recordMutable(arr);
        // must be done after SET_INFO, because it ASSERTs closure_MUTABLE()
        return (arr);
    } else {
        SET_INFO(arr, stg_SMALL_MUT_ARR_PTRS_DIRTY_info);
        return (arr);
    }
}

stg_cloneSmallArrayzh ( gcptr src, W_ offset, W_ n )
{
462
    cloneSmallArray(stg_SMALL_MUT_ARR_PTRS_FROZEN_CLEAN_info, src, offset, n)
463 464 465 466 467 468 469 470 471 472
}

stg_cloneSmallMutableArrayzh ( gcptr src, W_ offset, W_ n )
{
    cloneSmallArray(stg_SMALL_MUT_ARR_PTRS_DIRTY_info, src, offset, n)
}

// We have to escape the "z" in the name.
stg_freezzeSmallArrayzh ( gcptr src, W_ offset, W_ n )
{
473
    cloneSmallArray(stg_SMALL_MUT_ARR_PTRS_FROZEN_CLEAN_info, src, offset, n)
474 475 476 477 478 479 480
}

stg_thawSmallArrayzh ( gcptr src, W_ offset, W_ n )
{
    cloneSmallArray(stg_SMALL_MUT_ARR_PTRS_DIRTY_info, src, offset, n)
}

481 482 483 484 485 486 487 488 489 490 491
// Concurrent GC write barrier for pointer array copies
//
// hdr_size in bytes. dst_off in words, n in words.
stg_copyArray_barrier ( W_ hdr_size, gcptr dst, W_ dst_off, W_ n)
{
    W_ end, p;
    ASSERT(n > 0);  // Assumes n==0 is handled by caller
    p = dst + hdr_size + WDS(dst_off);
    end = p + WDS(n);

again:
492
    IF_NONMOVING_WRITE_BARRIER_ENABLED {
493 494 495 496 497 498 499 500 501 502
        ccall updateRemembSetPushClosure_(BaseReg "ptr", W_[p] "ptr");
    }
    p = p + WDS(1);
    if (p < end) {
        goto again;
    }

    return ();
}

503 504 505 506
stg_copySmallArrayzh ( gcptr src, W_ src_off, gcptr dst, W_ dst_off, W_ n)
{
    W_ dst_p, src_p, bytes;

507
    if (n > 0) {
508
        IF_NONMOVING_WRITE_BARRIER_ENABLED {
509 510 511
            call stg_copyArray_barrier(SIZEOF_StgSmallMutArrPtrs,
                                      dst, dst_off, n);
        }
512

513 514 515 516 517 518 519
        SET_INFO(dst, stg_SMALL_MUT_ARR_PTRS_DIRTY_info);

        dst_p = dst + SIZEOF_StgSmallMutArrPtrs + WDS(dst_off);
        src_p = src + SIZEOF_StgSmallMutArrPtrs + WDS(src_off);
        bytes = WDS(n);
        prim %memcpy(dst_p, src_p, bytes, SIZEOF_W);
    }
520 521 522 523 524 525 526 527

    return ();
}

stg_copySmallMutableArrayzh ( gcptr src, W_ src_off, gcptr dst, W_ dst_off, W_ n)
{
    W_ dst_p, src_p, bytes;

528
    if (n > 0) {
529
        IF_NONMOVING_WRITE_BARRIER_ENABLED {
530 531 532
            call stg_copyArray_barrier(SIZEOF_StgSmallMutArrPtrs,
                                      dst, dst_off, n);
        }
533

534 535 536 537 538 539 540 541 542 543
        SET_INFO(dst, stg_SMALL_MUT_ARR_PTRS_DIRTY_info);

        dst_p = dst + SIZEOF_StgSmallMutArrPtrs + WDS(dst_off);
        src_p = src + SIZEOF_StgSmallMutArrPtrs + WDS(src_off);
        bytes = WDS(n);
        if (src == dst) {
            prim %memmove(dst_p, src_p, bytes, SIZEOF_W);
        } else {
            prim %memcpy(dst_p, src_p, bytes, SIZEOF_W);
        }
544 545 546 547 548 549 550 551 552 553 554 555 556
    }

    return ();
}

// RRN: Uses the ticketed approach; see casMutVar
stg_casSmallArrayzh ( gcptr arr, W_ ind, gcptr old, gcptr new )
/* SmallMutableArray# s a -> Int# -> a -> a -> State# s -> (# State# s, Int#, Any a #) */
{
    gcptr h;
    W_ p, len;

    p = arr + SIZEOF_StgSmallMutArrPtrs + WDS(ind);
557
    (h) = prim %cmpxchgW(p, old, new);
558 559 560 561 562 563 564

    if (h != old) {
        // Failure, return what was there instead of 'old':
        return (1,h);
    } else {
        // Compare and Swap Succeeded:
        SET_HDR(arr, stg_SMALL_MUT_ARR_PTRS_DIRTY_info, CCCS);
565 566 567 568

        // Concurrent GC write barrier
        updateRemembSetPushPtr(old);

569 570 571 572 573
        return (0,new);
    }
}


574 575 576 577
/* -----------------------------------------------------------------------------
   MutVar primitives
   -------------------------------------------------------------------------- */

578
stg_newMutVarzh ( gcptr init )
579 580 581
{
    W_ mv;

582
    ALLOC_PRIM_P (SIZEOF_StgMutVar, stg_newMutVarzh, init);
583 584

    mv = Hp - SIZEOF_StgMutVar + WDS(1);
585
    /* No write barrier needed since this is a new allocation. */
586
    SET_HDR(mv,stg_MUT_VAR_DIRTY_info,CCCS);
587
    StgMutVar_var(mv) = init;
ian@well-typed.com's avatar
ian@well-typed.com committed
588

589
    return (mv);
590 591
}

592 593 594 595 596
// 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.
597
stg_casMutVarzh ( gcptr mv, gcptr old, gcptr new )
598
 /* MutVar# s a -> a -> a -> State# s -> (# State#, Int#, Any a #) */
Simon Marlow's avatar
Simon Marlow committed
599
{
600
#if defined(THREADED_RTS)
601
    gcptr h;
Simon Marlow's avatar
Simon Marlow committed
602

603
    (h) = prim %cmpxchgW(mv + SIZEOF_StgHeader + OFFSET_StgMutVar_var, old, new);
Simon Marlow's avatar
Simon Marlow committed
604
    if (h != old) {
605
        return (1,h);
Simon Marlow's avatar
Simon Marlow committed
606
    } else {
607
        if (GET_INFO(mv) == stg_MUT_VAR_CLEAN_info) {
608
            ccall dirty_MUT_VAR(BaseReg "ptr", mv "ptr", old);
609
        }
610
        return (0,new);
Simon Marlow's avatar
Simon Marlow committed
611
    }
612 613 614 615 616 617 618 619 620
#else
    gcptr prev_val;

    prev_val = StgMutVar_var(mv);
    if (prev_val != old) {
        return (1,prev_val);
    } else {
        StgMutVar_var(mv) = new;
        if (GET_INFO(mv) == stg_MUT_VAR_CLEAN_info) {
621
            ccall dirty_MUT_VAR(BaseReg "ptr", mv "ptr", old);
622 623 624 625
        }
        return (0,new);
    }
#endif
Simon Marlow's avatar
Simon Marlow committed
626 627
}

David Feuer's avatar
David Feuer committed
628
stg_atomicModifyMutVar2zh ( gcptr mv, gcptr f )
629
{
David Feuer's avatar
David Feuer committed
630
    W_ z, x, y, h;
631

ian@well-typed.com's avatar
ian@well-typed.com committed
632
    /* If x is the current contents of the MutVar#, then
633 634 635
       We want to make the new contents point to

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

637
       and the return value is
ian@well-typed.com's avatar
ian@well-typed.com committed
638

David Feuer's avatar
David Feuer committed
639
         (# x, (f x) #)
640 641 642 643

        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
644
         y = [stg_sel_0 z]   (max (HS + 1) MIN_UPD_SIZE)
645 646
    */

647
#if defined(MIN_UPD_SIZE) && MIN_UPD_SIZE > 1
648
#define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
649 650
#define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),WDS(MIN_UPD_SIZE-1))
#else
651
#define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(1))
652 653 654
#define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),0)
#endif

655
#if defined(MIN_UPD_SIZE) && MIN_UPD_SIZE > 2
656
#define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
657 658
#define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),WDS(MIN_UPD_SIZE-2))
#else
659
#define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(2))
660 661 662
#define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),0)
#endif

David Feuer's avatar
David Feuer committed
663
#define SIZE (THUNK_2_SIZE + THUNK_1_SIZE)
664

tibbe's avatar
tibbe committed
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
    HP_CHK_GEN_TICKY(SIZE);

    TICK_ALLOC_THUNK_2();
    CCCS_ALLOC(THUNK_2_SIZE);
    z = Hp - THUNK_2_SIZE + WDS(1);
    SET_HDR(z, stg_ap_2_upd_info, CCCS);
    LDV_RECORD_CREATE(z);
    StgThunk_payload(z,0) = f;

    TICK_ALLOC_THUNK_1();
    CCCS_ALLOC(THUNK_1_SIZE);
    y = z - THUNK_1_SIZE;
    SET_HDR(y, stg_sel_0_upd_info, CCCS);
    LDV_RECORD_CREATE(y);
    StgThunk_payload(y,0) = z;

  retry:
    x = StgMutVar_var(mv);
    StgThunk_payload(z,1) = x;
Ben Gamari's avatar
Ben Gamari committed
684
#if defined(THREADED_RTS)
685
    (h) = prim %cmpxchgW(mv + SIZEOF_StgHeader + OFFSET_StgMutVar_var, x, y);
tibbe's avatar
tibbe committed
686
    if (h != x) { goto retry; }
687
#else
688
    h = StgMutVar_var(mv);
tibbe's avatar
tibbe committed
689
    StgMutVar_var(mv) = y;
690
#endif
691

tibbe's avatar
tibbe committed
692
    if (GET_INFO(mv) == stg_MUT_VAR_CLEAN_info) {
693
        ccall dirty_MUT_VAR(BaseReg "ptr", mv "ptr", h);
tibbe's avatar
tibbe committed
694
    }
695

David Feuer's avatar
David Feuer committed
696
    return (x,z);
697 698
}

David Feuer's avatar
David Feuer committed
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
stg_atomicModifyMutVarzuzh ( gcptr mv, gcptr f )
{
    W_ z, x, h;

    /* If x is the current contents of the MutVar#, then
       We want to make the new contents point to

         (f x)

       and the return value is

         (# x, (f x) #)

        obviously we can share (f x).

         z = [stg_ap_2 f x]  (max (HS + 2) MIN_UPD_SIZE)
    */

#if defined(MIN_UPD_SIZE) && MIN_UPD_SIZE > 2
#define THUNK_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
#define TICK_ALLOC_THUNK() TICK_ALLOC_UP_THK(WDS(2),WDS(MIN_UPD_SIZE-2))
#else
#define THUNK_SIZE (SIZEOF_StgThunkHeader + WDS(2))
#define TICK_ALLOC_THUNK() TICK_ALLOC_UP_THK(WDS(2),0)
#endif

    HP_CHK_GEN_TICKY(THUNK_SIZE);

    TICK_ALLOC_THUNK();
    CCCS_ALLOC(THUNK_SIZE);
    z = Hp - THUNK_SIZE + WDS(1);
    SET_HDR(z, stg_ap_2_upd_info, CCCS);
    LDV_RECORD_CREATE(z);
    StgThunk_payload(z,0) = f;

  retry:
    x = StgMutVar_var(mv);
    StgThunk_payload(z,1) = x;
#if defined(THREADED_RTS)
    (h) = prim %cmpxchgW(mv + SIZEOF_StgHeader + OFFSET_StgMutVar_var, x, z);
    if (h != x) { goto retry; }
#else
    StgMutVar_var(mv) = z;
#endif

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

    return (x,z);
}


752 753 754 755
/* -----------------------------------------------------------------------------
   Weak Pointer Primitives
   -------------------------------------------------------------------------- */

756 757 758
stg_mkWeakzh ( gcptr key,
               gcptr value,
               gcptr finalizer /* or stg_NO_FINALIZER_closure */ )
759
{
tibbe's avatar
tibbe committed
760
    gcptr w;
761

tibbe's avatar
tibbe committed
762
    ALLOC_PRIM (SIZEOF_StgWeak)
763

tibbe's avatar
tibbe committed
764
    w = Hp - SIZEOF_StgWeak + WDS(1);
765
    // No memory barrier needed as this is a new allocation.
tibbe's avatar
tibbe committed
766
    SET_HDR(w, stg_WEAK_info, CCCS);
767

tibbe's avatar
tibbe committed
768 769 770 771
    StgWeak_key(w)         = key;
    StgWeak_value(w)       = value;
    StgWeak_finalizer(w)   = finalizer;
    StgWeak_cfinalizers(w) = stg_NO_FINALIZER_closure;
772

773 774 775 776 777
    StgWeak_link(w) = Capability_weak_ptr_list_hd(MyCapability());
    Capability_weak_ptr_list_hd(MyCapability()) = w;
    if (Capability_weak_ptr_list_tl(MyCapability()) == NULL) {
        Capability_weak_ptr_list_tl(MyCapability()) = w;
    }
778

779
    IF_DEBUG(weak, ccall debugBelch("New weak pointer at %p\n",w));
780

tibbe's avatar
tibbe committed
781
    return (w);
782 783
}

784
stg_mkWeakNoFinalizzerzh ( gcptr key, gcptr value )
785
{
tibbe's avatar
tibbe committed
786
    jump stg_mkWeakzh (key, value, stg_NO_FINALIZER_closure);
787 788
}

789 790 791 792 793
stg_addCFinalizzerToWeakzh ( W_ fptr,   // finalizer
                             W_ ptr,
                             W_ flag,   // has environment (0 or 1)
                             W_ eptr,
                             gcptr w )
794
{
tibbe's avatar
tibbe committed
795
    W_ c, info;
796

tibbe's avatar
tibbe committed
797
    ALLOC_PRIM (SIZEOF_StgCFinalizerList)
798

tibbe's avatar
tibbe committed
799 800
    c = Hp - SIZEOF_StgCFinalizerList + WDS(1);
    SET_HDR(c, stg_C_FINALIZER_LIST_info, CCCS);
801

tibbe's avatar
tibbe committed
802 803 804 805
    StgCFinalizerList_fptr(c) = fptr;
    StgCFinalizerList_ptr(c) = ptr;
    StgCFinalizerList_eptr(c) = eptr;
    StgCFinalizerList_flag(c) = flag;
806

tibbe's avatar
tibbe committed
807
    LOCK_CLOSURE(w, info);
808

tibbe's avatar
tibbe committed
809 810 811 812 813
    if (info == stg_DEAD_WEAK_info) {
        // Already dead.
        unlockClosure(w, info);
        return (0);
    }
814

815 816 817
    // Write barrier for concurrent non-moving collector
    updateRemembSetPushPtr(StgWeak_cfinalizers(w))

tibbe's avatar
tibbe committed
818 819
    StgCFinalizerList_link(c) = StgWeak_cfinalizers(w);
    StgWeak_cfinalizers(w) = c;
820

tibbe's avatar
tibbe committed
821
    unlockClosure(w, info);
822

tibbe's avatar
tibbe committed
823
    recordMutable(w);
824

825
    IF_DEBUG(weak, ccall debugBelch("Adding a finalizer to %p\n",w));
826

tibbe's avatar
tibbe committed
827
    return (1);
828
}
829

830
stg_finalizzeWeakzh ( gcptr w )
831
{
tibbe's avatar
tibbe committed
832 833
    gcptr f, list;
    W_ info;
834

tibbe's avatar
tibbe committed
835
    LOCK_CLOSURE(w, info);
836

tibbe's avatar
tibbe committed
837 838 839 840 841
    // already dead?
    if (info == stg_DEAD_WEAK_info) {
        unlockClosure(w, info);
        return (0,stg_NO_FINALIZER_closure);
    }
842

tibbe's avatar
tibbe committed
843 844
    f    = StgWeak_finalizer(w);
    list = StgWeak_cfinalizers(w);
845

tibbe's avatar
tibbe committed
846
    // kill it
Ben Gamari's avatar
Ben Gamari committed
847
#if defined(PROFILING)
tibbe's avatar
tibbe committed
848 849 850 851 852 853 854 855
    // @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));
    // Furthermore, when PROFILING is turned on, dead weak pointers are exactly as
    // large as weak pointers, so there is no need to fill the slop, either.
856
    // See stg_DEAD_WEAK_info in StgMiscClosures.cmm.
857 858
#endif

tibbe's avatar
tibbe committed
859 860 861 862
    //
    // Todo: maybe use SET_HDR() and remove LDV_recordCreate()?
    //
    unlockClosure(w, stg_DEAD_WEAK_info);
863

tibbe's avatar
tibbe committed
864
    LDV_RECORD_CREATE(w);
865

tibbe's avatar
tibbe committed
866 867 868
    if (list != stg_NO_FINALIZER_closure) {
      ccall runCFinalizers(list);
    }
869

tibbe's avatar
tibbe committed
870 871 872 873 874 875
    /* return the finalizer */
    if (f == stg_NO_FINALIZER_closure) {
        return (0,stg_NO_FINALIZER_closure);
    } else {
        return (1,f);
    }
876 877
}

878
stg_deRefWeakzh ( gcptr w )
879
{
tibbe's avatar
tibbe committed
880 881
    W_ code, info;
    gcptr val;
882

tibbe's avatar
tibbe committed
883
    info = GET_INFO(w);
884
    prim_read_barrier;
885

tibbe's avatar
tibbe committed
886 887 888 889
    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.
890

tibbe's avatar
tibbe committed
891 892 893
        LOCK_CLOSURE(w, info);
        unlockClosure(w, info);
    }
894

tibbe's avatar
tibbe committed
895 896 897
    if (info == stg_WEAK_info) {
        code = 1;
        val = StgWeak_value(w);
898 899
        // See Note [Concurrent read barrier on deRefWeak#] in NonMovingMark.c
        updateRemembSetPushPtr(val);
tibbe's avatar
tibbe committed
900 901 902 903 904
    } else {
        code = 0;
        val = w;
    }
    return (code,val);
905 906 907
}

/* -----------------------------------------------------------------------------
908
   Floating point operations.
909 910
   -------------------------------------------------------------------------- */

911
stg_decodeFloatzuIntzh ( F_ arg )
ian@well-typed.com's avatar
ian@well-typed.com committed
912
{
913
    W_ p;
914
    W_ tmp, mp_tmp1, mp_tmp_w, r1, r2;
915

916
    STK_CHK_GEN_N (WDS(2));
917

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

tibbe's avatar
tibbe committed
920 921
        mp_tmp1  = tmp + WDS(1);
        mp_tmp_w = tmp;
922

tibbe's avatar
tibbe committed
923 924
        /* Perform the operation */
        ccall __decodeFloat_Int(mp_tmp1 "ptr", mp_tmp_w "ptr", arg);
925

tibbe's avatar
tibbe committed
926 927
        r1 = W_[mp_tmp1];
        r2 = W_[mp_tmp_w];
928
    }
ian@well-typed.com's avatar
ian@well-typed.com committed
929

930
    /* returns: (Int# (mantissa), Int# (exponent)) */
931
    return (r1, r2);
932 933
}

934
stg_decodeDoublezu2Intzh ( D_ arg )
ian@well-typed.com's avatar
ian@well-typed.com committed
935
{
936 937 938
    W_ p, tmp;
    W_ mp_tmp1, mp_tmp2, mp_result1, mp_result2;
    W_ r1, r2, r3, r4;
939

940
    STK_CHK_GEN_N (WDS(4));
941

942 943
    reserve 4 = tmp {

tibbe's avatar
tibbe committed
944 945 946 947
        mp_tmp1    = tmp + WDS(3);
        mp_tmp2    = tmp + WDS(2);
        mp_result1 = tmp + WDS(1);
        mp_result2 = tmp;
948

tibbe's avatar
tibbe committed
949 950 951 952 953 954 955 956 957
        /* 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];
958
    }
959 960 961

    /* returns:
       (Int# (mant sign), Word# (mant high), Word# (mant low), Int# (expn)) */
962
    return (r1, r2, r3, r4);
963 964
}

965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
/* Double# -> (# Int64#, Int# #) */
stg_decodeDoublezuInt64zh ( D_ arg )
{
    CInt exp;
    I64  mant;
    W_   mant_ptr;

    STK_CHK_GEN_N (SIZEOF_INT64);
    reserve BYTES_TO_WDS(SIZEOF_INT64) = mant_ptr {
        (exp) = ccall __decodeDouble_Int64(mant_ptr "ptr", arg);
        mant = I64[mant_ptr];
    }

    return (mant, TO_W_(exp));
}

981 982 983 984
/* -----------------------------------------------------------------------------
 * Concurrency primitives
 * -------------------------------------------------------------------------- */

985
stg_forkzh ( gcptr closure )
986
{
tibbe's avatar
tibbe committed
987
    MAYBE_GC_P(stg_forkzh, closure);
988

tibbe's avatar
tibbe committed
989
    gcptr threadid;
990

tibbe's avatar
tibbe committed
991
    ("ptr" threadid) = ccall createIOThread( MyCapability() "ptr",
992
                                  TO_W_(RtsFlags_GcFlags_initialStkSize(RtsFlags)),
tibbe's avatar
tibbe committed
993
                                  closure "ptr");
994

tibbe's avatar
tibbe committed
995 996 997 998
    /* start blocked if the current thread is blocked */
    StgTSO_flags(threadid) = %lobits16(
        TO_W_(StgTSO_flags(threadid)) |
        TO_W_(StgTSO_flags(CurrentTSO)) & (TSO_BLOCKEX | TSO_INTERRUPTIBLE));
999

tibbe's avatar
tibbe committed
1000
    ccall scheduleThread(MyCapability() "ptr", threadid "ptr");
1001

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

tibbe's avatar
tibbe committed
1006
    return (threadid);
1007 1008
}

1009
stg_forkOnzh ( W_ cpu, gcptr closure )
1010
{
1011
again: MAYBE_GC(again);
1012

tibbe's avatar
tibbe committed
1013
    gcptr threadid;
1014

tibbe's avatar
tibbe committed
1015 1016
    ("ptr" threadid) = ccall createIOThread(
        MyCapability() "ptr",
1017
        TO_W_(RtsFlags_GcFlags_initialStkSize(RtsFlags)),
tibbe's avatar
tibbe committed
1018
        closure "ptr");
1019

tibbe's avatar
tibbe committed
1020 1021 1022 1023
    /* start blocked if the current thread is blocked */
    StgTSO_flags(threadid) = %lobits16(
        TO_W_(StgTSO_flags(threadid)) |
        TO_W_(StgTSO_flags(CurrentTSO)) & (TSO_BLOCKEX | TSO_INTERRUPTIBLE));
1024

tibbe's avatar
tibbe committed
1025
    ccall scheduleThreadOn(MyCapability() "ptr", cpu, threadid "ptr");
1026

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

tibbe's avatar
tibbe committed
1031
    return (threadid);
1032 1033
}

1034
stg_yieldzh ()
1035
{
tibbe's avatar
tibbe committed
1036 1037 1038 1039 1040 1041
    // 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;
    jump stg_yield_noregs();
1042 1043
}

1044
stg_labelThreadzh ( gcptr threadid, W_ addr )
1045
{
1046
#if defined(DEBUG) || defined(TRACING) || defined(DTRACE)
tibbe's avatar
tibbe committed
1047
    ccall labelThread(MyCapability() "ptr", threadid "ptr", addr "ptr");
1048
#endif
tibbe's avatar
tibbe committed
1049
    return ();