Merging in the new codegen branch
[ghc-hetmet.git] / rts / Exception.cmm
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2004
4  *
5  * Exception support
6  *
7  * This file is written in a subset of C--, extended with various
8  * features specific to GHC.  It is compiled by GHC directly.  For the
9  * syntax of .cmm files, see the parser in ghc/compiler/cmm/CmmParse.y.
10  *
11  * ---------------------------------------------------------------------------*/
12
13 #include "Cmm.h"
14 #include "RaiseAsync.h"
15
16 import ghczmprim_GHCziBool_True_closure;
17
18 /* -----------------------------------------------------------------------------
19    Exception Primitives
20
21    A thread can request that asynchronous exceptions not be delivered
22    ("blocked") for the duration of an I/O computation.  The primitive
23    
24         blockAsyncExceptions# :: IO a -> IO a
25
26    is used for this purpose.  During a blocked section, asynchronous
27    exceptions may be unblocked again temporarily:
28
29         unblockAsyncExceptions# :: IO a -> IO a
30
31    Furthermore, asynchronous exceptions are blocked automatically during
32    the execution of an exception handler.  Both of these primitives
33    leave a continuation on the stack which reverts to the previous
34    state (blocked or unblocked) on exit.
35
36    A thread which wants to raise an exception in another thread (using
37    killThread#) must block until the target thread is ready to receive
38    it.  The action of unblocking exceptions in a thread will release all
39    the threads waiting to deliver exceptions to that thread.
40
41    NB. there's a bug in here.  If a thread is inside an
42    unsafePerformIO, and inside blockAsyncExceptions# (there is an
43    unblockAsyncExceptions_ret on the stack), and it is blocked in an
44    interruptible operation, and it receives an exception, then the
45    unsafePerformIO thunk will be updated with a stack object
46    containing the unblockAsyncExceptions_ret frame.  Later, when
47    someone else evaluates this thunk, the blocked exception state is
48    not restored.
49
50    -------------------------------------------------------------------------- */
51
52 INFO_TABLE_RET( stg_unblockAsyncExceptionszh_ret, RET_SMALL )
53 {
54     CInt r;
55
56     StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) & 
57         ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
58
59     /* Eagerly raise a blocked exception, if there is one */
60     if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
61         /* 
62          * We have to be very careful here, as in killThread#, since
63          * we are about to raise an async exception in the current
64          * thread, which might result in the thread being killed.
65          */
66
67         STK_CHK_GEN( WDS(2), R1_PTR, stg_unblockAsyncExceptionszh_ret_info);
68         Sp_adj(-2);
69         Sp(1) = R1;
70         Sp(0) = stg_gc_unpt_r1_info;
71         SAVE_THREAD_STATE();
72         (r) = foreign "C" maybePerformBlockedException (MyCapability() "ptr", 
73                                                       CurrentTSO "ptr") [R1];
74
75         if (r != 0::CInt) {
76             if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
77                 jump stg_threadFinished;
78             } else {
79                 LOAD_THREAD_STATE();
80                 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
81                 jump %ENTRY_CODE(Sp(0));
82             }
83         }
84     }
85
86     Sp_adj(1);
87     jump %ENTRY_CODE(Sp(0));
88 }
89
90 INFO_TABLE_RET( stg_blockAsyncExceptionszh_ret, RET_SMALL )
91 {
92     StgTSO_flags(CurrentTSO) = 
93         StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
94
95     Sp_adj(1);
96     jump %ENTRY_CODE(Sp(0));
97 }
98
99 blockAsyncExceptionszh_fast
100 {
101     /* Args: R1 :: IO a */
102     STK_CHK_GEN( WDS(2)/* worst case */, R1_PTR, blockAsyncExceptionszh_fast);
103
104     if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) == 0) {
105         
106         StgTSO_flags(CurrentTSO) = 
107            StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
108
109         /* avoid growing the stack unnecessarily */
110         if (Sp(0) == stg_blockAsyncExceptionszh_ret_info) {
111             Sp_adj(1);
112         } else {
113             Sp_adj(-1);
114             Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
115         }
116     }
117     TICK_UNKNOWN_CALL();
118     TICK_SLOW_CALL_v();
119     jump stg_ap_v_fast;
120 }
121
122 unblockAsyncExceptionszh_fast
123 {
124     CInt r;
125
126     /* Args: R1 :: IO a */
127     STK_CHK_GEN( WDS(2), R1_PTR, unblockAsyncExceptionszh_fast);
128
129     if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) != 0) {
130
131         StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) & 
132            ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
133
134         /* Eagerly raise a blocked exception, if there is one */
135         if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
136             /* 
137              * We have to be very careful here, as in killThread#, since
138              * we are about to raise an async exception in the current
139              * thread, which might result in the thread being killed.
140              */
141             SAVE_THREAD_STATE();
142             (r) = foreign "C" maybePerformBlockedException (MyCapability() "ptr", 
143                                                       CurrentTSO "ptr") [R1];
144
145             if (r != 0::CInt) {
146                 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
147                     jump stg_threadFinished;
148                 } else {
149                     LOAD_THREAD_STATE();
150                     ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
151                     jump %ENTRY_CODE(Sp(0));
152                 }
153             }
154         }
155
156         /* avoid growing the stack unnecessarily */
157         if (Sp(0) == stg_unblockAsyncExceptionszh_ret_info) {
158             Sp_adj(1);
159         } else {
160             Sp_adj(-1);
161             Sp(0) = stg_blockAsyncExceptionszh_ret_info;
162         }
163     }
164     TICK_UNKNOWN_CALL();
165     TICK_SLOW_CALL_v();
166     jump stg_ap_v_fast;
167 }
168
169 asyncExceptionsBlockedzh_fast
170 {
171     /* args: none */
172     if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) != 0) {
173         RET_N(1);
174     } else {
175         RET_N(0);
176     }
177 }
178
179 killThreadzh_fast
180 {
181     /* args: R1 = TSO to kill, R2 = Exception */
182
183     W_ why_blocked;
184     W_ target;
185     W_ exception;
186     
187     target = R1;
188     exception = R2;
189     
190     STK_CHK_GEN( WDS(3), R1_PTR & R2_PTR, killThreadzh_fast);
191
192     /* 
193      * We might have killed ourselves.  In which case, better be *very*
194      * careful.  If the exception killed us, then return to the scheduler.
195      * If the exception went to a catch frame, we'll just continue from
196      * the handler.
197      */
198   loop:
199     if (StgTSO_what_next(target) == ThreadRelocated::I16) {
200         target = StgTSO__link(target);
201         goto loop;
202     }
203     if (target == CurrentTSO) {
204         SAVE_THREAD_STATE();
205         /* ToDo: what if the current thread is blocking exceptions? */
206         foreign "C" throwToSingleThreaded(MyCapability() "ptr", 
207                                           target "ptr", exception "ptr")[R1,R2];
208         if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
209             jump stg_threadFinished;
210         } else {
211             LOAD_THREAD_STATE();
212             ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
213             jump %ENTRY_CODE(Sp(0));
214         }
215     } else {
216         W_ out;
217         W_ retcode;
218         out = BaseReg + OFFSET_StgRegTable_rmp_tmp_w;
219         
220         (retcode) = foreign "C" throwTo(MyCapability() "ptr",
221                                       CurrentTSO "ptr",
222                                       target "ptr",
223                                       exception "ptr",
224                                       out "ptr") [R1,R2];
225         
226         switch [THROWTO_SUCCESS .. THROWTO_BLOCKED] (retcode) {
227
228         case THROWTO_SUCCESS: {
229             jump %ENTRY_CODE(Sp(0));
230         }
231
232         case THROWTO_BLOCKED: {
233             R3 = W_[out];
234             // we must block, and call throwToReleaseTarget() before returning
235             jump stg_block_throwto;
236         }
237         }
238     }
239 }
240
241 /* -----------------------------------------------------------------------------
242    Catch frames
243    -------------------------------------------------------------------------- */
244
245 #define SP_OFF 0
246
247 /* Catch frames are very similar to update frames, but when entering
248  * one we just pop the frame off the stack and perform the correct
249  * kind of return to the activation record underneath us on the stack.
250  */
251
252 INFO_TABLE_RET(stg_catch_frame, CATCH_FRAME,
253 #if defined(PROFILING)
254   W_ unused1, W_ unused2,
255 #endif
256   W_ unused3, P_ unused4)
257    {
258       Sp = Sp + SIZEOF_StgCatchFrame;
259       jump %ENTRY_CODE(Sp(SP_OFF));
260    }
261
262 /* -----------------------------------------------------------------------------
263  * The catch infotable
264  *
265  * This should be exactly the same as would be generated by this STG code
266  *
267  * catch = {x,h} \n {} -> catch#{x,h}
268  *
269  * It is used in deleteThread when reverting blackholes.
270  * -------------------------------------------------------------------------- */
271
272 INFO_TABLE(stg_catch,2,0,FUN,"catch","catch")
273 {
274   R2 = StgClosure_payload(R1,1); /* h */
275   R1 = StgClosure_payload(R1,0); /* x */
276   jump catchzh_fast;
277 }
278
279 catchzh_fast
280 {
281     /* args: R1 = m :: IO a, R2 = handler :: Exception -> IO a */
282     STK_CHK_GEN(SIZEOF_StgCatchFrame + WDS(1), R1_PTR & R2_PTR, catchzh_fast);
283   
284     /* Set up the catch frame */
285     Sp = Sp - SIZEOF_StgCatchFrame;
286     SET_HDR(Sp,stg_catch_frame_info,W_[CCCS]);
287     
288     StgCatchFrame_handler(Sp) = R2;
289     StgCatchFrame_exceptions_blocked(Sp) = TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX;
290     TICK_CATCHF_PUSHED();
291
292     /* Apply R1 to the realworld token */
293     TICK_UNKNOWN_CALL();
294     TICK_SLOW_CALL_v();
295     jump stg_ap_v_fast;
296 }
297
298 /* -----------------------------------------------------------------------------
299  * The raise infotable
300  * 
301  * This should be exactly the same as would be generated by this STG code
302  *
303  *   raise = {err} \n {} -> raise#{err}
304  *
305  * It is used in raisezh_fast to update thunks on the update list
306  * -------------------------------------------------------------------------- */
307
308 INFO_TABLE(stg_raise,1,0,THUNK_1_0,"raise","raise")
309 {
310   R1 = StgThunk_payload(R1,0);
311   jump raisezh_fast;
312 }
313
314 section "data" {
315   no_break_on_exception: W_[1];
316 }
317
318 INFO_TABLE_RET(stg_raise_ret, RET_SMALL, P_ arg1)
319 {
320   R1 = Sp(1);
321   Sp = Sp + WDS(2);
322   W_[no_break_on_exception] = 1;  
323   jump raisezh_fast;
324 }
325
326 raisezh_fast
327 {
328     W_ handler;
329     W_ frame_type;
330     W_ exception;
331     /* args : R1 :: Exception */
332
333    exception = R1;
334
335 #if defined(PROFILING)
336     /* Debugging tool: on raising an  exception, show where we are. */
337
338     /* ToDo: currently this is a hack.  Would be much better if
339      * the info was only displayed for an *uncaught* exception.
340      */
341     if (RtsFlags_ProfFlags_showCCSOnException(RtsFlags) != 0::I32) {
342       foreign "C" fprintCCS_stderr(W_[CCCS] "ptr") [];
343     }
344 #endif
345     
346 retry_pop_stack:
347     StgTSO_sp(CurrentTSO) = Sp;
348     (frame_type) = foreign "C" raiseExceptionHelper(BaseReg "ptr", CurrentTSO "ptr", exception "ptr") [];
349     Sp = StgTSO_sp(CurrentTSO);
350     if (frame_type == ATOMICALLY_FRAME) {
351       /* The exception has reached the edge of a memory transaction.  Check that 
352        * the transaction is valid.  If not then perhaps the exception should
353        * not have been thrown: re-run the transaction.  "trec" will either be
354        * a top-level transaction running the atomic block, or a nested 
355        * transaction running an invariant check.  In the latter case we
356        * abort and de-allocate the top-level transaction that encloses it
357        * as well (we could just abandon its transaction record, but this makes
358        * sure it's marked as aborted and available for re-use). */
359       W_ trec, outer;
360       W_ r;
361       trec = StgTSO_trec(CurrentTSO);
362       (r) = foreign "C" stmValidateNestOfTransactions(trec "ptr") [];
363       ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
364       foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
365       foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
366
367       if (outer != NO_TREC) {
368         foreign "C" stmAbortTransaction(MyCapability() "ptr", outer "ptr") [];
369         foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", outer "ptr") [];
370       }
371
372       StgTSO_trec(CurrentTSO) = NO_TREC;
373       if (r != 0) {
374         // Transaction was valid: continue searching for a catch frame
375         Sp = Sp + SIZEOF_StgAtomicallyFrame;
376         goto retry_pop_stack;
377       } else {
378         // Transaction was not valid: we retry the exception (otherwise continue
379         // with a further call to raiseExceptionHelper)
380         ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
381         StgTSO_trec(CurrentTSO) = trec;
382         R1 = StgAtomicallyFrame_code(Sp);
383         jump stg_ap_v_fast;
384       }          
385     }
386
387     // After stripping the stack, see whether we should break here for
388     // GHCi (c.f. the -fbreak-on-exception flag).  We do this after
389     // stripping the stack for a reason: we'll be inspecting values in
390     // GHCi, and it helps if all the thunks under evaluation have
391     // already been updated with the exception, rather than being left
392     // as blackholes.
393     if (W_[no_break_on_exception] != 0) {
394         W_[no_break_on_exception] = 0;
395     } else {
396         if (TO_W_(CInt[rts_stop_on_exception]) != 0) {
397             W_ ioAction;
398             // we don't want any further exceptions to be caught,
399             // until GHCi is ready to handle them.  This prevents
400             // deadlock if an exception is raised in InteractiveUI,
401             // for exmplae.  Perhaps the stop_on_exception flag should
402             // be per-thread.
403             W_[rts_stop_on_exception] = 0;
404             ("ptr" ioAction) = foreign "C" deRefStablePtr (W_[rts_breakpoint_io_action] "ptr") [];
405             Sp = Sp - WDS(7);
406             Sp(6) = exception;
407             Sp(5) = stg_raise_ret_info;
408             Sp(4) = stg_noforceIO_info;    // required for unregisterised
409             Sp(3) = exception;             // the AP_STACK
410             Sp(2) = ghczmprim_GHCziBool_True_closure; // dummy breakpoint info
411             Sp(1) = ghczmprim_GHCziBool_True_closure; // True <=> a breakpoint
412             R1 = ioAction;
413             jump RET_LBL(stg_ap_pppv);
414         }
415     }
416
417     if (frame_type == STOP_FRAME) {
418         /*
419          * We've stripped the entire stack, the thread is now dead.
420          * We will leave the stack in a GC'able state, see the stg_stop_thread
421          * entry code in StgStartup.cmm.
422          */
423         Sp = CurrentTSO + TSO_OFFSET_StgTSO_stack 
424                 + WDS(TO_W_(StgTSO_stack_size(CurrentTSO))) - WDS(2);
425         Sp(1) = exception;      /* save the exception */
426         Sp(0) = stg_enter_info; /* so that GC can traverse this stack */
427         StgTSO_what_next(CurrentTSO) = ThreadKilled::I16;
428         SAVE_THREAD_STATE();    /* inline! */
429
430         jump stg_threadFinished;
431     }
432
433     /* Ok, Sp points to the enclosing CATCH_FRAME or CATCH_STM_FRAME.  Pop everything
434      * down to and including this frame, update Su, push R1, and enter the handler.
435      */
436     if (frame_type == CATCH_FRAME) {
437       handler = StgCatchFrame_handler(Sp);
438     } else {
439       handler = StgCatchSTMFrame_handler(Sp);
440     }
441
442     /* Restore the blocked/unblocked state for asynchronous exceptions
443      * at the CATCH_FRAME.  
444      *
445      * If exceptions were unblocked, arrange that they are unblocked
446      * again after executing the handler by pushing an
447      * unblockAsyncExceptions_ret stack frame.
448      *
449      * If we've reached an STM catch frame then roll back the nested
450      * transaction we were using.
451      */
452     W_ frame;
453     frame = Sp;
454     if (frame_type == CATCH_FRAME) {
455       Sp = Sp + SIZEOF_StgCatchFrame;
456       if (StgCatchFrame_exceptions_blocked(frame) == 0) {
457         Sp_adj(-1);
458         Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
459       }
460     } else {
461       W_ trec, outer;
462       trec = StgTSO_trec(CurrentTSO);
463       ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
464       foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
465       foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
466       StgTSO_trec(CurrentTSO) = outer;
467       Sp = Sp + SIZEOF_StgCatchSTMFrame;
468     }
469
470     /* Ensure that async excpetions are blocked when running the handler.
471     */
472     StgTSO_flags(CurrentTSO) = 
473         StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
474
475     /* Call the handler, passing the exception value and a realworld
476      * token as arguments.
477      */
478     Sp_adj(-1);
479     Sp(0) = exception;
480     R1 = handler;
481     Sp_adj(-1);
482     TICK_UNKNOWN_CALL();
483     TICK_SLOW_CALL_pv();
484     jump RET_LBL(stg_ap_pv);
485 }
486
487 raiseIOzh_fast
488 {
489   /* Args :: R1 :: Exception */
490   jump raisezh_fast;
491 }