Evaluator.c 116 KB
Newer Older
1

2
/* -----------------------------------------------------------------------------
3
 * Bytecode evaluator
4
 *
5 6 7
 * Copyright (c) 1994-1998.
 *
 * $RCSfile: Evaluator.c,v $
8 9
 * $Revision: 1.16 $
 * $Date: 1999/05/11 16:47:50 $
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 * ---------------------------------------------------------------------------*/

#include "Rts.h"

#ifdef INTERPRETER

#include "RtsFlags.h"
#include "RtsUtils.h"
#include "Updates.h"
#include "Storage.h"
#include "SchedAPI.h" /* for createGenThread */
#include "Schedule.h" /* for context_switch  */

#include "Bytecodes.h"
#include "Assembler.h" /* for CFun stuff */
#include "ForeignCall.h"
26
#include "StablePriv.h"
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include "PrimOps.h"   /* for __{encode,decode}{Float,Double} */
#include "Evaluator.h"

#ifdef DEBUG
#include "Printer.h"
#include "Disassembler.h"

#include "Sanity.h"
#include "StgRun.h"
#endif

#include <math.h>    /* These are for primops */
#include <limits.h>  /* These are for primops */
#include <float.h>   /* These are for primops */
#ifdef HAVE_IEEE754_H
#include <ieee754.h> /* These are for primops */
#endif
44 45 46 47 48

#ifdef STANDALONE_INTEGER
#include "sainteger.h"
#else
#error Non-standalone integer not yet supported
49 50
#endif

51

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
/* An incredibly useful abbreviation.
 * Interestingly, there are some uses of END_TSO_QUEUE_closure that
 * can't use it because they use the closure at type StgClosure* or
 * even StgPtr*.  I suspect they should be changed.  -- ADR
 */
#define EndTSOQueue stgCast(StgTSO*,(void*)&END_TSO_QUEUE_closure)

/* These macros are rather delicate - read a good ANSI C book carefully
 * before meddling.
 */
#define mystr(x)      #x
#define mycat(x,y)    x##y
#define mycat2(x,y)   mycat(x,y)
#define mycat3(x,y,z) mycat2(x,mycat2(y,z))

67 68 69 70 71 72 73 74 75 76
#if defined(__GNUC__) && !defined(DEBUG)
#define USE_GCC_LABELS 1
#else
#define USE_GCC_LABELS 0
#endif

/* --------------------------------------------------------------------------
 * Crude profiling stuff (mainly to assess effect of optimiser)
 * ------------------------------------------------------------------------*/

77
#ifdef CRUDE_PROFILING
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

#define M_CPTAB 10000
#define CP_NIL (-1)

int cpInUse = -1;
int cpCurr;

typedef 
   struct { int /*StgVar*/ who; 
            int /*StgVar*/ twho; 
            int enters; 
            int bytes; 
            int insns; 
   }
   CPRecord;

CPRecord cpTab[M_CPTAB];

void cp_init ( void )
{
   int i;
   cpCurr = CP_NIL;
   cpInUse = 0;
   for (i = 0; i < M_CPTAB; i++)
      cpTab[i].who = CP_NIL;
}


void cp_enter ( StgBCO* b )
{
   int is_ret_cont;
   int h;
   int /*StgVar*/ v = b->stgexpr;
   if ((void*)v == NULL) return;

   is_ret_cont = 0;
   if (v > 500000000) {
      is_ret_cont = 1;
      v -= 1000000000;
   }

   if (v < 0) 
      h = (-v) % M_CPTAB; else
      h = v % M_CPTAB;
  
   assert (h >= 0 && h < M_CPTAB);
   while (cpTab[h].who != v && cpTab[h].who != CP_NIL) { 
      h++; if (h == M_CPTAB) h = 0;
   };
   cpCurr = h;
   if (cpTab[cpCurr].who == CP_NIL) {
      cpTab[cpCurr].who = v;
      if (!is_ret_cont) cpTab[cpCurr].enters = 1;
      cpTab[cpCurr].bytes = cpTab[cpCurr].insns = 0;
      cpInUse++;
      if (cpInUse * 2 > M_CPTAB) {
         fprintf(stderr, "\nCRUDE_PROFILING hash table is too full\n" );
         assert(0);
      }
   } else {
      if (!is_ret_cont) cpTab[cpCurr].enters++;
   }   


}

void cp_bill_words ( int nw )
{
   if (cpCurr == CP_NIL) return;
   cpTab[cpCurr].bytes += sizeof(StgWord)*nw;
}


void cp_bill_insns ( int ni )
{
   if (cpCurr == CP_NIL) return;
   cpTab[cpCurr].insns += ni;
}


static double percent ( double a, double b )
{
   return (100.0 * a) / b;
}


void cp_show ( void )
{
   int i, j, max, maxN, totE, totB, totI, cumE, cumB, cumI;
   char nm[200];

   if (cpInUse == -1) return;

   fflush(stdout);fflush(stderr);
   printf ( "\n\n" );

   totE = totB = totI = 0;
   for (i = 0; i < M_CPTAB; i++) {
      cpTab[i].twho = cpTab[i].who;
      if (cpTab[i].who != CP_NIL) {
         totE += cpTab[i].enters;
         totB += cpTab[i].bytes;
         totI += cpTab[i].insns;
      }
   }
  
   printf ( "Totals:   "
            "%6d (%7.3f M) enters,   "
            "%6d (%7.3f M) insns,   "
            "%6d  (%7.3f M) bytes\n\n", 
            totE, totE/1000000.0, totI, totI/1000000.0, totB, totB/1000000.0 );

   cumE = cumB = cumI = 0;
   for (j = 0; j < 32; j++) {

      maxN = max = -1;
      for (i = 0; i < M_CPTAB; i++)
         if (cpTab[i].who != CP_NIL &&
             cpTab[i].enters > maxN) {
            maxN = cpTab[i].enters;
            max = i;
         }
      if (max == -1) break;

      cumE += cpTab[max].enters;
      cumB += cpTab[max].bytes;
      cumI += cpTab[max].insns;

      strcpy(nm, maybeName(cpTab[max].who));
      if (strcmp(nm, "(unknown)")==0)
         sprintf ( nm, "id%d", -cpTab[max].who);

      printf ( "%20s %7d es (%4.1f%%, %4.1f%% c)    "
                    "%7d bs (%4.1f%%, %4.1f%% c)    "
                    "%7d is (%4.1f%%, %4.1f%% c)\n",
                nm,
                cpTab[max].enters, percent(cpTab[max].enters,totE), percent(cumE,totE),
                cpTab[max].bytes,  percent(cpTab[max].bytes,totB),  percent(cumB,totB),
                cpTab[max].insns,  percent(cpTab[max].insns,totI),  percent(cumI,totI)
             );

      cpTab[max].twho = cpTab[max].who;
      cpTab[max].who  = CP_NIL;
   }

   for (i = 0; i < M_CPTAB; i++)
      cpTab[i].who = cpTab[i].twho;

   printf ( "\n" );
}

#endif


232 233 234 235
/* --------------------------------------------------------------------------
 * Hugs Hooks - a bit of a hack
 * ------------------------------------------------------------------------*/

236 237 238
/* A total hack -- this code has an endian dependancy and only works
   on little-endian archs.
*/
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
void setRtsFlags( int x );
void setRtsFlags( int x )
{
    *(int*)(&(RtsFlags.DebugFlags)) = x;
}

/* --------------------------------------------------------------------------
 * RTS Hooks
 *
 * ToDo: figure out why these are being used and crush them!
 * ------------------------------------------------------------------------*/

void OnExitHook (void)
{
}
void StackOverflowHook (unsigned long stack_size)
{
    fprintf(stderr,"Stack Overflow\n");
    exit(1);
}
void OutOfHeapHook (unsigned long request_size, unsigned long heap_size)
{
    fprintf(stderr,"Out Of Heap\n");
    exit(1);
}
void MallocFailHook (unsigned long request_size /* in bytes */, char *msg)
{
    fprintf(stderr,"Malloc Fail\n");
    exit(1);
}
void defaultsHook (void)
{
    /* do nothing */
}

274

275
/* --------------------------------------------------------------------------
276
 * Entering-objects and bytecode interpreter part of evaluator
277 278
 * ------------------------------------------------------------------------*/

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
/* The primop (and all other) parts of this evaluator operate upon the 
   machine state which lives in MainRegTable.  enter is different: 
   to make its closure- and bytecode-interpreting loops go fast, some of that 
   state is pulled out into local vars (viz, registers, if we are lucky).  
   That means that we need to save(load) the local state at every exit(reentry) 
   into enter.  That is, around every procedure call it makes.  Blargh!
   If you modify this code, __be warned__ it will fail in mysterious ways if
   you fail to preserve this property.

   Currently the pulled-out state is Sp in xSp, Su in xSu and SpLim in xSpLim.
   The SSS macros saves the state back in MainRegTable, and LLL loads it from
   MainRegTable.  RETURN(v) does SSS and then returns v; all exits should
   be via RETURN and not plain return.

   Since xSp, xSu and xSpLim are local vars in enter, they are not visible
   in procedures called from enter.  To fix this, either (1) turn the 
   procedures into macros, so they get copied inline, or (2) bracket
   the procedure call with SSS and LLL so that the local and global
   machine states are synchronised for the duration of the call.
*/


/* Forward decls ... */
static        void* enterBCO_primop1 ( int );
static        void* enterBCO_primop2 ( int , int* /*StgThreadReturnCode* */ );
static inline void PopUpdateFrame ( StgClosure* obj );
static inline void PopCatchFrame  ( void );
static inline void PopSeqFrame    ( void );
static inline void PopStopFrame( StgClosure* obj );
static inline void PushTaggedRealWorld( void );
static inline void PushTaggedInteger  ( mpz_ptr );
static inline StgPtr grabHpUpd( nat size );
static inline StgPtr grabHpNonUpd( nat size );
static        StgClosure* raiseAnError   ( StgClosure* errObj );
313

314
static int  enterCountI = 0;
315

316 317 318 319 320 321 322 323 324
#ifdef STANDALONE_INTEGER
StgDouble B__encodeDouble (B* s, I_ e);
void      B__decodeDouble (B* man, I_* exp, StgDouble dbl);
#if ! FLOATS_AS_DOUBLES
StgFloat  B__encodeFloat (B* s, I_ e);
void      B__decodeFloat (B* man, I_* exp, StgFloat flt);
StgPtr    CreateByteArrayToHoldInteger ( int );
B*        IntegerInsideByteArray ( StgPtr );
void      SloppifyIntegerEnd ( StgPtr );
325
#endif
326
#endif
327 328 329



330 331

/* Macros to save/load local state. */
332
#ifdef DEBUG
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
#define SSS { tSp=Sp = xSp; tSu=Su = xSu; tSpLim=SpLim = xSpLim; }
#define LLL { tSp=xSp = Sp; tSu=xSu = Su; tSpLim=xSpLim = SpLim; }
#else
#define SSS { Sp = xSp; Su = xSu; SpLim = xSpLim; }
#define LLL { xSp = Sp; xSu = Su; xSpLim = SpLim; }
#endif

#define RETURN(vvv) { StgThreadReturnCode retVal=(vvv); SSS; return retVal; }


/* Macros to operate directly on the pulled-out machine state.
   These mirror some of the small procedures used in the primop code
   below, except you have to be careful about side effects,
   ie xPushPtr(xStackPtr(n)) won't work!  It certainly isn't the
   same as PushPtr(StackPtr(n)).  Also note that (1) some of
   the macros, in particular xPopTagged*, do not make the tag
   sanity checks that their non-x cousins do, and (2) some of
   the macros depend critically on the semantics of C comma
   expressions to work properly
*/
#define xPushPtr(ppp)           { xSp--; *xSp=(StgWord)(ppp); }
#define xPopPtr()               ((StgPtr)(*xSp++))

#define xPushCPtr(ppp)          { xSp--; *xSp=(StgWord)(ppp); }
#define xPopCPtr()              ((StgClosure*)(*xSp++))

#define xPushWord(ppp)          { xSp--; *xSp=(StgWord)(ppp); }
#define xPopWord()              ((StgWord)(*xSp++))

#define xStackPtr(nnn)          ((StgPtr)(*(xSp+(nnn))))
#define xStackWord(nnn)         ((StgWord)(*(xSp+(nnn))))
#define xSetStackWord(iii,www)  xSp[iii]=(StgWord)(www)

#define xPushTag(ttt)           { xSp--; *xSp=(StgWord)(ttt); }
#define xPopTag(ttt)            { StackTag t = (StackTag)(*xSp++); \
                                  ASSERT(t == ttt); }

#define xPushTaggedInt(xxx)     { xSp -= sizeofW(StgInt); \
                                  *xSp = (xxx); xPushTag(INT_TAG); }
#define xTaggedStackInt(iii)    ((StgInt)(*(xSp+1+(iii))))
#define xPopTaggedInt()         ((xSp++,xSp+=sizeofW(StgInt), \
                                 (StgInt)(*(xSp-sizeofW(StgInt)))))

#define xPushTaggedWord(xxx)    { xSp -= sizeofW(StgWord); \
                                  *xSp = (xxx); xPushTag(WORD_TAG); }
#define xTaggedStackWord(iii)   ((StgWord)(*(xSp+1+(iii))))
#define xPopTaggedWord()        ((xSp++,xSp+=sizeofW(StgWord), \
                                 (StgWord)(*(xSp-sizeofW(StgWord)))))

#define xPushTaggedAddr(xxx)    { xSp -= sizeofW(StgAddr); \
                                  *xSp = (StgWord)(xxx); xPushTag(ADDR_TAG); }
#define xTaggedStackAddr(iii)   ((StgAddr)(*(xSp+1+(iii))))
#define xPopTaggedAddr()        ((xSp++,xSp+=sizeofW(StgAddr), \
                                 (StgAddr)(*(xSp-sizeofW(StgAddr)))))

#define xPushTaggedChar(xxx)    { xSp -= sizeofW(StgChar); \
                                  *xSp = (StgWord)(xxx); xPushTag(CHAR_TAG); }
#define xTaggedStackChar(iii)   ((StgChar)(*(xSp+1+(iii))))
#define xPopTaggedChar()        ((xSp++,xSp+=sizeofW(StgChar), \
                                 (StgChar)(*(xSp-sizeofW(StgChar)))))

#define xPushTaggedFloat(xxx)   { xSp -= sizeofW(StgFloat); \
                                  ASSIGN_FLT(xSp,xxx); xPushTag(FLOAT_TAG); }
#define xTaggedStackFloat(iii)  PK_FLT(xSp+1+(iii))
#define xPopTaggedFloat()       ((xSp++,xSp+=sizeofW(StgFloat), \
                                 PK_FLT(xSp-sizeofW(StgFloat))))

#define xPushTaggedDouble(xxx)  { xSp -= sizeofW(StgDouble); \
                                  ASSIGN_DBL(xSp,xxx); xPushTag(DOUBLE_TAG); }
#define xTaggedStackDouble(iii) PK_DBL(xSp+1+(iii))
#define xPopTaggedDouble()      ((xSp++,xSp+=sizeofW(StgDouble), \
                                 PK_DBL(xSp-sizeofW(StgDouble))))


#define xPopUpdateFrame(ooo)                                      \
{                                                                 \
    /* NB: doesn't assume that Sp == Su */                        \
    IF_DEBUG(evaluator,                                           \
             fprintf(stderr,  "Updating ");                       \
             printPtr(stgCast(StgPtr,xSu->updatee));              \
             fprintf(stderr,  " with ");                          \
             printObj(ooo);                                       \
             fprintf(stderr,"xSp = %p\txSu = %p\n\n", xSp, xSu);  \
             );                                                   \
    UPD_IND(xSu->updatee,ooo);                                    \
    xSp = stgCast(StgStackPtr,xSu) + sizeofW(StgUpdateFrame);     \
    xSu = xSu->link;                                              \
}



/* Instruction stream macros */
#define BCO_INSTR_8  *bciPtr++
#define BCO_INSTR_16 ((bciPtr += 2,  (*(bciPtr-2) << 8) + *(bciPtr-1)))
#define PC (bciPtr - &(bcoInstr(bco,0)))


StgThreadReturnCode enter( StgClosure* obj0 )
431
{
432 433 434 435 436 437 438 439
   /* use of register here is primarily to make it clear to compilers
      that these entities are non-aliasable.
   */
    register StgPtr           xSp;    /* local state -- stack pointer */
    register StgUpdateFrame*  xSu;    /* local state -- frame pointer */
    register StgPtr           xSpLim; /* local state -- stack lim pointer */
    register StgClosure*      obj;    /* object currently under evaluation */
             char             eCount; /* enter counter, for context switching */
440

441
#ifdef DEBUG
442 443
    /* use the t values to check that Su/Sp/SpLim do not change unexpectedly */
    StgPtr tSp = Sp; StgUpdateFrame* tSu = Su; StgPtr tSpLim = SpLim;
444
#endif
445

446 447
    obj    = obj0;
    eCount = 0;
448

449 450 451 452 453
    /* Load the local state from global state, and Party On, Dudes! */
    /* From here onwards, we operate with the local state and 
       save/reload it as necessary.
    */
    LLL;
454

455
    enterLoop:
456

457
#ifdef DEBUG
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    assert(Sp == tSp);
    assert(Su == tSu);
    assert(SpLim == tSpLim);
    IF_DEBUG(evaluator,
             SSS;
             enterCountI++;
             ASSERT(xSpLim <= xSp && xSp <= stgCast(StgPtr,xSu));
             fprintf(stderr, 
             "\n---------------------------------------------------------------\n");
             fprintf(stderr,"(%d) Entering: ",enterCountI); printObj(obj);
             fprintf(stderr,"xSp = %p\txSu = %p\n", xSp, xSu);
             fprintf(stderr, "\n" );
             printStack(xSp,CurrentTSO->stack+CurrentTSO->stack_size,xSu);
             fprintf(stderr, "\n\n");
             LLL;
            );
#endif
475

476 477 478 479 480 481
    if (++eCount == 0) {
       if (context_switch) {
          xPushCPtr(obj); /* code to restart with */
          RETURN(ThreadYielding);
       }
    }
482

483 484 485
    switch ( get_itbl(obj)->type ) {
    case INVALID_OBJECT:
            barf("Invalid object %p",obj);
486

487
    case BCO: bco_entry:
488

489 490 491 492
            /* ---------------------------------------------------- */
            /* Start of the bytecode evaluator                      */
            /* ---------------------------------------------------- */
        {
493
#           if USE_GCC_LABELS
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
#           define Ins(x)          &&l##x
            static void *labs[] = { INSTRLIST };
#           undef Ins
#           define LoopTopLabel
#           define Case(x)         l##x
#           define Continue        goto *labs[BCO_INSTR_8]
#           define Dispatch        Continue;
#           define EndDispatch
#           else
#           define LoopTopLabel    insnloop:
#           define Case(x)         case x
#           define Continue        goto insnloop
#           define Dispatch        switch (BCO_INSTR_8) {
#           define EndDispatch     }
#           endif

            register StgWord8* bciPtr; /* instruction pointer */
            register StgBCO*   bco = (StgBCO*)obj;
            StgWord wantToGC;

            /* Don't need to SSS ... LLL around doYouWantToGC */
            wantToGC = doYouWantToGC();
            if (wantToGC) {
                xPushCPtr((StgClosure*)bco); /* code to restart with */
                RETURN(HeapOverflow);
            }
520

521 522 523 524 525 526 527 528 529 530 531 532 533 534
#           if CRUDE_PROFILING
            cp_enter ( bco );
#           endif


            bciPtr = &(bcoInstr(bco,0));

            LoopTopLabel

            ASSERT(PC < bco->n_instrs);
            IF_DEBUG(evaluator,
            fprintf(stderr,"Sp = %p\tSu = %p\tpc = %d\t", xSp, xSu, PC);
                    SSS;
                    disInstr(bco,PC);
535 536 537 538 539
                    { int i;
                    fprintf(stderr,"\n");
                      for (i = 8; i >= 0; i--) 
                         fprintf(stderr, "%d  %p\n", i, (StgPtr)(*(Sp+i)));
                      }
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 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 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
                    fprintf(stderr,"\n");
                    LLL;
                   );

#           if CRUDE_PROFILING
            SSS; cp_bill_insns(1); LLL;
#           endif

            Dispatch

            Case(i_INTERNAL_ERROR):
                    barf("INTERNAL_ERROR at %p:%d",bco,PC-1);
            Case(i_PANIC):
                    barf("PANIC at %p:%d",bco,PC-1);
            Case(i_STK_CHECK):
                {
                    int n = BCO_INSTR_8;
                    if (xSp - n < xSpLim) {
                        xPushCPtr((StgClosure*)bco); /* code to restart with */
                        RETURN(StackOverflow);
                    }
                    Continue;
                }
            Case(i_ARG_CHECK):
                {
                    nat n = BCO_INSTR_8;
                    if ((StgPtr*)(xSp + n) > (StgPtr*)xSu) {
                        StgWord words = (P_)xSu - xSp;
                         
                        /* first build a PAP */
                        ASSERT((P_)xSu >= xSp);  /* was (words >= 0) but that's always true */
                        if (words == 0) { /* optimisation */
                            /* Skip building the PAP and update with an indirection. */
                        } else { 
                            /* Build the PAP. */
                            /* In the evaluator, we avoid the need to do 
                             * a heap check here by including the size of
                             * the PAP in the heap check we performed
                             * when we entered the BCO.
        	             */
                             StgInt  i;
                             StgPAP* pap;
                             SSS; pap = (StgPAP*)grabHpNonUpd(PAP_sizeW(words)); LLL;
                             SET_HDR(pap,&PAP_info,CC_pap);
                             pap->n_args = words;
                             pap->fun = obj;
                             for (i = 0; i < (I_)words; ++i) {
                                 payloadWord(pap,i) = xSp[i];
                             }
                             xSp += words;
                             obj = stgCast(StgClosure*,pap);
                        }
        
                        /* now deal with "update frame" */
                        /* as an optimisation, we process all on top of stack */
                        /* instead of just the top one */
                        ASSERT(xSp==(P_)xSu);
                        do {
                            switch (get_itbl(xSu)->type) {
                                case CATCH_FRAME:
                                    /* Hit a catch frame during an arg satisfaction check,
                                     * so the thing returning (1) has not thrown an
                                     * exception, and (2) is of functional type.  Just
                                     * zap the catch frame and carry on down the stack
                                     * (looking for more arguments, basically).
                                     */
                                     SSS; PopCatchFrame(); LLL;
                                     break;
                                case UPDATE_FRAME:
                                     xPopUpdateFrame(obj);
                                     break;
                                case STOP_FRAME:
                                     SSS; PopStopFrame(obj); LLL;
                                     RETURN(ThreadFinished);
                                case SEQ_FRAME:
                                     SSS; PopSeqFrame(); LLL;
                                     ASSERT(xSp != (P_)xSu);
                                     /* Hit a SEQ frame during an arg satisfaction check.
                                      * So now return to bco_info which is under the 
                                      * SEQ frame.  The following code is copied from a 
                                      * case RET_BCO further down.  (The reason why we're
                                      * here is that something of functional type has 
                                      * been seq-d on, and we're now returning to the
                                      * algebraic-case-continuation which forced the
                                      * evaluation in the first place.)
                                      */
                                      {
                                          StgClosure* ret;
                                          (void)xPopPtr();
                                          ret = xPopCPtr();
                                          xPushPtr((P_)obj);
                                          obj = ret;
                                          goto enterLoop;
                                      }
                                      break;
                                default:        
                                      barf("Invalid update frame during argcheck");
                            }
                        } while (xSp==(P_)xSu);
                        goto enterLoop;
                    }
                    Continue;
                }
            Case(i_ALLOC_AP):
                {
                    StgPtr p;
                    int words = BCO_INSTR_8;
                    SSS; p = grabHpUpd(AP_sizeW(words)); LLL;
                    xPushPtr(p);
                    Continue;
                }
            Case(i_ALLOC_CONSTR):
                {
                    StgPtr p;
                    StgInfoTable* info = bcoConstAddr(bco,BCO_INSTR_8);
                    SSS; p = grabHpNonUpd(sizeW_fromITBL(info)); LLL;
                    SET_HDR((StgClosure*)p,info,??);
                    xPushPtr(p);
                    Continue;
                }
            Case(i_MKAP):
                {
                    int x = BCO_INSTR_8;  /* ToDo: Word not Int! */
                    int y = BCO_INSTR_8;
                    StgAP_UPD* o = stgCast(StgAP_UPD*,xStackPtr(x));
                    SET_HDR(o,&AP_UPD_info,??);
                    o->n_args = y;
                    o->fun    = stgCast(StgClosure*,xPopPtr());
                    for(x=0; x < y; ++x) {
                        payloadWord(o,x) = xPopWord();
                    }
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             SSS; 
                             printObj(stgCast(StgClosure*,o)); 
                             LLL;
                    );
                    Continue;
                }
            Case(i_MKAP_big):
                {
                    int x, y;
                    StgAP_UPD* o;
                    x = BCO_INSTR_16;
                    y = BCO_INSTR_16;
                    o = stgCast(StgAP_UPD*,xStackPtr(x));
                    SET_HDR(o,&AP_UPD_info,??);
                    o->n_args = y;
                    o->fun    = stgCast(StgClosure*,xPopPtr());
                    for(x=0; x < y; ++x) {
                        payloadWord(o,x) = xPopWord();
                    }
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             SSS;
                             printObj(stgCast(StgClosure*,o));
                             LLL;
                    );
                    Continue;
                }
            Case(i_MKPAP):
                {
                    int x = BCO_INSTR_8;
                    int y = BCO_INSTR_8;
                    StgPAP* o = stgCast(StgPAP*,xStackPtr(x));
                    SET_HDR(o,&PAP_info,??);
                    o->n_args = y;
                    o->fun    = stgCast(StgClosure*,xPopPtr());
                    for(x=0; x < y; ++x) {
                        payloadWord(o,x) = xPopWord();
                    }
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             SSS;
                             printObj(stgCast(StgClosure*,o));
                             LLL;
                            );
                    Continue;
                }
            Case(i_PACK):
                {
                    int offset = BCO_INSTR_8;
                    StgClosure* o = stgCast(StgClosure*,xStackPtr(offset));
                    const StgInfoTable* info = get_itbl(o);
                    nat p  = info->layout.payload.ptrs; 
                    nat np = info->layout.payload.nptrs; 
                    nat i;
                    for(i=0; i < p; ++i) {
                        payloadCPtr(o,i) = xPopCPtr();
                    }
                    for(i=0; i < np; ++i) {
                        payloadWord(o,p+i) = 0xdeadbeef;
                    }
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             SSS;
                             printObj(stgCast(StgClosure*,o));
                             LLL;
                             );
                    Continue;
                }
            Case(i_PACK_big):
                {
                    int offset = BCO_INSTR_16;
                    StgClosure* o = stgCast(StgClosure*,xStackPtr(offset));
                    const StgInfoTable* info = get_itbl(o);
                    nat p  = info->layout.payload.ptrs; 
                    nat np = info->layout.payload.nptrs; 
                    nat i;
                    for(i=0; i < p; ++i) {
                        payloadCPtr(o,i) = xPopCPtr();
                    }
                    for(i=0; i < np; ++i) {
                        payloadWord(o,p+i) = 0xdeadbeef;
                    }
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             SSS;
                             printObj(stgCast(StgClosure*,o));
                             LLL;
                             );
                    Continue;
                }
            Case(i_SLIDE):
                {
                    int x = BCO_INSTR_8;
                    int y = BCO_INSTR_8;
                    ASSERT(xSp+x+y <= stgCast(StgPtr,xSu));
                    /* a_1, .. a_x, b_1, .. b_y, s => a_1, .. a_x, s */
                    while(--x >= 0) {
                        xSetStackWord(x+y,xStackWord(x));
                    }
                    xSp += y;
                    Continue;
                }
            Case(i_SLIDE_big):
                {
                    int x, y;
                    x = BCO_INSTR_16;
                    y = BCO_INSTR_16;
                    ASSERT(xSp+x+y <= stgCast(StgPtr,xSu));
                    /* a_1, .. a_x, b_1, .. b_y, s => a_1, .. a_x, s */
                    while(--x >= 0) {
                        xSetStackWord(x+y,xStackWord(x));
                    }
                    xSp += y;
                    Continue;
                }
            Case(i_ENTER):
                {
                    obj = xPopCPtr();
                    goto enterLoop;
                }
            Case(i_RETADDR):
                {
                    xPushPtr(bcoConstPtr(bco,BCO_INSTR_8));
                    xPushPtr(stgCast(StgPtr,&ret_bco_info));
                    Continue;
                }
            Case(i_TEST):
                {
                    int  tag       = BCO_INSTR_8;
                    StgWord offset = BCO_INSTR_16;
                    if (constrTag(stgCast(StgClosure*,xStackPtr(0))) != tag) {
                        bciPtr += offset;
                    }
                    Continue;
                }
            Case(i_UNPACK):
                {
                    StgClosure* o = stgCast(StgClosure*,xStackPtr(0));
                    const StgInfoTable* itbl = get_itbl(o);
                    int i = itbl->layout.payload.ptrs;
                    ASSERT(  itbl->type == CONSTR
                          || itbl->type == CONSTR_STATIC
                          || itbl->type == CONSTR_NOCAF_STATIC
                          );
                    while (--i>=0) {
                        xPushCPtr(payloadCPtr(o,i));
                    }
                    Continue;
                }
            Case(i_VAR_big):
                {
                    int n = BCO_INSTR_16;
                    StgPtr p = xStackPtr(n);
                    xPushPtr(p);
                    Continue;
                }
            Case(i_VAR):
                {
                    StgPtr p = xStackPtr(BCO_INSTR_8);
                    xPushPtr(p);
                    Continue;
                }
            Case(i_CONST):
                {
                    xPushPtr(stgCast(StgPtr,bcoConstPtr(bco,BCO_INSTR_8)));
                    Continue;
                }
            Case(i_CONST_big):
                {
                    int n = BCO_INSTR_16;
                    xPushPtr(stgCast(StgPtr,bcoConstPtr(bco,n)));
                    Continue;
                }
            Case(i_VOID):
                {
                    SSS; PushTaggedRealWorld(); LLL;
                    Continue;
                }
            Case(i_VAR_INT):
                {
                    StgInt i = xTaggedStackInt(BCO_INSTR_8);
                    xPushTaggedInt(i);
                    Continue;
                }
            Case(i_CONST_INT):
                {
                    xPushTaggedInt(bcoConstInt(bco,BCO_INSTR_8));
                    Continue;
                }
            Case(i_PACK_INT):
                {
                    StgClosure* o;
                    SSS; o = (StgClosure*)grabHpNonUpd(Izh_sizeW); LLL;
                    SET_HDR(o,&Izh_con_info,??);
                    payloadWord(o,0) = xPopTaggedInt();
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             SSS;
                             printObj(stgCast(StgClosure*,o));
                             LLL;
                             );
                    xPushPtr(stgCast(StgPtr,o));
                    Continue;
                }
            Case(i_UNPACK_INT):
                {
                    StgClosure* con = stgCast(StgClosure*,xStackPtr(0));
                    /* ASSERT(isIntLike(con)); */
                    xPushTaggedInt(payloadWord(con,0));
                    Continue;
                }
            Case(i_TEST_INT):
                {
                    StgWord offset = BCO_INSTR_16;
                    StgInt  x      = xPopTaggedInt();
                    StgInt  y      = xPopTaggedInt();
                    if (x != y) {
                        bciPtr += offset;
                    }
                    Continue;
                }
            Case(i_CONST_INTEGER):
                {
                    StgPtr p;
                    int n;
                    char* s = bcoConstAddr(bco,BCO_INSTR_8);
                    SSS;
                    n = size_fromStr(s);
                    p = CreateByteArrayToHoldInteger(n);
                    do_fromStr ( s, n, IntegerInsideByteArray(p));
                    SloppifyIntegerEnd(p);
		    LLL;
                    xPushPtr(p);
                    Continue;
                }
            Case(i_VAR_WORD):
                {
        	    StgWord w = xTaggedStackWord(BCO_INSTR_8);
                    xPushTaggedWord(w);
                    Continue;
                }
            Case(i_CONST_WORD):
                {
                    xPushTaggedWord(bcoConstWord(bco,BCO_INSTR_8));
                    Continue;
                }
            Case(i_PACK_WORD):
                {
                    StgClosure* o;
                    SSS; o = (StgClosure*)grabHpNonUpd(Wzh_sizeW); LLL;
                    SET_HDR(o,&Wzh_con_info,??);
                    payloadWord(o,0) = xPopTaggedWord();
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             SSS;
                             printObj(stgCast(StgClosure*,o)); 
                             LLL;
                            );
                    xPushPtr(stgCast(StgPtr,o));
                    Continue;
                }
            Case(i_UNPACK_WORD):
                {
                    StgClosure* con = stgCast(StgClosure*,xStackPtr(0));
                    /* ASSERT(isWordLike(con)); */
                    xPushTaggedWord(payloadWord(con,0));
                    Continue;
                }
            Case(i_VAR_ADDR):
                {
                    StgAddr a = xTaggedStackAddr(BCO_INSTR_8);
                    xPushTaggedAddr(a);
                    Continue;
                }
            Case(i_CONST_ADDR):
                {
                    xPushTaggedAddr(bcoConstAddr(bco,BCO_INSTR_8));
                    Continue;
                }
            Case(i_PACK_ADDR):
                {
                    StgClosure* o;
                    SSS; o = (StgClosure*)grabHpNonUpd(Azh_sizeW); LLL;
                    SET_HDR(o,&Azh_con_info,??);
                    payloadPtr(o,0) = xPopTaggedAddr();
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             SSS;
                             printObj(stgCast(StgClosure*,o));
                             LLL;
                             );
                    xPushPtr(stgCast(StgPtr,o));
                    Continue;
                }
            Case(i_UNPACK_ADDR):
                {
                    StgClosure* con = stgCast(StgClosure*,xStackPtr(0));
                    /* ASSERT(isAddrLike(con)); */
                    xPushTaggedAddr(payloadPtr(con,0));
                    Continue;
                }
            Case(i_VAR_CHAR):
                {
                    StgChar c = xTaggedStackChar(BCO_INSTR_8);
                    xPushTaggedChar(c);
                    Continue;
                }
            Case(i_CONST_CHAR):
                {
                    xPushTaggedChar(bcoConstChar(bco,BCO_INSTR_8));
                    Continue;
                }
            Case(i_PACK_CHAR):
                {
                    StgClosure* o;
                    SSS; o = (StgClosure*)grabHpNonUpd(Czh_sizeW); LLL;
                    SET_HDR(o,&Czh_con_info,??);
                    payloadWord(o,0) = xPopTaggedChar();
                    xPushPtr(stgCast(StgPtr,o));
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             SSS;
                             printObj(stgCast(StgClosure*,o));
                             LLL;
                             );
                    Continue;
                }
            Case(i_UNPACK_CHAR):
                {
                    StgClosure* con = stgCast(StgClosure*,xStackPtr(0));
                    /* ASSERT(isCharLike(con)); */
                    xPushTaggedChar(payloadWord(con,0));
                    Continue;
                }
            Case(i_VAR_FLOAT):
                {
                    StgFloat f = xTaggedStackFloat(BCO_INSTR_8);
                    xPushTaggedFloat(f);
                    Continue;
                }
            Case(i_CONST_FLOAT):
                {
                    xPushTaggedFloat(bcoConstFloat(bco,BCO_INSTR_8));
                    Continue;
                }
            Case(i_PACK_FLOAT):
                {
                    StgClosure* o;
                    SSS; o = (StgClosure*)grabHpNonUpd(Fzh_sizeW); LLL;
                    SET_HDR(o,&Fzh_con_info,??);
                    ASSIGN_FLT(&payloadWord(o,0),xPopTaggedFloat());
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             SSS;
                             printObj(stgCast(StgClosure*,o));
                             LLL;
                             );
                    xPushPtr(stgCast(StgPtr,o));
                    Continue;
                }
            Case(i_UNPACK_FLOAT):
                {
                    StgClosure* con = stgCast(StgClosure*,xStackPtr(0));
                    /* ASSERT(isFloatLike(con)); */
                    xPushTaggedFloat(PK_FLT(&payloadWord(con,0)));
                    Continue;
                }
            Case(i_VAR_DOUBLE):
                {
                    StgDouble d = xTaggedStackDouble(BCO_INSTR_8);
                    xPushTaggedDouble(d);
                    Continue;
                }
            Case(i_CONST_DOUBLE):
                {
                    xPushTaggedDouble(bcoConstDouble(bco,BCO_INSTR_8));
                    Continue;
                }
            Case(i_CONST_DOUBLE_big):
                {
                    int n = BCO_INSTR_16;
                    xPushTaggedDouble(bcoConstDouble(bco,n));
                    Continue;
                }
            Case(i_PACK_DOUBLE):
                {
                    StgClosure* o;
                    SSS; o = (StgClosure*)grabHpNonUpd(Dzh_sizeW); LLL;
                    SET_HDR(o,&Dzh_con_info,??);
                    ASSIGN_DBL(&payloadWord(o,0),xPopTaggedDouble());
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             printObj(stgCast(StgClosure*,o));
                             );
                    xPushPtr(stgCast(StgPtr,o));
                    Continue;
                }
            Case(i_UNPACK_DOUBLE):
                {
                    StgClosure* con = stgCast(StgClosure*,xStackPtr(0));
                    /* ASSERT(isDoubleLike(con)); */
                    xPushTaggedDouble(PK_DBL(&payloadWord(con,0)));
                    Continue;
                }
            Case(i_VAR_STABLE):
                {   
                    fprintf(stderr, "unimp: i_VAR_STABLE\n" ); exit(0);
                    /*fix side effects here ...*/
                    /*
                    xPushTaggedStablePtr(xTaggedStackStable(BCO_INSTR_8));
                    */
                    Continue;
                }
            Case(i_PACK_STABLE):
                {
        	    //StgClosure* o;
                    fprintf(stderr, "unimp: i_PACK_STABLE\n" ); exit(0);
                    /*
                    SSS; o = (StgClosure*)grabHpNonUpd(Stablezh_sizeW); LLL;
                    SET_HDR(o,&StablePtr_con_info,??);
                    payloadWord(o,0) = xPopTaggedStablePtr();
                    IF_DEBUG(evaluator,
                             fprintf(stderr,"\tBuilt "); 
                             printObj(stgCast(StgClosure*,o));
                             );
                    xPushPtr(stgCast(StgPtr,o));
                    */
                    Continue;
                }
            Case(i_UNPACK_STABLE):
                {
        	    //StgClosure* con;
                    fprintf(stderr, "unimp: i_UNPACK_STABLE\n" ); exit(0);
                    /*
                    con = stgCast(StgClosure*,xStackPtr(0));
                    ASSERT(isStableLike(con));
                    xPushTaggedStablePtr(payloadWord(con,0));
                    */
                    Continue;
                }
            Case(i_PRIMOP1):
                {
                    int   i;
                    void* p;
                    i = BCO_INSTR_8;
                    SSS; p = enterBCO_primop1 ( i ); LLL;
                    if (p) { obj = p; goto enterLoop; };
                    Continue;
                }
            Case(i_PRIMOP2):
                {
                    int   i, trc;
                    void* p;
                    trc = 12345678;  /* Hope that no StgThreadReturnCode has this value */
                    i   = BCO_INSTR_8;
                    SSS; p = enterBCO_primop2 ( i, &trc ); LLL;
                    if (p) {
                       if (trc == 12345678) {
                          /* we want to enter p */
                          obj = p; goto enterLoop;
                       } else {
                          /* p is the the StgThreadReturnCode for this thread */
                          RETURN((StgThreadReturnCode)p);
                       };
                    }
                    Continue;
                }
        
            /* combined insns, created by peephole opt */
            Case(i_SE):
                {
                    int x = BCO_INSTR_8;
                    int y = BCO_INSTR_8;
                    ASSERT(xSp+x+y <= stgCast(StgPtr,xSu));
                    /* a_1, .. a_x, b_1, .. b_y, s => a_1, .. a_x, s */
                    if (x == 1) {
                       obj = xPopCPtr();
                       xSp += y;
                       goto enterLoop;
                    } else {
                       while(--x >= 0) {
                           xSetStackWord(x+y,xStackWord(x));
                       }
                       xSp += y;
                       obj = xPopCPtr();
                    }
                    goto enterLoop;
                }
            Case(i_VV):
                {
                    StgPtr p;
                    p = xStackPtr(BCO_INSTR_8);
                    xPushPtr(p);
                    p = xStackPtr(BCO_INSTR_8);
                    xPushPtr(p);
                    Continue;
                }
            Case(i_RV):
                {
                    StgPtr p;
                    xPushPtr(bcoConstPtr(bco,BCO_INSTR_8));
                    xPushPtr(stgCast(StgPtr,&ret_bco_info));
                    p = xStackPtr(BCO_INSTR_8);
                    xPushPtr(p);
                    Continue;
                }
            Case(i_RVE):
                {
                    StgPtr retaddr = bcoConstPtr(bco,BCO_INSTR_8);
                    StgPtr ptr = xStackPtr(BCO_INSTR_8);

                    /* A shortcut.  We're going to push the address of a
                       return continuation, and then enter a variable, so
                       that when the var is evaluated, we return to the
                       continuation.  The shortcut is: if the var is a 
                       constructor, don't bother to enter it.  Instead,
                       push the variable on the stack (since this is what
                       the continuation expects) and jump directly to the
                       continuation.
                     */
                    if (get_itbl((StgClosure*)ptr)->type == CONSTR) {
                       xPushPtr(ptr);
                       obj = (StgClosure*)retaddr;
                       IF_DEBUG(evaluator,
                                fprintf(stderr, "object to enter is a constructor -- "
                                        "jumping directly to return continuation\n" );
1199
                               );
1200 1201 1202 1203 1204 1205 1206 1207 1208
                       goto bco_entry;
                    }

                    /* This is the normal, non-short-cut route */
                    xPushPtr(retaddr);
                    xPushPtr(stgCast(StgPtr,&ret_bco_info));
                    obj = (StgClosure*)ptr;
                    goto enterLoop;
                }
1209 1210


1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
            Case(i_VAR_DOUBLE_big):
            Case(i_CONST_FLOAT_big):
            Case(i_VAR_FLOAT_big):
            Case(i_CONST_CHAR_big):
            Case(i_VAR_CHAR_big):
            Case(i_CONST_ADDR_big):
            Case(i_VAR_ADDR_big):
            Case(i_CONST_INTEGER_big):
            Case(i_CONST_INT_big):
            Case(i_VAR_INT_big):
            Case(i_VAR_WORD_big):
            Case(i_RETADDR_big):
            Case(i_ALLOC_PAP):
                    bciPtr--;
                    printf ( "\n\n" );
                    disInstr ( bco, PC );
                    barf("\nUnrecognised instruction");
        
            EndDispatch
        
            barf("enterBCO: ran off end of loop");
            break;
        }
1234

1235 1236 1237 1238 1239
#           undef LoopTopLabel
#           undef Case
#           undef Continue
#           undef Dispatch
#           undef EndDispatch
1240

1241 1242 1243
            /* ---------------------------------------------------- */
            /* End of the bytecode evaluator                        */
            /* ---------------------------------------------------- */
1244

1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
    case CAF_UNENTERED:
        {
            StgBlockingQueue* bh;
            StgCAF* caf = (StgCAF*)obj;
            if (xSp - sizeofW(StgUpdateFrame) < xSpLim) {
                xPushCPtr(obj); /* code to restart with */
                RETURN(StackOverflow);
            }
            /* ToDo: look for xSp==xSu && stackInt(0) == UPD_FRAME 
               and insert an indirection immediately */
            SSS; bh = (StgBlockingQueue*)grabHpUpd(BLACKHOLE_sizeW()); LLL;
            SET_INFO(bh,&CAF_BLACKHOLE_info);
            bh->blocking_queue = EndTSOQueue;
            IF_DEBUG(gccafs,
                     fprintf(stderr,"Created CAF_BLACKHOLE %p for CAF %p in evaluator\n",bh,caf));
            SET_INFO(caf,&CAF_ENTERED_info);
            caf->value = (StgClosure*)bh;
            if (caf->mut_link == NULL) { 
               SSS; recordOldToNewPtrs((StgMutClosure*)caf); LLL; 
            }
            SSS; PUSH_UPD_FRAME(bh,0); LLL;
            xSp -= sizeofW(StgUpdateFrame);
            caf->link = enteredCAFs;
            enteredCAFs = caf;
            obj = caf->body;
            goto enterLoop;
        }
    case CAF_ENTERED:
        {
            StgCAF* caf = (StgCAF*)obj;
            obj = caf->value; /* it's just a fancy indirection */
            goto enterLoop;
        }
    case BLACKHOLE:
1279
    case SE_BLACKHOLE:
1280
    case CAF_BLACKHOLE:
1281
    case SE_CAF_BLACKHOLE:
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
        {
	    /*was StgBlackHole* */
            StgBlockingQueue* bh = (StgBlockingQueue*)obj;
            /* Put ourselves on the blocking queue for this black hole and block */
            CurrentTSO->link = bh->blocking_queue;
            bh->blocking_queue = CurrentTSO;
            xPushCPtr(obj); /* code to restart with */
            barf("enter: CAF_BLACKHOLE unexpected!");
            RETURN(ThreadBlocked);
        }
    case AP_UPD:
        {
            StgAP_UPD* ap = stgCast(StgAP_UPD*,obj);
            int i = ap->n_args;
            if (xSp - (i + sizeofW(StgUpdateFrame)) < xSpLim) {
                xPushCPtr(obj); /* code to restart with */
                RETURN(StackOverflow);
            }
            /* ToDo: look for xSp==xSu && stackInt(0) == UPD_FRAME 
               and insert an indirection immediately  */
            SSS; PUSH_UPD_FRAME(ap,0); LLL;
            xSp -= sizeofW(StgUpdateFrame);
            while (--i >= 0) {
                xPushWord(payloadWord(ap,i));
            }
            obj = ap->fun;
1308
#ifdef EAGER_BLACKHOLING
1309 1310 1311 1312 1313 1314 1315 1316
            {
                /* superfluous - but makes debugging easier */
                StgBlackHole* bh = stgCast(StgBlackHole*,ap);
                SET_INFO(bh,&BLACKHOLE_info);
                bh->blocking_queue = EndTSOQueue;
                IF_DEBUG(gccafs,fprintf(stderr,"Eagerly blackholed AP_UPD %p in evaluator\n",bh));
                /*printObj(bh); */
            }
1317
#endif /* EAGER_BLACKHOLING */
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
            goto enterLoop;
        }
    case PAP:
        {
            StgPAP* pap = stgCast(StgPAP*,obj);
            int i = pap->n_args;  /* ToDo: stack check */
            /* ToDo: if PAP is in whnf, we can update any update frames
             * on top of stack.
	     */
            while (--i >= 0) {
                xPushWord(payloadWord(pap,i));
            }
            obj = pap->fun;
            goto enterLoop;
        }
    case IND:
        {
            obj = stgCast(StgInd*,obj)->indirectee;
            goto enterLoop;
        }
    case IND_OLDGEN:
        {
            obj = stgCast(StgIndOldGen*,obj)->indirectee;
            goto enterLoop;
        }
    case CONSTR:
    case CONSTR_INTLIKE:
    case CONSTR_CHARLIKE:
    case CONSTR_STATIC:
    case CONSTR_NOCAF_STATIC:
        {
            while (1) {
                switch (get_itbl(stgCast(StgClosure*,xSp))->type) {
                case CATCH_FRAME:
                        SSS; PopCatchFrame(); LLL;
                        break;
                case UPDATE_FRAME:
                        xPopUpdateFrame(obj);
                        break;
                case SEQ_FRAME:
                        SSS; PopSeqFrame(); LLL;
                        break;
                case STOP_FRAME:
                    {
                        ASSERT(xSp==(P_)xSu);
                        IF_DEBUG(evaluator,
                                 SSS;
                                 printObj(obj);
                                 /*fprintf(stderr,"xSp = %p\txSu = %p\n", xSp, xSu);*/
                                 /*printStack(xSp,CurrentTSO->stack+CurrentTSO->stack_size,xSu);*/
                                 LLL;
                                 );
                        SSS; PopStopFrame(obj); LLL;
                        RETURN(ThreadFinished);
                    }
                case RET_BCO:
                    {
                        StgClosure* ret;
                        (void)xPopPtr();
                        ret = xPopCPtr();
                        xPushPtr((P_)obj);
                        obj = ret;
                        goto bco_entry;
                        /* was: goto enterLoop;
                           But we know that obj must be a bco now, so jump directly.
                        */
                    }
                case RET_SMALL:  /* return to GHC */
                case RET_VEC_SMALL:
                case RET_BIG:
                case RET_VEC_BIG:
                        barf("todo: RET_[VEC_]{BIG,SMALL}");
                default:
                        belch("entered CONSTR with invalid continuation on stack");
                        IF_DEBUG(evaluator,
                                 SSS;
                                 printObj(stgCast(StgClosure*,xSp));
                                 LLL;
                                 );
                        barf("bailing out");
                }
            }
        }
    default:
        {
            SSS;
            fprintf(stderr, "enterCountI = %d\n", enterCountI);
            fprintf(stderr, "panic: enter: entered unknown closure\n"); 
            printObj(obj);
            fprintf(stderr, "what it points at is\n");
            printObj( ((StgEvacuated*)obj) ->evacuee);
            LLL;
            exit(1);
            /* formerly ... */
            CurrentTSO->whatNext = ThreadEnterGHC;
            xPushCPtr(obj); /* code to restart with */
            RETURN(ThreadYielding);
        }
    }
    barf("Ran off the end of enter - yoiks");
    assert(0);
}

#undef RETURN
#undef BCO_INSTR_8
#undef BCO_INSTR_16
#undef SSS
#undef LLL
#undef PC
#undef xPushPtr
#undef xPopPtr
#undef xPushCPtr
#undef xPopCPtr
#undef xPopWord
#undef xStackPtr
#undef xStackWord
#undef xSetStackWord
#undef xPushTag
#undef xPopTag
#undef xPushTaggedInt
#undef xPopTaggedInt
#undef xTaggedStackInt
#undef xPushTaggedWord
#undef xPopTaggedWord
#undef xTaggedStackWord
#undef xPushTaggedAddr
#undef xTaggedStackAddr
#undef xPopTaggedAddr
#undef xPushTaggedChar
#undef xTaggedStackChar
#undef xPopTaggedChar
#undef xPushTaggedFloat
#undef xTaggedStackFloat
#undef xPopTaggedFloat
#undef xPushTaggedDouble
#undef xTaggedStackDouble
#undef xPopTaggedDouble



/* --------------------------------------------------------------------------
 * Supporting routines for primops
 * ------------------------------------------------------------------------*/

static inline void            PushTag            ( StackTag    t ) 
   { *(--Sp) = t; }
static inline void            PushPtr            ( StgPtr      x ) 
   { *(--stgCast(StgPtr*,Sp))  = x; }
static inline void            PushCPtr           ( StgClosure* x ) 
   { *(--stgCast(StgClosure**,Sp)) = x; }
static inline void            PushInt            ( StgInt      x ) 
   { *(--stgCast(StgInt*,Sp))  = x; }
static inline void            PushWord           ( StgWord     x ) 
   { *(--stgCast(StgWord*,Sp)) = x; }
                                                     
                                                 
static inline void            checkTag           ( StackTag t1, StackTag t2 ) 
   { ASSERT(t1 == t2);}
static inline void            PopTag             ( StackTag t ) 
   { checkTag(t,*(Sp++));    }
static inline StgPtr          PopPtr             ( void )       
   { return *stgCast(StgPtr*,Sp)++; }
static inline StgClosure*     PopCPtr            ( void )       
   { return *stgCast(StgClosure**,Sp)++; }
static inline StgInt          PopInt             ( void )       
   { return *stgCast(StgInt*,Sp)++;  }
static inline StgWord         PopWord            ( void )       
   { return *stgCast(StgWord*,Sp)++; }

static inline StgPtr          stackPtr           ( StgStackOffset i ) 
   { return *stgCast(StgPtr*, Sp+i); }
static inline StgInt          stackInt           ( StgStackOffset i ) 
   { return *stgCast(StgInt*, Sp+i); }
static inline StgWord         stackWord          ( StgStackOffset i ) 
   { return *stgCast(StgWord*,Sp+i); }
                              
static inline void            setStackWord       ( StgStackOffset i, StgWord w ) 
   { Sp[i] = w; }

static inline void            PushTaggedRealWorld( void            ) 
   { PushTag(REALWORLD_TAG);  }
       inline void            PushTaggedInt      ( StgInt        x ) 
   { Sp -= sizeofW(StgInt);        *Sp = x;          PushTag(INT_TAG);    }
static inline void            PushTaggedWord     ( StgWord       x ) 
   { Sp -= sizeofW(StgWord);       *Sp = x;          PushTag(WORD_TAG);   }
static inline void            PushTaggedAddr     ( StgAddr       x ) 
   { Sp -= sizeofW(StgAddr);       *Sp = (W_)x;      PushTag(ADDR_TAG);   }
static inline void            PushTaggedChar     ( StgChar       x ) 
   { Sp -= sizeofW(StgChar);         *Sp = stgCast(StgWord,x); PushTag(CHAR_TAG); }
static inline void            PushTaggedFloat    ( StgFloat      x ) 
   { Sp -= sizeofW(StgFloat);      ASSIGN_FLT(Sp,x); PushTag(FLOAT_TAG);  }
static inline void            PushTaggedDouble   ( StgDouble     x ) 
   { Sp -= sizeofW(StgDouble);     ASSIGN_DBL(Sp,x); PushTag(DOUBLE_TAG); }
static inline void            PushTaggedStablePtr   ( StgStablePtr  x ) 
   { Sp -= sizeofW(StgStablePtr);  *Sp = x;          PushTag(STABLE_TAG); }
static inline void            PushTaggedBool     ( int           x ) 
   { PushTaggedInt(x); }



static inline void            PopTaggedRealWorld ( void ) 
   { PopTag(REALWORLD_TAG); }
       inline StgInt          PopTaggedInt       ( void ) 
   { StgInt    r; PopTag(INT_TAG);     r = *stgCast(StgInt*,  Sp);      
     Sp += sizeofW(StgInt);        return r;}
static inline StgWord         PopTaggedWord      ( void ) 
   { StgWord   r; PopTag(WORD_TAG);    r = *stgCast(StgWord*, Sp);      
     Sp += sizeofW(StgWord);       return r;}
static inline StgAddr         PopTaggedAddr      ( void ) 
   { StgAddr   r; PopTag(ADDR_TAG);    r = *stgCast(StgAddr*, Sp);      
     Sp += sizeofW(StgAddr);       return r;}
static inline StgChar         PopTaggedChar      ( void ) 
   { StgChar   r; PopTag(CHAR_TAG);    r = stgCast(StgChar, *Sp);       
     Sp += sizeofW(StgChar);       return r;}
static inline StgFloat        PopTaggedFloat     ( void ) 
   { StgFloat  r; PopTag(FLOAT_TAG);   r = PK_FLT(Sp);                  
     Sp += sizeofW(StgFloat);      return r;}
static inline StgDouble       PopTaggedDouble    ( void ) 
   { StgDouble r; PopTag(DOUBLE_TAG);  r = PK_DBL(Sp);                  
     Sp += sizeofW(StgDouble);     return r;}
static inline StgStablePtr    PopTaggedStablePtr    ( void ) 
   { StgInt    r; PopTag(STABLE_TAG);  r = *stgCast(StgStablePtr*, Sp); 
     Sp += sizeofW(StgStablePtr);  return r;}



static inline StgInt          taggedStackInt     ( StgStackOffset i ) 
   { checkTag(INT_TAG,Sp[i]);     return *stgCast(StgInt*,         Sp+1+i); }
static inline StgWord         taggedStackWord    ( StgStackOffset i ) 
   { checkTag(WORD_TAG,Sp[i]);    return *stgCast(StgWord*,        Sp+1+i); }
static inline StgAddr         taggedStackAddr    ( StgStackOffset i ) 
   { checkTag(ADDR_TAG,Sp[i]);    return *stgCast(StgAddr*,        Sp+1+i); }
static inline StgChar         taggedStackChar    ( StgStackOffset i ) 
   { checkTag(CHAR_TAG,Sp[i]);    return stgCast(StgChar, *(Sp+1+i))   ; }
static inline StgFloat        taggedStackFloat   ( StgStackOffset i ) 
   { checkTag(FLOAT_TAG,Sp[i]);   return PK_FLT(Sp+1+i); }
static inline StgDouble       taggedStackDouble  ( StgStackOffset i ) 
   { checkTag(DOUBLE_TAG,Sp[i]);  return PK_DBL(Sp+1+i); }
static inline StgStablePtr    taggedStackStable  ( StgStackOffset i ) 
   { checkTag(STABLE_TAG,Sp[i]);  return *stgCast(StgStablePtr*,   Sp+1+i); }


/* --------------------------------------------------------------------------
 * Heap allocation
 *
 * Should we allocate from a nursery or use the
 * doYouWantToGC/allocate interface?  We'd already implemented a
 * nursery-style scheme when the doYouWantToGC/allocate interface
 * was implemented.
 * One reason to prefer the doYouWantToGC/allocate interface is to 
 * support operations which allocate an unknown amount in the heap
 * (array ops, gmp ops, etc)
 * ------------------------------------------------------------------------*/

static inline StgPtr grabHpUpd( nat size )
{
    ASSERT( size >= MIN_UPD_SIZE + sizeofW(StgHeader) );
1575
#ifdef CRUDE_PROFILING
1576 1577 1578 1579 1580 1581 1582 1583
    cp_bill_words ( size );
#endif
    return allocate(size);
}

static inline StgPtr grabHpNonUpd( nat size )
{
    ASSERT( size >= MIN_NONUPD_SIZE + sizeofW(StgHeader) );
1584
#ifdef CRUDE_PROFILING
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
    cp_bill_words ( size );
#endif
    return allocate(size);
}

/* --------------------------------------------------------------------------
 * Manipulate "update frame" list:
 * o Update frames           (based on stg_do_update and friends in Updates.hc)
 * o Error handling/catching (based on catchzh_fast and friends in Prims.hc)
 * o Seq frames              (based on seq_frame_entry in Prims.hc)
 * o Stop frames
 * ------------------------------------------------------------------------*/

static inline void PopUpdateFrame( StgClosure* obj )
{
    /* NB: doesn't assume that Sp == Su */
    IF_DEBUG(evaluator,
             fprintf(stderr,  "Updating ");
             printPtr(stgCast(StgPtr,Su->updatee)); 
             fprintf(stderr,  " with ");
             printObj(obj);
             fprintf(stderr,"Sp = %p\tSu = %p\n\n", Sp, Su);
             );
1608
#ifdef EAGER_BLACKHOLING
1609
    ASSERT(get_itbl(Su->updatee)->type == BLACKHOLE
1610
           || get_itbl(Su->updatee)->type == SE_BLACKHOLE
1611
           || get_itbl(Su->updatee)->type == CAF_BLACKHOLE
1612
           || get_itbl(Su->updatee)->type == SE_CAF_BLACKHOLE
1613
           );
1614
#endif /* EAGER_BLACKHOLING */
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
    UPD_IND(Su->updatee,obj);
    Sp = stgCast(StgStackPtr,Su) + sizeofW(StgUpdateFrame);
    Su = Su->link;
}

static inline void PopStopFrame( StgClosure* obj )
{
    /* Move Su just off the end of the stack, we're about to spam the
     * STOP_FRAME with the return value.
     */
    Su = stgCast(StgUpdateFrame*,Sp+1);  
    *stgCast(StgClosure**,Sp) = obj;
}

static inline void PushCatchFrame( StgClosure* handler )
{
    StgCatchFrame* fp;
    /* ToDo: stack check! */
    Sp -= sizeofW(StgCatchFrame);
    fp = stgCast(StgCatchFrame*,Sp);
    SET_HDR(fp,&catch_frame_info,CCCS);
    fp->handler         = handler;
    fp->link            = Su;
    Su = stgCast(StgUpdateFrame*,fp);
}

static inline void PopCatchFrame( void )
{
    /* NB: doesn't assume that Sp == Su */
    /* fprintf(stderr,"Popping catch frame\n"); */
1645 1646 1647 1648
    Sp = stgCast(StgStackPtr,Su) + sizeofW(StgCatchFrame);
    Su = stgCast(StgCatchFrame*,Su)->link;		
}

1649
static inline void PushSeqFrame( void )
1650 1651 1652
{
    StgSeqFrame* fp;
    /* ToDo: stack check! */
1653
    Sp -= sizeofW(StgSeqFrame);
1654 1655 1656 1657 1658 1659
    fp = stgCast(StgSeqFrame*,Sp);
    SET_HDR(fp,&seq_frame_info,CCCS);
    fp->link = Su;
    Su = stgCast(StgUpdateFrame*,fp);
}

1660
static inline void PopSeqFrame( void )
1661 1662 1663 1664 1665 1666
{
    /* NB: doesn't assume that Sp == Su */
    Sp = stgCast(StgStackPtr,Su) + sizeofW(StgSeqFrame);
    Su = stgCast(StgSeqFrame*,Su)->link;		
}

1667
static inline StgClosure* raiseAnError( StgClosure* errObj )
1668
{
1669 1670 1671
    StgClosure *raise_closure;

    /* This closure represents the expression 'raise# E' where E
1672
     * is the exception raised.  It is used to overwrite all the
1673 1674 1675 1676 1677 1678
     * thunks which are currently under evaluataion.
     */
    raise_closure = (StgClosure *)allocate(sizeofW(StgClosure)+1);
    raise_closure->header.info = &raise_info;
    raise_closure->payload[0] = R1.cl;

1679 1680 1681
    while (1) {
        switch (get_itbl(Su)->type) {
        case UPDATE_FRAME:
1682
                UPD_IND(Su->updatee,raise_closure);
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
                Sp = stgCast(StgStackPtr,Su) + sizeofW(StgUpdateFrame);
                Su = Su->link;
                break;
        case SEQ_FRAME:
                PopSeqFrame();
                break;
        case CATCH_FRAME:  /* found it! */
            {
                StgCatchFrame* fp = stgCast(StgCatchFrame*,Su);
                StgClosure *handler = fp->handler;
                Su = fp->link; 
                Sp += sizeofW(StgCatchFrame); /* Pop */
                PushCPtr(errObj);
                return handler;
1697
	    }
1698
        case STOP_FRAME:
1699
                barf("raiseError: uncaught exception: STOP_FRAME");
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
        default:
                barf("raiseError: weird activation record");
        }
    }
}

static StgClosure* raisePrim(char* msg)
{
    /* ToDo: figure out some way to turn the msg into a Haskell Exception
     * Hack: we don't know how to build an Exception but we do know how
     * to build a (recursive!) error object.
     * The result isn't pretty but it's (slightly) better than nothing.
     */
    nat size = sizeof(StgClosure) + 1;
    StgClosure* errObj = stgCast(StgClosure*,grabHpNonUpd(size));
    SET_INFO(errObj,&raise_info);
    errObj->payload[0] = errObj;
1717
fprintf(stderr, "\n\n\nRAISE PRIM %s\n", msg);
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760