[project @ 2005-07-12 12:09:44 by simonmar]
[ghc-hetmet.git] / ghc / rts / Interpreter.c
1 /* -----------------------------------------------------------------------------
2  * Bytecode interpreter
3  *
4  * Copyright (c) The GHC Team, 1994-2002.
5  * ---------------------------------------------------------------------------*/
6
7 #include "PosixSource.h"
8 #include "Rts.h"
9 #include "RtsAPI.h"
10 #include "RtsUtils.h"
11 #include "Closures.h"
12 #include "TSO.h"
13 #include "Schedule.h"
14 #include "RtsFlags.h"
15 #include "Storage.h"
16 #include "LdvProfile.h"
17 #include "Updates.h"
18 #include "Sanity.h"
19 #include "Liveness.h"
20
21 #include "Bytecodes.h"
22 #include "Printer.h"
23 #include "Disassembler.h"
24 #include "Interpreter.h"
25
26 #include <string.h>     /* for memcpy */
27 #ifdef HAVE_ERRNO_H
28 #include <errno.h>
29 #endif
30
31
32 /* --------------------------------------------------------------------------
33  * The bytecode interpreter
34  * ------------------------------------------------------------------------*/
35
36 /* Gather stats about entry, opcode, opcode-pair frequencies.  For
37    tuning the interpreter. */
38
39 /* #define INTERP_STATS */
40
41
42 /* Sp points to the lowest live word on the stack. */
43
44 #define BCO_NEXT      instrs[bciPtr++]
45 #define BCO_PTR(n)    (W_)ptrs[n]
46 #define BCO_LIT(n)    literals[n]
47 #define BCO_ITBL(n)   itbls[n]
48
49 #define LOAD_STACK_POINTERS                                     \
50     Sp = cap->r.rCurrentTSO->sp;                                \
51     /* We don't change this ... */                              \
52     SpLim = cap->r.rCurrentTSO->stack + RESERVED_STACK_WORDS;
53
54 #define SAVE_STACK_POINTERS                     \
55     cap->r.rCurrentTSO->sp = Sp
56
57 #define RETURN_TO_SCHEDULER(todo,retcode)       \
58    SAVE_STACK_POINTERS;                         \
59    cap->r.rCurrentTSO->what_next = (todo);      \
60    threadPaused(cap->r.rCurrentTSO);            \
61    return (retcode);
62
63 #define RETURN_TO_SCHEDULER_NO_PAUSE(todo,retcode)      \
64    SAVE_STACK_POINTERS;                         \
65    cap->r.rCurrentTSO->what_next = (todo);      \
66    return (retcode);
67
68
69 STATIC_INLINE StgPtr
70 allocate_UPD (int n_words)
71 {
72    return allocate(stg_max(sizeofW(StgHeader)+MIN_UPD_SIZE, n_words));
73 }
74
75 STATIC_INLINE StgPtr
76 allocate_NONUPD (int n_words)
77 {
78     return allocate(stg_max(sizeofW(StgHeader)+MIN_NONUPD_SIZE, n_words));
79 }
80
81
82 #ifdef INTERP_STATS
83
84 /* Hacky stats, for tuning the interpreter ... */
85 int it_unknown_entries[N_CLOSURE_TYPES];
86 int it_total_unknown_entries;
87 int it_total_entries;
88
89 int it_retto_BCO;
90 int it_retto_UPDATE;
91 int it_retto_other;
92
93 int it_slides;
94 int it_insns;
95 int it_BCO_entries;
96
97 int it_ofreq[27];
98 int it_oofreq[27][27];
99 int it_lastopc;
100
101 #define INTERP_TICK(n) (n)++
102
103 void interp_startup ( void )
104 {
105    int i, j;
106    it_retto_BCO = it_retto_UPDATE = it_retto_other = 0;
107    it_total_entries = it_total_unknown_entries = 0;
108    for (i = 0; i < N_CLOSURE_TYPES; i++)
109       it_unknown_entries[i] = 0;
110    it_slides = it_insns = it_BCO_entries = 0;
111    for (i = 0; i < 27; i++) it_ofreq[i] = 0;
112    for (i = 0; i < 27; i++) 
113      for (j = 0; j < 27; j++)
114         it_oofreq[i][j] = 0;
115    it_lastopc = 0;
116 }
117
118 void interp_shutdown ( void )
119 {
120    int i, j, k, o_max, i_max, j_max;
121    debugBelch("%d constrs entered -> (%d BCO, %d UPD, %d ??? )\n",
122                    it_retto_BCO + it_retto_UPDATE + it_retto_other,
123                    it_retto_BCO, it_retto_UPDATE, it_retto_other );
124    debugBelch("%d total entries, %d unknown entries \n", 
125                    it_total_entries, it_total_unknown_entries);
126    for (i = 0; i < N_CLOSURE_TYPES; i++) {
127      if (it_unknown_entries[i] == 0) continue;
128      debugBelch("   type %2d: unknown entries (%4.1f%%) == %d\n",
129              i, 100.0 * ((double)it_unknown_entries[i]) / 
130                         ((double)it_total_unknown_entries),
131              it_unknown_entries[i]);
132    }
133    debugBelch("%d insns, %d slides, %d BCO_entries\n", 
134                    it_insns, it_slides, it_BCO_entries);
135    for (i = 0; i < 27; i++) 
136       debugBelch("opcode %2d got %d\n", i, it_ofreq[i] );
137
138    for (k = 1; k < 20; k++) {
139       o_max = 0;
140       i_max = j_max = 0;
141       for (i = 0; i < 27; i++) {
142          for (j = 0; j < 27; j++) {
143             if (it_oofreq[i][j] > o_max) {
144                o_max = it_oofreq[i][j];
145                i_max = i; j_max = j;
146             }
147          }
148       }
149       
150       debugBelch("%d:  count (%4.1f%%) %6d   is %d then %d\n",
151                 k, ((double)o_max) * 100.0 / ((double)it_insns), o_max,
152                    i_max, j_max );
153       it_oofreq[i_max][j_max] = 0;
154
155    }
156 }
157
158 #else // !INTERP_STATS
159
160 #define INTERP_TICK(n) /* nothing */
161
162 #endif
163
164 static StgWord app_ptrs_itbl[] = {
165     (W_)&stg_ap_p_info,
166     (W_)&stg_ap_pp_info,
167     (W_)&stg_ap_ppp_info,
168     (W_)&stg_ap_pppp_info,
169     (W_)&stg_ap_ppppp_info,
170     (W_)&stg_ap_pppppp_info,
171 };
172
173 StgThreadReturnCode
174 interpretBCO (Capability* cap)
175 {
176     // Use of register here is primarily to make it clear to compilers
177     // that these entities are non-aliasable.
178     register StgPtr       Sp;    // local state -- stack pointer
179     register StgPtr       SpLim; // local state -- stack lim pointer
180     register StgClosure*  obj;
181     nat n, m;
182
183     LOAD_STACK_POINTERS;
184
185     // ------------------------------------------------------------------------
186     // Case 1:
187     // 
188     //       We have a closure to evaluate.  Stack looks like:
189     //       
190     //          |   XXXX_info   |
191     //          +---------------+
192     //       Sp |      -------------------> closure
193     //          +---------------+
194     //       
195     if (Sp[0] == (W_)&stg_enter_info) {
196         Sp++;
197         goto eval;
198     }
199
200     // ------------------------------------------------------------------------
201     // Case 2:
202     // 
203     //       We have a BCO application to perform.  Stack looks like:
204     //
205     //          |     ....      |
206     //          +---------------+
207     //          |     arg1      |
208     //          +---------------+
209     //          |     BCO       |
210     //          +---------------+
211     //       Sp |   RET_BCO     |
212     //          +---------------+
213     //       
214     else if (Sp[0] == (W_)&stg_apply_interp_info) {
215         obj = (StgClosure *)Sp[1];
216         Sp += 2;
217         goto run_BCO_fun;
218     }
219
220     // ------------------------------------------------------------------------
221     // Case 3:
222     //
223     //       We have an unboxed value to return.  See comment before
224     //       do_return_unboxed, below.
225     //
226     else {
227         goto do_return_unboxed;
228     }
229
230     // Evaluate the object on top of the stack.
231 eval:
232     obj = (StgClosure*)Sp[0]; Sp++;
233
234 eval_obj:
235     INTERP_TICK(it_total_evals);
236
237     IF_DEBUG(interpreter,
238              debugBelch(
239              "\n---------------------------------------------------------------\n");
240              debugBelch("Evaluating: "); printObj(obj);
241              debugBelch("Sp = %p\n", Sp);
242              debugBelch("\n" );
243
244              printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
245              debugBelch("\n\n");
246             );
247
248     IF_DEBUG(sanity,checkStackChunk(Sp, cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size));
249
250     switch ( get_itbl(obj)->type ) {
251
252     case IND:
253     case IND_OLDGEN:
254     case IND_PERM:
255     case IND_OLDGEN_PERM:
256     case IND_STATIC:
257     { 
258         obj = ((StgInd*)obj)->indirectee;
259         goto eval_obj;
260     }
261     
262     case CONSTR:
263     case CONSTR_1_0:
264     case CONSTR_0_1:
265     case CONSTR_2_0:
266     case CONSTR_1_1:
267     case CONSTR_0_2:
268     case CONSTR_INTLIKE:
269     case CONSTR_CHARLIKE:
270     case CONSTR_STATIC:
271     case CONSTR_NOCAF_STATIC:
272     case FUN:
273     case FUN_1_0:
274     case FUN_0_1:
275     case FUN_2_0:
276     case FUN_1_1:
277     case FUN_0_2:
278     case FUN_STATIC:
279     case PAP:
280         // already in WHNF
281         break;
282         
283     case BCO:
284         ASSERT(((StgBCO *)obj)->arity > 0);
285         break;
286
287     case AP:    /* Copied from stg_AP_entry. */
288     {
289         nat i, words;
290         StgAP *ap;
291         
292         ap = (StgAP*)obj;
293         words = ap->n_args;
294         
295         // Stack check
296         if (Sp - (words+sizeofW(StgUpdateFrame)) < SpLim) {
297             Sp -= 2;
298             Sp[1] = (W_)obj;
299             Sp[0] = (W_)&stg_enter_info;
300             RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
301         }
302         
303         /* Ok; we're safe.  Party on.  Push an update frame. */
304         Sp -= sizeofW(StgUpdateFrame);
305         {
306             StgUpdateFrame *__frame;
307             __frame = (StgUpdateFrame *)Sp;
308             SET_INFO(__frame, (StgInfoTable *)&stg_upd_frame_info);
309             __frame->updatee = (StgClosure *)(ap);
310         }
311         
312         /* Reload the stack */
313         Sp -= words;
314         for (i=0; i < words; i++) {
315             Sp[i] = (W_)ap->payload[i];
316         }
317
318         obj = (StgClosure*)ap->fun;
319         ASSERT(get_itbl(obj)->type == BCO);
320         goto run_BCO_fun;
321     }
322
323     default:
324 #ifdef INTERP_STATS
325     { 
326         int j;
327         
328         j = get_itbl(obj)->type;
329         ASSERT(j >= 0 && j < N_CLOSURE_TYPES);
330         it_unknown_entries[j]++;
331         it_total_unknown_entries++;
332     }
333 #endif
334     {
335         // Can't handle this object; yield to scheduler
336         IF_DEBUG(interpreter,
337                  debugBelch("evaluating unknown closure -- yielding to sched\n"); 
338                  printObj(obj);
339             );
340         Sp -= 2;
341         Sp[1] = (W_)obj;
342         Sp[0] = (W_)&stg_enter_info;
343         RETURN_TO_SCHEDULER_NO_PAUSE(ThreadRunGHC, ThreadYielding);
344     }
345     }
346
347     // ------------------------------------------------------------------------
348     // We now have an evaluated object (obj).  The next thing to
349     // do is return it to the stack frame on top of the stack.
350 do_return:
351     ASSERT(closure_HNF(obj));
352
353     IF_DEBUG(interpreter,
354              debugBelch(
355              "\n---------------------------------------------------------------\n");
356              debugBelch("Returning: "); printObj(obj);
357              debugBelch("Sp = %p\n", Sp);
358              debugBelch("\n" );
359              printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
360              debugBelch("\n\n");
361             );
362
363     IF_DEBUG(sanity,checkStackChunk(Sp, cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size));
364
365     switch (get_itbl((StgClosure *)Sp)->type) {
366
367     case RET_SMALL: {
368         const StgInfoTable *info;
369
370         // NOTE: not using get_itbl().
371         info = ((StgClosure *)Sp)->header.info;
372         if (info == (StgInfoTable *)&stg_ap_v_info) {
373             n = 1; m = 0; goto do_apply;
374         }
375         if (info == (StgInfoTable *)&stg_ap_f_info) {
376             n = 1; m = 1; goto do_apply;
377         }
378         if (info == (StgInfoTable *)&stg_ap_d_info) {
379             n = 1; m = sizeofW(StgDouble); goto do_apply;
380         }
381         if (info == (StgInfoTable *)&stg_ap_l_info) {
382             n = 1; m = sizeofW(StgInt64); goto do_apply;
383         }
384         if (info == (StgInfoTable *)&stg_ap_n_info) {
385             n = 1; m = 1; goto do_apply;
386         }
387         if (info == (StgInfoTable *)&stg_ap_p_info) {
388             n = 1; m = 1; goto do_apply;
389         }
390         if (info == (StgInfoTable *)&stg_ap_pp_info) {
391             n = 2; m = 2; goto do_apply;
392         }
393         if (info == (StgInfoTable *)&stg_ap_ppp_info) {
394             n = 3; m = 3; goto do_apply;
395         }
396         if (info == (StgInfoTable *)&stg_ap_pppp_info) {
397             n = 4; m = 4; goto do_apply;
398         }
399         if (info == (StgInfoTable *)&stg_ap_ppppp_info) {
400             n = 5; m = 5; goto do_apply;
401         }
402         if (info == (StgInfoTable *)&stg_ap_pppppp_info) {
403             n = 6; m = 6; goto do_apply;
404         }
405         goto do_return_unrecognised;
406     }
407
408     case UPDATE_FRAME:
409         // Returning to an update frame: do the update, pop the update
410         // frame, and continue with the next stack frame.
411         INTERP_TICK(it_retto_UPDATE);
412         UPD_IND(((StgUpdateFrame *)Sp)->updatee, obj); 
413         Sp += sizeofW(StgUpdateFrame);
414         goto do_return;
415
416     case RET_BCO:
417         // Returning to an interpreted continuation: put the object on
418         // the stack, and start executing the BCO.
419         INTERP_TICK(it_retto_BCO);
420         Sp--;
421         Sp[0] = (W_)obj;
422         obj = (StgClosure*)Sp[2];
423         ASSERT(get_itbl(obj)->type == BCO);
424         goto run_BCO_return;
425
426     default:
427     do_return_unrecognised:
428     {
429         // Can't handle this return address; yield to scheduler
430         INTERP_TICK(it_retto_other);
431         IF_DEBUG(interpreter,
432                  debugBelch("returning to unknown frame -- yielding to sched\n"); 
433                  printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
434             );
435         Sp -= 2;
436         Sp[1] = (W_)obj;
437         Sp[0] = (W_)&stg_enter_info;
438         RETURN_TO_SCHEDULER_NO_PAUSE(ThreadRunGHC, ThreadYielding);
439     }
440     }
441
442     // -------------------------------------------------------------------------
443     // Returning an unboxed value.  The stack looks like this:
444     //
445     //    |     ....      |
446     //    +---------------+
447     //    |     fv2       |
448     //    +---------------+
449     //    |     fv1       |
450     //    +---------------+
451     //    |     BCO       |
452     //    +---------------+
453     //    | stg_ctoi_ret_ |
454     //    +---------------+
455     //    |    retval     |
456     //    +---------------+
457     //    |   XXXX_info   |
458     //    +---------------+
459     //
460     // where XXXX_info is one of the stg_gc_unbx_r1_info family.
461     //
462     // We're only interested in the case when the real return address
463     // is a BCO; otherwise we'll return to the scheduler.
464
465 do_return_unboxed:
466     { 
467         int offset;
468         
469         ASSERT( Sp[0] == (W_)&stg_gc_unbx_r1_info
470                 || Sp[0] == (W_)&stg_gc_unpt_r1_info
471                 || Sp[0] == (W_)&stg_gc_f1_info
472                 || Sp[0] == (W_)&stg_gc_d1_info
473                 || Sp[0] == (W_)&stg_gc_l1_info
474                 || Sp[0] == (W_)&stg_gc_void_info // VoidRep
475             );
476
477         // get the offset of the stg_ctoi_ret_XXX itbl
478         offset = stack_frame_sizeW((StgClosure *)Sp);
479
480         switch (get_itbl((StgClosure *)Sp+offset)->type) {
481
482         case RET_BCO:
483             // Returning to an interpreted continuation: put the object on
484             // the stack, and start executing the BCO.
485             INTERP_TICK(it_retto_BCO);
486             obj = (StgClosure*)Sp[offset+1];
487             ASSERT(get_itbl(obj)->type == BCO);
488             goto run_BCO_return_unboxed;
489
490         default:
491         {
492             // Can't handle this return address; yield to scheduler
493             INTERP_TICK(it_retto_other);
494             IF_DEBUG(interpreter,
495                      debugBelch("returning to unknown frame -- yielding to sched\n"); 
496                      printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
497                 );
498             RETURN_TO_SCHEDULER_NO_PAUSE(ThreadRunGHC, ThreadYielding);
499         }
500         }
501     }
502     // not reached.
503
504
505     // -------------------------------------------------------------------------
506     // Application...
507
508 do_apply:
509     // we have a function to apply (obj), and n arguments taking up m
510     // words on the stack.  The info table (stg_ap_pp_info or whatever)
511     // is on top of the arguments on the stack.
512     {
513         switch (get_itbl(obj)->type) {
514
515         case PAP: {
516             StgPAP *pap;
517             nat arity, i;
518
519             pap = (StgPAP *)obj;
520
521             // we only cope with PAPs whose function is a BCO
522             if (get_itbl(pap->fun)->type != BCO) {
523                 goto defer_apply_to_sched;
524             }
525
526             Sp++;
527             arity = pap->arity;
528             ASSERT(arity > 0);
529             if (arity < n) {
530                 // n must be greater than 1, and the only kinds of
531                 // application we support with more than one argument
532                 // are all pointers...
533                 //
534                 // Shuffle the args for this function down, and put
535                 // the appropriate info table in the gap.
536                 for (i = 0; i < arity; i++) {
537                     Sp[i-1] = Sp[i];
538                 }
539                 Sp[arity-1] = app_ptrs_itbl[n-arity-1];
540                 Sp--;
541                 // unpack the PAP's arguments onto the stack
542                 Sp -= pap->n_args;
543                 for (i = 0; i < pap->n_args; i++) {
544                     Sp[i] = (W_)pap->payload[i];
545                 }
546                 obj = pap->fun;
547                 goto run_BCO_fun;
548             } 
549             else if (arity == n) {
550                 Sp -= pap->n_args;
551                 for (i = 0; i < pap->n_args; i++) {
552                     Sp[i] = (W_)pap->payload[i];
553                 }
554                 obj = pap->fun;
555                 goto run_BCO_fun;
556             } 
557             else /* arity > n */ {
558                 // build a new PAP and return it.
559                 StgPAP *new_pap;
560                 nat size;
561                 size = PAP_sizeW(pap->n_args + m);
562                 new_pap = (StgPAP *)allocate(size);
563                 SET_HDR(new_pap,&stg_PAP_info,CCCS);
564                 new_pap->arity = pap->arity - n;
565                 new_pap->n_args = pap->n_args + m;
566                 new_pap->fun = pap->fun;
567                 for (i = 0; i < pap->n_args; i++) {
568                     new_pap->payload[i] = pap->payload[i];
569                 }
570                 for (i = 0; i < m; i++) {
571                     new_pap->payload[pap->n_args + i] = (StgClosure *)Sp[i];
572                 }
573                 obj = (StgClosure *)new_pap;
574                 Sp += m;
575                 goto do_return;
576             }
577         }           
578
579         case BCO: {
580             nat arity;
581             int i; // arithmetic involving i might go negative below
582
583             Sp++;
584             arity = ((StgBCO *)obj)->arity;
585             ASSERT(arity > 0);
586             if (arity < n) {
587                 // n must be greater than 1, and the only kinds of
588                 // application we support with more than one argument
589                 // are all pointers...
590                 //
591                 // Shuffle the args for this function down, and put
592                 // the appropriate info table in the gap.
593                 for (i = 0; i < arity; i++) {
594                     Sp[i-1] = Sp[i];
595                 }
596                 Sp[arity-1] = app_ptrs_itbl[n-arity-1];
597                 Sp--;
598                 goto run_BCO_fun;
599             } 
600             else if (arity == n) {
601                 goto run_BCO_fun;
602             }
603             else /* arity > n */ {
604                 // build a PAP and return it.
605                 StgPAP *pap;
606                 nat size, i;
607                 size = PAP_sizeW(m);
608                 pap = (StgPAP *)allocate(size);
609                 SET_HDR(pap, &stg_PAP_info,CCCS);
610                 pap->arity = arity - n;
611                 pap->fun = obj;
612                 pap->n_args = m;
613                 for (i = 0; i < m; i++) {
614                     pap->payload[i] = (StgClosure *)Sp[i];
615                 }
616                 obj = (StgClosure *)pap;
617                 Sp += m;
618                 goto do_return;
619             }
620         }
621
622         // No point in us applying machine-code functions
623         default:
624         defer_apply_to_sched:
625             Sp -= 2;
626             Sp[1] = (W_)obj;
627             Sp[0] = (W_)&stg_enter_info;
628             RETURN_TO_SCHEDULER_NO_PAUSE(ThreadRunGHC, ThreadYielding);
629     }
630
631     // ------------------------------------------------------------------------
632     // Ok, we now have a bco (obj), and its arguments are all on the
633     // stack.  We can start executing the byte codes.
634     //
635     // The stack is in one of two states.  First, if this BCO is a
636     // function:
637     //
638     //    |     ....      |
639     //    +---------------+
640     //    |     arg2      |
641     //    +---------------+
642     //    |     arg1      |
643     //    +---------------+
644     //
645     // Second, if this BCO is a continuation:
646     //
647     //    |     ....      |
648     //    +---------------+
649     //    |     fv2       |
650     //    +---------------+
651     //    |     fv1       |
652     //    +---------------+
653     //    |     BCO       |
654     //    +---------------+
655     //    | stg_ctoi_ret_ |
656     //    +---------------+
657     //    |    retval     |
658     //    +---------------+
659     // 
660     // where retval is the value being returned to this continuation.
661     // In the event of a stack check, heap check, or context switch,
662     // we need to leave the stack in a sane state so the garbage
663     // collector can find all the pointers.
664     //
665     //  (1) BCO is a function:  the BCO's bitmap describes the
666     //      pointerhood of the arguments.
667     //
668     //  (2) BCO is a continuation: BCO's bitmap describes the
669     //      pointerhood of the free variables.
670     //
671     // Sadly we have three different kinds of stack/heap/cswitch check
672     // to do:
673
674 run_BCO_return:
675     // Heap check
676     if (doYouWantToGC()) {
677         Sp--; Sp[0] = (W_)&stg_enter_info;
678         RETURN_TO_SCHEDULER(ThreadInterpret, HeapOverflow);
679     }
680     // Stack checks aren't necessary at return points, the stack use
681     // is aggregated into the enclosing function entry point.
682     goto run_BCO;
683     
684 run_BCO_return_unboxed:
685     // Heap check
686     if (doYouWantToGC()) {
687         RETURN_TO_SCHEDULER(ThreadInterpret, HeapOverflow);
688     }
689     // Stack checks aren't necessary at return points, the stack use
690     // is aggregated into the enclosing function entry point.
691     goto run_BCO;
692     
693 run_BCO_fun:
694     IF_DEBUG(sanity,
695              Sp -= 2; 
696              Sp[1] = (W_)obj; 
697              Sp[0] = (W_)&stg_apply_interp_info;
698              checkStackChunk(Sp,SpLim);
699              Sp += 2;
700         );
701
702     // Heap check
703     if (doYouWantToGC()) {
704         Sp -= 2; 
705         Sp[1] = (W_)obj; 
706         Sp[0] = (W_)&stg_apply_interp_info; // placeholder, really
707         RETURN_TO_SCHEDULER(ThreadInterpret, HeapOverflow);
708     }
709     
710     // Stack check
711     if (Sp - INTERP_STACK_CHECK_THRESH < SpLim) {
712         Sp -= 2; 
713         Sp[1] = (W_)obj; 
714         Sp[0] = (W_)&stg_apply_interp_info; // placeholder, really
715         RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
716     }
717     goto run_BCO;
718     
719     // Now, actually interpret the BCO... (no returning to the
720     // scheduler again until the stack is in an orderly state).
721 run_BCO:
722     INTERP_TICK(it_BCO_entries);
723     {
724         register int       bciPtr     = 1; /* instruction pointer */
725         register StgBCO*   bco        = (StgBCO*)obj;
726         register StgWord16* instrs    = (StgWord16*)(bco->instrs->payload);
727         register StgWord*  literals   = (StgWord*)(&bco->literals->payload[0]);
728         register StgPtr*   ptrs       = (StgPtr*)(&bco->ptrs->payload[0]);
729         register StgInfoTable** itbls = (StgInfoTable**)
730             (&bco->itbls->payload[0]);
731
732 #ifdef INTERP_STATS
733         it_lastopc = 0; /* no opcode */
734 #endif
735
736     nextInsn:
737         ASSERT(bciPtr <= instrs[0]);
738         IF_DEBUG(interpreter,
739                  //if (do_print_stack) {
740                  //debugBelch("\n-- BEGIN stack\n");
741                  //printStack(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size,iSu);
742                  //debugBelch("-- END stack\n\n");
743                  //}
744                  debugBelch("Sp = %p   pc = %d      ", Sp, bciPtr);
745                  disInstr(bco,bciPtr);
746                  if (0) { int i;
747                  debugBelch("\n");
748                  for (i = 8; i >= 0; i--) {
749                      debugBelch("%d  %p\n", i, (StgPtr)(*(Sp+i)));
750                  }
751                  debugBelch("\n");
752                  }
753                  //if (do_print_stack) checkStack(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size,iSu);
754             );
755
756         INTERP_TICK(it_insns);
757
758 #ifdef INTERP_STATS
759         ASSERT( (int)instrs[bciPtr] >= 0 && (int)instrs[bciPtr] < 27 );
760         it_ofreq[ (int)instrs[bciPtr] ] ++;
761         it_oofreq[ it_lastopc ][ (int)instrs[bciPtr] ] ++;
762         it_lastopc = (int)instrs[bciPtr];
763 #endif
764
765         switch (BCO_NEXT) {
766
767         case bci_STKCHECK: {
768             // Explicit stack check at the beginning of a function
769             // *only* (stack checks in case alternatives are
770             // propagated to the enclosing function).
771             int stk_words_reqd = BCO_NEXT + 1;
772             if (Sp - stk_words_reqd < SpLim) {
773                 Sp -= 2; 
774                 Sp[1] = (W_)obj; 
775                 Sp[0] = (W_)&stg_apply_interp_info;
776                 RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
777             } else {
778                 goto nextInsn;
779             }
780         }
781
782         case bci_PUSH_L: {
783             int o1 = BCO_NEXT;
784             Sp[-1] = Sp[o1];
785             Sp--;
786             goto nextInsn;
787         }
788
789         case bci_PUSH_LL: {
790             int o1 = BCO_NEXT;
791             int o2 = BCO_NEXT;
792             Sp[-1] = Sp[o1];
793             Sp[-2] = Sp[o2];
794             Sp -= 2;
795             goto nextInsn;
796         }
797
798         case bci_PUSH_LLL: {
799             int o1 = BCO_NEXT;
800             int o2 = BCO_NEXT;
801             int o3 = BCO_NEXT;
802             Sp[-1] = Sp[o1];
803             Sp[-2] = Sp[o2];
804             Sp[-3] = Sp[o3];
805             Sp -= 3;
806             goto nextInsn;
807         }
808
809         case bci_PUSH_G: {
810             int o1 = BCO_NEXT;
811             Sp[-1] = BCO_PTR(o1);
812             Sp -= 1;
813             goto nextInsn;
814         }
815
816         case bci_PUSH_ALTS: {
817             int o_bco  = BCO_NEXT;
818             Sp[-2] = (W_)&stg_ctoi_R1p_info;
819             Sp[-1] = BCO_PTR(o_bco);
820             Sp -= 2;
821             goto nextInsn;
822         }
823
824         case bci_PUSH_ALTS_P: {
825             int o_bco  = BCO_NEXT;
826             Sp[-2] = (W_)&stg_ctoi_R1unpt_info;
827             Sp[-1] = BCO_PTR(o_bco);
828             Sp -= 2;
829             goto nextInsn;
830         }
831
832         case bci_PUSH_ALTS_N: {
833             int o_bco  = BCO_NEXT;
834             Sp[-2] = (W_)&stg_ctoi_R1n_info;
835             Sp[-1] = BCO_PTR(o_bco);
836             Sp -= 2;
837             goto nextInsn;
838         }
839
840         case bci_PUSH_ALTS_F: {
841             int o_bco  = BCO_NEXT;
842             Sp[-2] = (W_)&stg_ctoi_F1_info;
843             Sp[-1] = BCO_PTR(o_bco);
844             Sp -= 2;
845             goto nextInsn;
846         }
847
848         case bci_PUSH_ALTS_D: {
849             int o_bco  = BCO_NEXT;
850             Sp[-2] = (W_)&stg_ctoi_D1_info;
851             Sp[-1] = BCO_PTR(o_bco);
852             Sp -= 2;
853             goto nextInsn;
854         }
855
856         case bci_PUSH_ALTS_L: {
857             int o_bco  = BCO_NEXT;
858             Sp[-2] = (W_)&stg_ctoi_L1_info;
859             Sp[-1] = BCO_PTR(o_bco);
860             Sp -= 2;
861             goto nextInsn;
862         }
863
864         case bci_PUSH_ALTS_V: {
865             int o_bco  = BCO_NEXT;
866             Sp[-2] = (W_)&stg_ctoi_V_info;
867             Sp[-1] = BCO_PTR(o_bco);
868             Sp -= 2;
869             goto nextInsn;
870         }
871
872         case bci_PUSH_APPLY_N:
873             Sp--; Sp[0] = (W_)&stg_ap_n_info;
874             goto nextInsn;
875         case bci_PUSH_APPLY_V:
876             Sp--; Sp[0] = (W_)&stg_ap_v_info;
877             goto nextInsn;
878         case bci_PUSH_APPLY_F:
879             Sp--; Sp[0] = (W_)&stg_ap_f_info;
880             goto nextInsn;
881         case bci_PUSH_APPLY_D:
882             Sp--; Sp[0] = (W_)&stg_ap_d_info;
883             goto nextInsn;
884         case bci_PUSH_APPLY_L:
885             Sp--; Sp[0] = (W_)&stg_ap_l_info;
886             goto nextInsn;
887         case bci_PUSH_APPLY_P:
888             Sp--; Sp[0] = (W_)&stg_ap_p_info;
889             goto nextInsn;
890         case bci_PUSH_APPLY_PP:
891             Sp--; Sp[0] = (W_)&stg_ap_pp_info;
892             goto nextInsn;
893         case bci_PUSH_APPLY_PPP:
894             Sp--; Sp[0] = (W_)&stg_ap_ppp_info;
895             goto nextInsn;
896         case bci_PUSH_APPLY_PPPP:
897             Sp--; Sp[0] = (W_)&stg_ap_pppp_info;
898             goto nextInsn;
899         case bci_PUSH_APPLY_PPPPP:
900             Sp--; Sp[0] = (W_)&stg_ap_ppppp_info;
901             goto nextInsn;
902         case bci_PUSH_APPLY_PPPPPP:
903             Sp--; Sp[0] = (W_)&stg_ap_pppppp_info;
904             goto nextInsn;
905             
906         case bci_PUSH_UBX: {
907             int i;
908             int o_lits = BCO_NEXT;
909             int n_words = BCO_NEXT;
910             Sp -= n_words;
911             for (i = 0; i < n_words; i++) {
912                 Sp[i] = (W_)BCO_LIT(o_lits+i);
913             }
914             goto nextInsn;
915         }
916
917         case bci_SLIDE: {
918             int n  = BCO_NEXT;
919             int by = BCO_NEXT;
920             /* a_1, .. a_n, b_1, .. b_by, s => a_1, .. a_n, s */
921             while(--n >= 0) {
922                 Sp[n+by] = Sp[n];
923             }
924             Sp += by;
925             INTERP_TICK(it_slides);
926             goto nextInsn;
927         }
928
929         case bci_ALLOC_AP: {
930             StgAP* ap; 
931             int n_payload = BCO_NEXT;
932             int request   = PAP_sizeW(n_payload);
933             ap = (StgAP*)allocate_UPD(request);
934             Sp[-1] = (W_)ap;
935             ap->n_args = n_payload;
936             SET_HDR(ap, &stg_AP_info, CCS_SYSTEM/*ToDo*/)
937             Sp --;
938             goto nextInsn;
939         }
940
941         case bci_ALLOC_PAP: {
942             StgPAP* pap; 
943             int arity = BCO_NEXT;
944             int n_payload = BCO_NEXT;
945             int request   = PAP_sizeW(n_payload);
946             pap = (StgPAP*)allocate_NONUPD(request);
947             Sp[-1] = (W_)pap;
948             pap->n_args = n_payload;
949             pap->arity = arity;
950             SET_HDR(pap, &stg_PAP_info, CCS_SYSTEM/*ToDo*/)
951             Sp --;
952             goto nextInsn;
953         }
954
955         case bci_MKAP: {
956             int i;
957             int stkoff = BCO_NEXT;
958             int n_payload = BCO_NEXT;
959             StgAP* ap = (StgAP*)Sp[stkoff];
960             ASSERT((int)ap->n_args == n_payload);
961             ap->fun = (StgClosure*)Sp[0];
962
963             // The function should be a BCO, and its bitmap should
964             // cover the payload of the AP correctly.
965             ASSERT(get_itbl(ap->fun)->type == BCO
966                    && (get_itbl(ap)->type == PAP || 
967                        BCO_BITMAP_SIZE(ap->fun) == ap->n_args));
968
969             for (i = 0; i < n_payload; i++)
970                 ap->payload[i] = (StgClosure*)Sp[i+1];
971             Sp += n_payload+1;
972             IF_DEBUG(interpreter,
973                      debugBelch("\tBuilt "); 
974                      printObj((StgClosure*)ap);
975                 );
976             goto nextInsn;
977         }
978
979         case bci_UNPACK: {
980             /* Unpack N ptr words from t.o.s constructor */
981             int i;
982             int n_words = BCO_NEXT;
983             StgClosure* con = (StgClosure*)Sp[0];
984             Sp -= n_words;
985             for (i = 0; i < n_words; i++) {
986                 Sp[i] = (W_)con->payload[i];
987             }
988             goto nextInsn;
989         }
990
991         case bci_PACK: {
992             int i;
993             int o_itbl         = BCO_NEXT;
994             int n_words        = BCO_NEXT;
995             StgInfoTable* itbl = INFO_PTR_TO_STRUCT(BCO_ITBL(o_itbl));
996             int request        = CONSTR_sizeW( itbl->layout.payload.ptrs, 
997                                                itbl->layout.payload.nptrs );
998             StgClosure* con = (StgClosure*)allocate_NONUPD(request);
999             ASSERT( itbl->layout.payload.ptrs + itbl->layout.payload.nptrs > 0);
1000             SET_HDR(con, BCO_ITBL(o_itbl), CCS_SYSTEM/*ToDo*/);
1001             for (i = 0; i < n_words; i++) {
1002                 con->payload[i] = (StgClosure*)Sp[i];
1003             }
1004             Sp += n_words;
1005             Sp --;
1006             Sp[0] = (W_)con;
1007             IF_DEBUG(interpreter,
1008                      debugBelch("\tBuilt "); 
1009                      printObj((StgClosure*)con);
1010                 );
1011             goto nextInsn;
1012         }
1013
1014         case bci_TESTLT_P: {
1015             unsigned int discr  = BCO_NEXT;
1016             int failto = BCO_NEXT;
1017             StgClosure* con = (StgClosure*)Sp[0];
1018             if (GET_TAG(con) >= discr) {
1019                 bciPtr = failto;
1020             }
1021             goto nextInsn;
1022         }
1023
1024         case bci_TESTEQ_P: {
1025             unsigned int discr  = BCO_NEXT;
1026             int failto = BCO_NEXT;
1027             StgClosure* con = (StgClosure*)Sp[0];
1028             if (GET_TAG(con) != discr) {
1029                 bciPtr = failto;
1030             }
1031             goto nextInsn;
1032         }
1033
1034         case bci_TESTLT_I: {
1035             // There should be an Int at Sp[1], and an info table at Sp[0].
1036             int discr   = BCO_NEXT;
1037             int failto  = BCO_NEXT;
1038             I_ stackInt = (I_)Sp[1];
1039             if (stackInt >= (I_)BCO_LIT(discr))
1040                 bciPtr = failto;
1041             goto nextInsn;
1042         }
1043
1044         case bci_TESTEQ_I: {
1045             // There should be an Int at Sp[1], and an info table at Sp[0].
1046             int discr   = BCO_NEXT;
1047             int failto  = BCO_NEXT;
1048             I_ stackInt = (I_)Sp[1];
1049             if (stackInt != (I_)BCO_LIT(discr)) {
1050                 bciPtr = failto;
1051             }
1052             goto nextInsn;
1053         }
1054
1055         case bci_TESTLT_D: {
1056             // There should be a Double at Sp[1], and an info table at Sp[0].
1057             int discr   = BCO_NEXT;
1058             int failto  = BCO_NEXT;
1059             StgDouble stackDbl, discrDbl;
1060             stackDbl = PK_DBL( & Sp[1] );
1061             discrDbl = PK_DBL( & BCO_LIT(discr) );
1062             if (stackDbl >= discrDbl) {
1063                 bciPtr = failto;
1064             }
1065             goto nextInsn;
1066         }
1067
1068         case bci_TESTEQ_D: {
1069             // There should be a Double at Sp[1], and an info table at Sp[0].
1070             int discr   = BCO_NEXT;
1071             int failto  = BCO_NEXT;
1072             StgDouble stackDbl, discrDbl;
1073             stackDbl = PK_DBL( & Sp[1] );
1074             discrDbl = PK_DBL( & BCO_LIT(discr) );
1075             if (stackDbl != discrDbl) {
1076                 bciPtr = failto;
1077             }
1078             goto nextInsn;
1079         }
1080
1081         case bci_TESTLT_F: {
1082             // There should be a Float at Sp[1], and an info table at Sp[0].
1083             int discr   = BCO_NEXT;
1084             int failto  = BCO_NEXT;
1085             StgFloat stackFlt, discrFlt;
1086             stackFlt = PK_FLT( & Sp[1] );
1087             discrFlt = PK_FLT( & BCO_LIT(discr) );
1088             if (stackFlt >= discrFlt) {
1089                 bciPtr = failto;
1090             }
1091             goto nextInsn;
1092         }
1093
1094         case bci_TESTEQ_F: {
1095             // There should be a Float at Sp[1], and an info table at Sp[0].
1096             int discr   = BCO_NEXT;
1097             int failto  = BCO_NEXT;
1098             StgFloat stackFlt, discrFlt;
1099             stackFlt = PK_FLT( & Sp[1] );
1100             discrFlt = PK_FLT( & BCO_LIT(discr) );
1101             if (stackFlt != discrFlt) {
1102                 bciPtr = failto;
1103             }
1104             goto nextInsn;
1105         }
1106
1107         // Control-flow ish things
1108         case bci_ENTER:
1109             // Context-switch check.  We put it here to ensure that
1110             // the interpreter has done at least *some* work before
1111             // context switching: sometimes the scheduler can invoke
1112             // the interpreter with context_switch == 1, particularly
1113             // if the -C0 flag has been given on the cmd line.
1114             if (context_switch) {
1115                 Sp--; Sp[0] = (W_)&stg_enter_info;
1116                 RETURN_TO_SCHEDULER(ThreadInterpret, ThreadYielding);
1117             }
1118             goto eval;
1119
1120         case bci_RETURN:
1121             obj = (StgClosure *)Sp[0];
1122             Sp++;
1123             goto do_return;
1124
1125         case bci_RETURN_P:
1126             Sp--;
1127             Sp[0] = (W_)&stg_gc_unpt_r1_info;
1128             goto do_return_unboxed;
1129         case bci_RETURN_N:
1130             Sp--;
1131             Sp[0] = (W_)&stg_gc_unbx_r1_info;
1132             goto do_return_unboxed;
1133         case bci_RETURN_F:
1134             Sp--;
1135             Sp[0] = (W_)&stg_gc_f1_info;
1136             goto do_return_unboxed;
1137         case bci_RETURN_D:
1138             Sp--;
1139             Sp[0] = (W_)&stg_gc_d1_info;
1140             goto do_return_unboxed;
1141         case bci_RETURN_L:
1142             Sp--;
1143             Sp[0] = (W_)&stg_gc_l1_info;
1144             goto do_return_unboxed;
1145         case bci_RETURN_V:
1146             Sp--;
1147             Sp[0] = (W_)&stg_gc_void_info;
1148             goto do_return_unboxed;
1149
1150         case bci_SWIZZLE: {
1151             int stkoff = BCO_NEXT;
1152             signed short n = (signed short)(BCO_NEXT);
1153             Sp[stkoff] += (W_)n;
1154             goto nextInsn;
1155         }
1156
1157         case bci_CCALL: {
1158             StgInt tok;
1159             int stk_offset            = BCO_NEXT;
1160             int o_itbl                = BCO_NEXT;
1161             void(*marshall_fn)(void*) = (void (*)(void*))BCO_LIT(o_itbl);
1162             int ret_dyn_size = 
1163                 RET_DYN_BITMAP_SIZE + RET_DYN_NONPTR_REGS_SIZE
1164                 + sizeofW(StgRetDyn);
1165
1166 #ifdef RTS_SUPPORTS_THREADS
1167             // Threaded RTS:
1168             // Arguments on the TSO stack are not good, because garbage
1169             // collection might move the TSO as soon as we call
1170             // suspendThread below.
1171
1172             W_ arguments[stk_offset];
1173             
1174             memcpy(arguments, Sp, sizeof(W_) * stk_offset);
1175 #endif
1176
1177             // Restore the Haskell thread's current value of errno
1178             errno = cap->r.rCurrentTSO->saved_errno;
1179
1180             // There are a bunch of non-ptr words on the stack (the
1181             // ccall args, the ccall fun address and space for the
1182             // result), which we need to cover with an info table
1183             // since we might GC during this call.
1184             //
1185             // We know how many (non-ptr) words there are before the
1186             // next valid stack frame: it is the stk_offset arg to the
1187             // CCALL instruction.   So we build a RET_DYN stack frame
1188             // on the stack frame to describe this chunk of stack.
1189             //
1190             Sp -= ret_dyn_size;
1191             ((StgRetDyn *)Sp)->liveness = NO_PTRS | N_NONPTRS(stk_offset);
1192             ((StgRetDyn *)Sp)->info = (StgInfoTable *)&stg_gc_gen_info;
1193
1194             SAVE_STACK_POINTERS;
1195             tok = suspendThread(&cap->r);
1196
1197 #ifndef RTS_SUPPORTS_THREADS
1198             // Careful:
1199             // suspendThread might have shifted the stack
1200             // around (stack squeezing), so we have to grab the real
1201             // Sp out of the TSO to find the ccall args again.
1202
1203             marshall_fn ( (void*)(cap->r.rCurrentTSO->sp + ret_dyn_size) );
1204 #else
1205             // Threaded RTS:
1206             // We already made a copy of the arguments above.
1207
1208             marshall_fn ( arguments );
1209 #endif
1210
1211             // And restart the thread again, popping the RET_DYN frame.
1212             cap = (Capability *)((void *)((unsigned char*)resumeThread(tok) - sizeof(StgFunTable)));
1213             LOAD_STACK_POINTERS;
1214             Sp += ret_dyn_size;
1215             
1216             // Save the Haskell thread's current value of errno
1217             cap->r.rCurrentTSO->saved_errno = errno;
1218                 
1219 #ifdef RTS_SUPPORTS_THREADS
1220             // Threaded RTS:
1221             // Copy the "arguments", which might include a return value,
1222             // back to the TSO stack. It would of course be enough to
1223             // just copy the return value, but we don't know the offset.
1224             memcpy(Sp, arguments, sizeof(W_) * stk_offset);
1225 #endif
1226
1227             goto nextInsn;
1228         }
1229
1230         case bci_JMP: {
1231             /* BCO_NEXT modifies bciPtr, so be conservative. */
1232             int nextpc = BCO_NEXT;
1233             bciPtr     = nextpc;
1234             goto nextInsn;
1235         }
1236
1237         case bci_CASEFAIL:
1238             barf("interpretBCO: hit a CASEFAIL");
1239             
1240             // Errors
1241         default: 
1242             barf("interpretBCO: unknown or unimplemented opcode");
1243
1244         } /* switch on opcode */
1245     }
1246     }
1247
1248     barf("interpretBCO: fell off end of the interpreter");
1249 }