OSDN Git Service

./:
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch11.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             E X P _ C H 1 1                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2007, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with Casing;   use Casing;
29 with Debug;    use Debug;
30 with Einfo;    use Einfo;
31 with Elists;   use Elists;
32 with Errout;   use Errout;
33 with Exp_Ch7;  use Exp_Ch7;
34 with Exp_Util; use Exp_Util;
35 with Namet;    use Namet;
36 with Nlists;   use Nlists;
37 with Nmake;    use Nmake;
38 with Opt;      use Opt;
39 with Rtsfind;  use Rtsfind;
40 with Restrict; use Restrict;
41 with Rident;   use Rident;
42 with Sem;      use Sem;
43 with Sem_Ch8;  use Sem_Ch8;
44 with Sem_Res;  use Sem_Res;
45 with Sem_Util; use Sem_Util;
46 with Sinfo;    use Sinfo;
47 with Sinput;   use Sinput;
48 with Snames;   use Snames;
49 with Stand;    use Stand;
50 with Stringt;  use Stringt;
51 with Targparm; use Targparm;
52 with Tbuild;   use Tbuild;
53 with Uintp;    use Uintp;
54
55 package body Exp_Ch11 is
56
57    -----------------------
58    -- Local Subprograms --
59    -----------------------
60
61    procedure Warn_No_Exception_Propagation_Active (N : Node_Id);
62    --  Generates warning that pragma Restrictions (No_Exception_Propagation)
63    --  is in effect. Caller then generates appropriate continuation message.
64    --  N is the node on which the warning is placed.
65
66    procedure Warn_If_No_Propagation (N : Node_Id);
67    --  Called for an exception raise that is not a local raise (and thus can
68    --  not be optimized to a goto. Issues warning if No_Exception_Propagation
69    --  restriction is set. N is the node for the raise or equivalent call.
70
71    ---------------------------
72    -- Expand_At_End_Handler --
73    ---------------------------
74
75    --  For a handled statement sequence that has a cleanup (At_End_Proc
76    --  field set), an exception handler of the following form is required:
77
78    --     exception
79    --       when all others =>
80    --          cleanup call
81    --          raise;
82
83    --  Note: this exception handler is treated rather specially by
84    --  subsequent expansion in two respects:
85
86    --    The normal call to Undefer_Abort is omitted
87    --    The raise call does not do Defer_Abort
88
89    --  This is because the current tasking code seems to assume that
90    --  the call to the cleanup routine that is made from an exception
91    --  handler for the abort signal is called with aborts deferred.
92
93    --  This expansion is only done if we have front end exception handling.
94    --  If we have back end exception handling, then the AT END handler is
95    --  left alone, and cleanups (including the exceptional case) are handled
96    --  by the back end.
97
98    --  In the front end case, the exception handler described above handles
99    --  the exceptional case. The AT END handler is left in the generated tree
100    --  and the code generator (e.g. gigi) must still handle proper generation
101    --  of cleanup calls for the non-exceptional case.
102
103    procedure Expand_At_End_Handler (HSS : Node_Id; Block : Node_Id) is
104       Clean   : constant Entity_Id  := Entity (At_End_Proc (HSS));
105       Loc     : constant Source_Ptr := Sloc (Clean);
106       Ohandle : Node_Id;
107       Stmnts  : List_Id;
108
109    begin
110       pragma Assert (Present (Clean));
111       pragma Assert (No (Exception_Handlers (HSS)));
112
113       --  Don't expand if back end exception handling active
114
115       if Exception_Mechanism = Back_End_Exceptions then
116          return;
117       end if;
118
119       --  Don't expand an At End handler if we have already had configurable
120       --  run-time violations, since likely this will just be a matter of
121       --  generating useless cascaded messages
122
123       if Configurable_Run_Time_Violations > 0 then
124          return;
125       end if;
126
127       --  Don't expand an At End handler if we are not allowing exceptions
128       --  or if exceptions are transformed into local gotos, and never
129       --  propagated (No_Exception_Propagation).
130
131       if No_Exception_Handlers_Set then
132          return;
133       end if;
134
135       if Present (Block) then
136          Push_Scope (Block);
137       end if;
138
139       Ohandle :=
140         Make_Others_Choice (Loc);
141       Set_All_Others (Ohandle);
142
143       Stmnts := New_List (
144         Make_Procedure_Call_Statement (Loc,
145           Name => New_Occurrence_Of (Clean, Loc)),
146         Make_Raise_Statement (Loc));
147
148       Set_Exception_Handlers (HSS, New_List (
149         Make_Implicit_Exception_Handler (Loc,
150           Exception_Choices => New_List (Ohandle),
151           Statements        => Stmnts)));
152
153       Analyze_List (Stmnts, Suppress => All_Checks);
154       Expand_Exception_Handlers (HSS);
155
156       if Present (Block) then
157          Pop_Scope;
158       end if;
159    end Expand_At_End_Handler;
160
161    -------------------------------
162    -- Expand_Exception_Handlers --
163    -------------------------------
164
165    procedure Expand_Exception_Handlers (HSS : Node_Id) is
166       Handlrs       : constant List_Id    := Exception_Handlers (HSS);
167       Loc           : constant Source_Ptr := Sloc (HSS);
168       Handler       : Node_Id;
169       Others_Choice : Boolean;
170       Obj_Decl      : Node_Id;
171       Next_Handler  : Node_Id;
172
173       procedure Expand_Local_Exception_Handlers;
174       --  This procedure handles the expansion of exception handlers for the
175       --  optimization of local raise statements into goto statements.
176
177       procedure Prepend_Call_To_Handler
178         (Proc : RE_Id;
179          Args : List_Id := No_List);
180       --  Routine to prepend a call to the procedure referenced by Proc at
181       --  the start of the handler code for the current Handler.
182
183       procedure Replace_Raise_By_Goto (Raise_S : Node_Id; Goto_L1 : Node_Id);
184       --  Raise_S is a raise statement (possibly expanded, and possibly of the
185       --  form of a Raise_xxx_Error node with a condition. This procedure is
186       --  called to replace the raise action with the (already analyzed) goto
187       --  statement passed as Goto_L1. This procedure also takes care of the
188       --  requirement of inserting a Local_Raise call where possible.
189
190       -------------------------------------
191       -- Expand_Local_Exception_Handlers --
192       -------------------------------------
193
194       --  There are two cases for this transformation. First the case of
195       --  explicit raise statements. For this case, the transformation we do
196       --  looks like this. Right now we have for example (where L1, L2 are
197       --  exception labels)
198
199       --  begin
200       --     ...
201       --     raise_exception (excep1'identity);  -- was raise excep1
202       --     ...
203       --     raise_exception (excep2'identity);  -- was raise excep2
204       --     ...
205       --  exception
206       --     when excep1 =>
207       --        estmts1
208       --     when excep2 =>
209       --        estmts2
210       --  end;
211
212       --  This gets transformed into:
213
214       --  begin
215       --     L1 : label;                        -- marked Exception_Junk
216       --     L2 : label;                        -- marked Exception_Junk
217       --     L3 : label;                        -- marked Exception_Junk
218
219       --     begin                              -- marked Exception_Junk
220       --        ...
221       --        local_raise (excep1'address);   -- was raise excep1
222       --        goto L1;
223       --        ...
224       --        local_raise (excep2'address);   -- was raise excep2
225       --        goto L2;
226       --        ...
227       --     exception
228       --        when excep1 =>
229       --           goto L1;
230       --        when excep2 =>
231       --           goto L2;
232       --     end;
233
234       --     goto L3;        -- skip handler if no raise, marked Exception_Junk
235
236       --     <<L1>>          -- local excep target label, marked Exception_Junk
237       --        begin        -- marked Exception_Junk
238       --           estmts1
239       --        end;
240       --        goto L3;     -- marked Exception_Junk
241
242       --     <<L2>>          -- marked Exception_Junk
243       --        begin        -- marked Exception_Junk
244       --           estmts2
245       --        end;
246       --        goto L3;     -- marked Exception_Junk
247       --     <<L3>>          -- marked Exception_Junk
248       --  end;
249
250       --  Note: the reason we wrap the original statement sequence in an
251       --  inner block is that there may be raise statements within the
252       --  sequence of statements in the handlers, and we must ensure that
253       --  these are properly handled, and in particular, such raise statements
254       --  must not reenter the same exception handlers.
255
256       --  If the restriction No_Exception_Propagation is in effect, then we
257       --  can omit the exception handlers.
258
259       --  begin
260       --     L1 : label;                        -- marked Exception_Junk
261       --     L2 : label;                        -- marked Exception_Junk
262       --     L3 : label;                        -- marked Exception_Junk
263
264       --     begin                              -- marked Exception_Junk
265       --        ...
266       --        local_raise (excep1'address);   -- was raise excep1
267       --        goto L1;
268       --        ...
269       --        local_raise (excep2'address);   -- was raise excep2
270       --        goto L2;
271       --        ...
272       --     end;
273
274       --     goto L3;        -- skip handler if no raise, marked Exception_Junk
275
276       --     <<L1>>          -- local excep target label, marked Exception_Junk
277       --        begin        -- marked Exception_Junk
278       --           estmts1
279       --        end;
280       --        goto L3;     -- marked Exception_Junk
281
282       --     <<L2>>          -- marked Exception_Junk
283       --        begin        -- marked Exception_Junk
284       --           estmts2
285       --        end;
286
287       --     <<L3>>          -- marked Exception_Junk
288       --  end;
289
290       --  The second case is for exceptions generated by the back end in one
291       --  of three situations:
292
293       --    1. Front end generates N_Raise_xxx_Error node
294       --    2. Front end sets Do_xxx_Check flag in subexpression node
295       --    3. Back end detects a situation where an exception is appropriate
296
297       --  In all these cases, the current processing in gigi is to generate a
298       --  call to the appropriate Rcheck_xx routine (where xx encodes both the
299       --  exception message and the exception to be raised, Constraint_Error,
300       --  Program_Error, or Storage_Error.
301
302       --  We could handle some subcases of 1 using the same front end expansion
303       --  into gotos, but even for case 1, we can't handle all cases, since
304       --  generating gotos in the middle of expressions is not possible (it's
305       --  possible at the gigi/gcc level, but not at the level of the GNAT
306       --  tree).
307
308       --  In any case, it seems easier to have a scheme which handles all three
309       --  cases in a uniform manner. So here is how we proceed in this case.
310
311       --  This procedure detects all handlers for these three exceptions,
312       --  Constraint_Error, Program_Error and Storage_Error (including WHEN
313       --  OTHERS handlers that cover one or more of these cases).
314
315       --  If the handler meets the requirements for being the target of a local
316       --  raise, then the front end does the expansion described previously,
317       --  creating a label to be used as a goto target to raise the exception.
318       --  However, no attempt is made in the front end to convert any related
319       --  raise statements into gotos, e.g. all N_Raise_xxx_Error nodes are
320       --  left unchanged and passed to the back end.
321
322       --  Instead, the front end generates two nodes
323
324       --     N_Push_Constraint_Error_Label
325       --     N_Push_Program_Error_Label
326       --     N_Push_Storage_Error_Label
327
328       --       The Push node is generated at the start of the statements
329       --       covered by the handler, and has as a parameter the label to be
330       --       used as the raise target.
331
332       --     N_Pop_Constraint_Error_Label
333       --     N_Pop_Program_Error_Label
334       --     N_Pop_Storage_Error_Label
335
336       --       The Pop node is generated at the end of the covered statements
337       --       and undoes the effect of the preceding corresponding Push node.
338
339       --  In the case where the handler does NOT meet the requirements, the
340       --  front end will still generate the Push and Pop nodes, but the label
341       --  field in the Push node will be empty signifying that for this region
342       --  of code, no optimization is possible.
343
344       --  The back end must maintain three stacks, one for each exception case,
345       --  the Push node pushes an entry onto the corresponding stack, and Pop
346       --  node pops off the entry. Then instead of calling Rcheck_nn, if the
347       --  corresponding top stack entry has an non-empty label, a goto is
348       --  generated. This goto should be preceded by a call to Local_Raise as
349       --  described above.
350
351       --  An example of this transformation is as follows, given:
352
353       --  declare
354       --    A : Integer range 1 .. 10;
355       --  begin
356       --    A := B + C;
357       --  exception
358       --    when Constraint_Error =>
359       --       estmts
360       --  end;
361
362       --  gets transformed to:
363
364       --  declare
365       --    A : Integer range 1 .. 10;
366
367       --  begin
368       --     L1 : label;
369       --     L2 : label;
370
371       --     begin
372       --        %push_constraint_error_label (L1)
373       --        R1b : constant long_long_integer := long_long_integer?(b) +
374       --          long_long_integer?(c);
375       --        [constraint_error when
376       --          not (R1b in -16#8000_0000# .. 16#7FFF_FFFF#)
377       --          "overflow check failed"]
378       --        a := integer?(R1b);
379       --        %pop_constraint_error_Label
380
381       --     exception
382       --        ...
383       --        when constraint_error =>
384       --           goto L1;
385       --     end;
386
387       --     goto L2;       -- skip handler when exception not raised
388       --     <<L1>>         -- target label for local exception
389       --     estmts
390       --     <<L2>>
391       --  end;
392
393       --  Note: the generated labels and goto statements all have the flag
394       --  Exception_Junk set True, so that Sem_Ch6.Check_Returns will ignore
395       --  this generated exception stuff when checking for missing return
396       --  statements (see circuitry in Check_Statement_Sequence).
397
398       --  Note: All of the processing described above occurs only if
399       --  restriction No_Exception_Propagation applies or debug flag .g is
400       --  enabled.
401
402       CE_Locally_Handled : Boolean := False;
403       SE_Locally_Handled : Boolean := False;
404       PE_Locally_Handled : Boolean := False;
405       --  These three flags indicate whether a handler for the corresponding
406       --  exception (CE=Constraint_Error, SE=Storage_Error, PE=Program_Error)
407       --  is present. If so the switch is set to True, the Exception_Label
408       --  field of the corresponding handler is set, and appropriate Push
409       --  and Pop nodes are inserted into the code.
410
411       Local_Expansion_Required : Boolean := False;
412       --  Set True if we have at least one handler requiring local raise
413       --  expansion as described above.
414
415       procedure Expand_Local_Exception_Handlers is
416
417          procedure Add_Exception_Label (H : Node_Id);
418          --  H is an exception handler. First check for an Exception_Label
419          --  already allocated for H. If none, allocate one, set the field in
420          --  the handler node, add the label declaration, and set the flag
421          --  Local_Expansion_Required. Note: if Local_Raise_Not_OK is set
422          --  the call has no effect and Exception_Label is left empty.
423
424          procedure Add_Label_Declaration (L : Entity_Id);
425          --  Add an implicit declaration of the given label to the declaration
426          --  list in the parent of the current sequence of handled statements.
427
428          generic
429             Exc_Locally_Handled : in out Boolean;
430             --  Flag indicating whether a local handler for this exception
431             --  has already been generated.
432
433             with function Make_Push_Label (Loc : Source_Ptr) return Node_Id;
434             --  Function to create a Push_xxx_Label node
435
436             with function Make_Pop_Label (Loc : Source_Ptr) return Node_Id;
437             --  Function to create a Pop_xxx_Label node
438
439          procedure Generate_Push_Pop (H : Node_Id);
440          --  Common code for Generate_Push_Pop_xxx below, used to generate an
441          --  exception label and Push/Pop nodes for Constraint_Error,
442          --  Program_Error, or Storage_Error.
443
444          -------------------------
445          -- Add_Exception_Label --
446          -------------------------
447
448          procedure Add_Exception_Label (H : Node_Id) is
449          begin
450             if No (Exception_Label (H))
451               and then not Local_Raise_Not_OK (H)
452               and then not Special_Exception_Package_Used
453             then
454                Local_Expansion_Required := True;
455
456                declare
457                   L : constant Entity_Id :=
458                         Make_Defining_Identifier (Sloc (H),
459                           Chars => New_Internal_Name ('L'));
460                begin
461                   Set_Exception_Label (H, L);
462                   Add_Label_Declaration (L);
463                end;
464             end if;
465          end Add_Exception_Label;
466
467          ---------------------------
468          -- Add_Label_Declaration --
469          ---------------------------
470
471          procedure Add_Label_Declaration (L : Entity_Id) is
472             P : constant Node_Id := Parent (HSS);
473
474             Decl_L : constant Node_Id :=
475                        Make_Implicit_Label_Declaration (Loc,
476                          Defining_Identifier => L);
477
478          begin
479             if Declarations (P) = No_List then
480                Set_Declarations (P, Empty_List);
481             end if;
482
483             Append (Decl_L, Declarations (P));
484             Analyze (Decl_L);
485          end Add_Label_Declaration;
486
487          -----------------------
488          -- Generate_Push_Pop --
489          -----------------------
490
491          procedure Generate_Push_Pop (H : Node_Id) is
492          begin
493             if Exc_Locally_Handled then
494                return;
495             else
496                Exc_Locally_Handled := True;
497             end if;
498
499             Add_Exception_Label (H);
500
501             declare
502                F : constant Node_Id := First (Statements (HSS));
503                L : constant Node_Id := Last  (Statements (HSS));
504
505                Push : constant Node_Id := Make_Push_Label (Sloc (F));
506                Pop  : constant Node_Id := Make_Pop_Label  (Sloc (L));
507
508             begin
509                --  We make sure that a call to Get_Local_Raise_Call_Entity is
510                --  made during front end processing, so that when we need it
511                --  in the back end, it will already be available and loaded.
512
513                Discard_Node (Get_Local_Raise_Call_Entity);
514
515                --  Prepare and insert Push and Pop nodes
516
517                Set_Exception_Label (Push, Exception_Label (H));
518                Insert_Before (F, Push);
519                Set_Analyzed (Push);
520
521                Insert_After (L, Pop);
522                Set_Analyzed (Pop);
523             end;
524          end Generate_Push_Pop;
525
526          --  Local declarations
527
528          Loc    : constant Source_Ptr := Sloc (HSS);
529          Stmts  : List_Id := No_List;
530          Choice : Node_Id;
531          Excep  : Entity_Id;
532
533          procedure Generate_Push_Pop_For_Constraint_Error is
534            new Generate_Push_Pop
535              (Exc_Locally_Handled => CE_Locally_Handled,
536               Make_Push_Label     => Make_Push_Constraint_Error_Label,
537               Make_Pop_Label      => Make_Pop_Constraint_Error_Label);
538          --  If no Push/Pop has been generated for CE yet, then set the flag
539          --  CE_Locally_Handled, allocate an Exception_Label for handler H (if
540          --  not already done), and generate Push/Pop nodes for the exception
541          --  label at the start and end of the statements of HSS.
542
543          procedure Generate_Push_Pop_For_Program_Error is
544            new Generate_Push_Pop
545              (Exc_Locally_Handled => PE_Locally_Handled,
546               Make_Push_Label     => Make_Push_Program_Error_Label,
547               Make_Pop_Label      => Make_Pop_Program_Error_Label);
548          --  If no Push/Pop has been generated for PE yet, then set the flag
549          --  PE_Locally_Handled, allocate an Exception_Label for handler H (if
550          --  not already done), and generate Push/Pop nodes for the exception
551          --  label at the start and end of the statements of HSS.
552
553          procedure Generate_Push_Pop_For_Storage_Error is
554            new Generate_Push_Pop
555              (Exc_Locally_Handled => SE_Locally_Handled,
556               Make_Push_Label     => Make_Push_Storage_Error_Label,
557               Make_Pop_Label      => Make_Pop_Storage_Error_Label);
558          --  If no Push/Pop has been generated for SE yet, then set the flag
559          --  SE_Locally_Handled, allocate an Exception_Label for handler H (if
560          --  not already done), and generate Push/Pop nodes for the exception
561          --  label at the start and end of the statements of HSS.
562
563       --  Start of processing for Expand_Local_Exception_Handlers
564
565       begin
566          --  No processing if all exception handlers will get removed
567
568          if Debug_Flag_Dot_X then
569             return;
570          end if;
571
572          --  See for each handler if we have any local raises to expand
573
574          Handler := First_Non_Pragma (Handlrs);
575          while Present (Handler) loop
576
577             --  Note, we do not test Local_Raise_Not_OK here, because in the
578             --  case of Push/Pop generation we want to generate push with a
579             --  null label. The Add_Exception_Label routine has no effect if
580             --  Local_Raise_Not_OK is set, so this works as required.
581
582             if Present (Local_Raise_Statements (Handler)) then
583                Add_Exception_Label (Handler);
584             end if;
585
586             --  If we are doing local raise to goto optimization (restriction
587             --  No_Exception_Propagation set or debug flag .g set), then check
588             --  to see if handler handles CE, PE, SE and if so generate the
589             --  appropriate push/pop sequence for the back end.
590
591             if (Debug_Flag_Dot_G
592                  or else Restriction_Active (No_Exception_Propagation))
593               and then Has_Local_Raise (Handler)
594             then
595                Choice := First (Exception_Choices (Handler));
596                while Present (Choice) loop
597                   if Nkind (Choice) = N_Others_Choice
598                     and then not All_Others (Choice)
599                   then
600                      Generate_Push_Pop_For_Constraint_Error (Handler);
601                      Generate_Push_Pop_For_Program_Error    (Handler);
602                      Generate_Push_Pop_For_Storage_Error    (Handler);
603
604                   elsif Is_Entity_Name (Choice) then
605                      Excep := Get_Renamed_Entity (Entity (Choice));
606
607                      if Excep = Standard_Constraint_Error then
608                         Generate_Push_Pop_For_Constraint_Error (Handler);
609                      elsif Excep = Standard_Program_Error then
610                         Generate_Push_Pop_For_Program_Error    (Handler);
611                      elsif Excep = Standard_Storage_Error then
612                         Generate_Push_Pop_For_Storage_Error    (Handler);
613                      end if;
614                   end if;
615
616                   Next (Choice);
617                end loop;
618             end if;
619
620             Next_Non_Pragma (Handler);
621          end loop;
622
623          --  Nothing to do if no handlers requiring the goto transformation
624
625          if not (Local_Expansion_Required) then
626             return;
627          end if;
628
629          --  Prepare to do the transformation
630
631          declare
632             --  L3 is the label to exit the HSS
633
634             L3_Dent : constant Entity_Id :=
635                         Make_Defining_Identifier (Loc,
636                           Chars => New_Internal_Name ('L'));
637
638             Labl_L3 : constant Node_Id :=
639                         Make_Label (Loc,
640                           Identifier => New_Occurrence_Of (L3_Dent, Loc));
641
642             Blk_Stm : Node_Id;
643             Relmt   : Elmt_Id;
644
645          begin
646             Set_Exception_Junk (Labl_L3);
647             Add_Label_Declaration (L3_Dent);
648
649             --  Wrap existing statements and handlers in an inner block
650
651             Blk_Stm :=
652               Make_Block_Statement (Loc,
653                 Handled_Statement_Sequence => Relocate_Node (HSS));
654             Set_Exception_Junk (Blk_Stm);
655
656             Rewrite (HSS,
657               Make_Handled_Sequence_Of_Statements (Loc,
658                 Statements => New_List (Blk_Stm)));
659
660             --  Set block statement as analyzed, we don't want to actually call
661             --  Analyze on this block, it would cause a recursion in exception
662             --  handler processing which would mess things up.
663
664             Set_Analyzed (Blk_Stm);
665
666             --  Now loop through the exception handlers to deal with those that
667             --  are targets of local raise statements.
668
669             Handler := First_Non_Pragma (Handlrs);
670             while Present (Handler) loop
671                if Present (Exception_Label (Handler)) then
672
673                   --  This handler needs the goto expansion
674
675                   declare
676                      Loc : constant Source_Ptr := Sloc (Handler);
677
678                      --  L1 is the start label for this handler
679
680                      L1_Dent : constant Entity_Id := Exception_Label (Handler);
681
682                      Labl_L1 : constant Node_Id :=
683                                  Make_Label (Loc,
684                                    Identifier =>
685                                      New_Occurrence_Of (L1_Dent, Loc));
686
687                      --  Jump to L1 to be used as replacement for the original
688                      --  handler (used in the case where exception propagation
689                      --  may still occur).
690
691                      Name_L1 : constant Node_Id :=
692                                  New_Occurrence_Of (L1_Dent, Loc);
693
694                      Goto_L1 : constant Node_Id :=
695                                  Make_Goto_Statement (Loc,
696                                    Name => Name_L1);
697
698                      --  Jump to L3 to be used at the end of handler
699
700                      Name_L3 : constant Node_Id :=
701                                  New_Occurrence_Of (L3_Dent, Loc);
702
703                      Goto_L3 : constant Node_Id :=
704                                  Make_Goto_Statement (Loc,
705                                    Name => Name_L3);
706
707                      H_Stmts : constant List_Id := Statements (Handler);
708
709                   begin
710                      Set_Exception_Junk (Labl_L1);
711                      Set_Exception_Junk (Goto_L3);
712
713                      --  Note: we do NOT set Exception_Junk in Goto_L1, since
714                      --  this is a real transfer of control that we want the
715                      --  Sem_Ch6.Check_Returns procedure to recognize properly.
716
717                      --  Replace handler by a goto L1. We can mark this as
718                      --  analyzed since it is fully formed, and we don't
719                      --  want it going through any further checks. We save
720                      --  the last statement location in the goto L1 node for
721                      --  the benefit of Sem_Ch6.Check_Returns.
722
723                      Set_Statements (Handler, New_List (Goto_L1));
724                      Set_Analyzed (Goto_L1);
725                      Set_Etype (Name_L1, Standard_Void_Type);
726
727                      --  Now replace all the raise statements by goto L1
728
729                      if Present (Local_Raise_Statements (Handler)) then
730                         Relmt := First_Elmt (Local_Raise_Statements (Handler));
731                         while Present (Relmt) loop
732                            declare
733                               Raise_S : constant Node_Id := Node (Relmt);
734
735                               Name_L1 : constant Node_Id :=
736                                           New_Occurrence_Of (L1_Dent, Loc);
737
738                               Goto_L1 : constant Node_Id :=
739                                           Make_Goto_Statement (Loc,
740                                             Name => Name_L1);
741
742                            begin
743                               --  Replace raise by goto L1
744
745                               Set_Analyzed (Goto_L1);
746                               Set_Etype (Name_L1, Standard_Void_Type);
747                               Replace_Raise_By_Goto (Raise_S, Goto_L1);
748                            end;
749
750                            Next_Elmt (Relmt);
751                         end loop;
752                      end if;
753
754                      --  Add a goto L3 at end of statement list in block. The
755                      --  first time, this is what skips over the exception
756                      --  handlers in the normal case. Subsequent times, it
757                      --  terminates the execution of the previous handler code,
758                      --  and skips subsequent handlers.
759
760                      Stmts := Statements (HSS);
761
762                      Insert_After (Last (Stmts), Goto_L3);
763                      Set_Analyzed (Goto_L3);
764                      Set_Etype (Name_L3, Standard_Void_Type);
765
766                      --  Now we drop the label that marks the handler start,
767                      --  followed by the statements of the handler.
768
769                      Set_Etype (Identifier (Labl_L1), Standard_Void_Type);
770
771                      Insert_After_And_Analyze (Last (Stmts), Labl_L1);
772
773                      declare
774                         Loc : constant Source_Ptr := Sloc (First (H_Stmts));
775                         Blk : constant Node_Id :=
776                                 Make_Block_Statement (Loc,
777                                   Handled_Statement_Sequence =>
778                                     Make_Handled_Sequence_Of_Statements (Loc,
779                                       Statements => H_Stmts));
780                      begin
781                         Set_Exception_Junk (Blk);
782                         Insert_After_And_Analyze (Last (Stmts), Blk);
783                      end;
784                   end;
785
786                   --  Here if we have local raise statements but the handler is
787                   --  not suitable for processing with a local raise. In this
788                   --  case we have to generate possible diagnostics.
789
790                elsif Has_Local_Raise (Handler)
791                  and then Local_Raise_Statements (Handler) /= No_Elist
792                then
793                   Relmt := First_Elmt (Local_Raise_Statements (Handler));
794                   while Present (Relmt) loop
795                      Warn_If_No_Propagation (Node (Relmt));
796                      Next_Elmt (Relmt);
797                   end loop;
798                end if;
799
800                Next (Handler);
801             end loop;
802
803             --  Only remaining step is to drop the L3 label and we are done
804
805             Set_Etype (Identifier (Labl_L3), Standard_Void_Type);
806
807             --  If we had at least one handler, then we drop the label after
808             --  the last statement of that handler.
809
810             if Stmts /= No_List then
811                Insert_After_And_Analyze (Last (Stmts), Labl_L3);
812
813             --  Otherwise we have removed all the handlers (this results from
814             --  use of pragma Restrictions (No_Exception_Propagation), and we
815             --  drop the label at the end of the statements of the HSS.
816
817             else
818                Insert_After_And_Analyze (Last (Statements (HSS)), Labl_L3);
819             end if;
820
821             return;
822          end;
823       end Expand_Local_Exception_Handlers;
824
825       -----------------------------
826       -- Prepend_Call_To_Handler --
827       -----------------------------
828
829       procedure Prepend_Call_To_Handler
830         (Proc : RE_Id;
831          Args : List_Id := No_List)
832       is
833          Ent : constant Entity_Id := RTE (Proc);
834
835       begin
836          --  If we have no Entity, then we are probably in no run time mode
837          --  or some weird error has occured. In either case do do nothing!
838
839          if Present (Ent) then
840             declare
841                Call : constant Node_Id :=
842                         Make_Procedure_Call_Statement (Loc,
843                           Name => New_Occurrence_Of (RTE (Proc), Loc),
844                           Parameter_Associations => Args);
845
846             begin
847                Prepend_To (Statements (Handler), Call);
848                Analyze (Call, Suppress => All_Checks);
849             end;
850          end if;
851       end Prepend_Call_To_Handler;
852
853       ---------------------------
854       -- Replace_Raise_By_Goto --
855       ---------------------------
856
857       procedure Replace_Raise_By_Goto (Raise_S : Node_Id; Goto_L1 : Node_Id) is
858          Loc   : constant Source_Ptr := Sloc (Raise_S);
859          Excep : Entity_Id;
860          LR    : Node_Id;
861          Cond  : Node_Id;
862          Orig  : Node_Id;
863
864       begin
865          --  If we have a null statement, it means that there is no replacement
866          --  needed (typically this results from a suppressed check).
867
868          if Nkind (Raise_S) = N_Null_Statement then
869             return;
870
871          --  Test for Raise_xxx_Error
872
873          elsif Nkind (Raise_S) = N_Raise_Constraint_Error then
874             Excep := Standard_Constraint_Error;
875             Cond  := Condition (Raise_S);
876
877          elsif Nkind (Raise_S) = N_Raise_Storage_Error then
878             Excep := Standard_Storage_Error;
879             Cond := Condition (Raise_S);
880
881          elsif Nkind (Raise_S) = N_Raise_Program_Error then
882             Excep := Standard_Program_Error;
883             Cond := Condition (Raise_S);
884
885             --  The only other possibility is a node that is or used to be a
886             --  simple raise statement.
887
888          else
889             Orig := Original_Node (Raise_S);
890             pragma Assert (Nkind (Orig) = N_Raise_Statement
891                              and then Present (Name (Orig))
892                              and then No (Expression (Orig)));
893             Excep := Entity (Name (Orig));
894             Cond := Empty;
895          end if;
896
897          --  Here Excep is the exception to raise, and Cond is the condition
898          --  First prepare the call to Local_Raise (excep'address).
899
900          if RTE_Available (RE_Local_Raise) then
901             LR :=
902               Make_Procedure_Call_Statement (Loc,
903                 Name => New_Occurrence_Of (RTE (RE_Local_Raise), Loc),
904                 Parameter_Associations => New_List (
905                   Unchecked_Convert_To (RTE (RE_Address),
906                     Make_Attribute_Reference (Loc,
907                       Prefix         => New_Occurrence_Of (Excep, Loc),
908                       Attribute_Name => Name_Identity))));
909
910             --  Use null statement if Local_Raise not available
911
912          else
913             LR :=
914               Make_Null_Statement (Loc);
915          end if;
916
917          --  If there is no condition, we rewrite as
918
919          --    begin
920          --       Local_Raise (excep'Identity);
921          --       goto L1;
922          --    end;
923
924          if No (Cond) then
925             Rewrite (Raise_S,
926               Make_Block_Statement (Loc,
927                 Handled_Statement_Sequence =>
928                   Make_Handled_Sequence_Of_Statements (Loc,
929                     Statements => New_List (LR, Goto_L1))));
930             Set_Exception_Junk (Raise_S);
931
932          --  If there is a condition, we rewrite as
933
934          --    if condition then
935          --       Local_Raise (excep'Identity);
936          --       goto L1;
937          --    end if;
938
939          else
940             Rewrite (Raise_S,
941               Make_If_Statement (Loc,
942                 Condition       => Cond,
943                 Then_Statements => New_List (LR, Goto_L1)));
944          end if;
945
946          Analyze (Raise_S);
947       end Replace_Raise_By_Goto;
948
949    --  Start of processing for Expand_Exception_Handlers
950
951    begin
952       Expand_Local_Exception_Handlers;
953
954       --  Loop through handlers
955
956       Handler := First_Non_Pragma (Handlrs);
957       Handler_Loop : while Present (Handler) loop
958          Next_Handler := Next_Non_Pragma (Handler);
959
960          --  Remove source handler if gnat debug flag N is set
961
962          if Debug_Flag_Dot_X and then Comes_From_Source (Handler) then
963             Remove (Handler);
964
965          --  Remove handler if no exception propagation, generating a warning
966          --  if a source generated handler was not the target of a local raise.
967
968          elsif Restriction_Active (No_Exception_Propagation) then
969             if not Has_Local_Raise (Handler)
970               and then Comes_From_Source (Handler)
971               and then Warn_On_Non_Local_Exception
972             then
973                Warn_No_Exception_Propagation_Active (Handler);
974                Error_Msg_N
975                  ("\?this handler can never be entered, and has been removed",
976                   Handler);
977             end if;
978
979             Remove (Handler);
980
981          --  Exception handler is active and retained and must be processed
982
983          else
984             --  If an exception occurrence is present, then we must declare it
985             --  and initialize it from the value stored in the TSD
986
987             --     declare
988             --        name : Exception_Occurrence;
989             --     begin
990             --        Save_Occurrence (name, Get_Current_Excep.all)
991             --        ...
992             --     end;
993
994             if Present (Choice_Parameter (Handler)) then
995                declare
996                   Cparm : constant Entity_Id  := Choice_Parameter (Handler);
997                   Clc   : constant Source_Ptr := Sloc (Cparm);
998                   Save  : Node_Id;
999
1000                begin
1001                   Save :=
1002                     Make_Procedure_Call_Statement (Loc,
1003                       Name =>
1004                         New_Occurrence_Of (RTE (RE_Save_Occurrence), Loc),
1005                       Parameter_Associations => New_List (
1006                         New_Occurrence_Of (Cparm, Clc),
1007                         Make_Explicit_Dereference (Loc,
1008                           Make_Function_Call (Loc,
1009                             Name => Make_Explicit_Dereference (Loc,
1010                               New_Occurrence_Of
1011                                 (RTE (RE_Get_Current_Excep), Loc))))));
1012
1013                   Mark_Rewrite_Insertion (Save);
1014                   Prepend (Save, Statements (Handler));
1015
1016                   Obj_Decl :=
1017                     Make_Object_Declaration
1018                       (Clc,
1019                        Defining_Identifier => Cparm,
1020                        Object_Definition   =>
1021                          New_Occurrence_Of
1022                            (RTE (RE_Exception_Occurrence), Clc));
1023                   Set_No_Initialization (Obj_Decl, True);
1024
1025                   Rewrite (Handler,
1026                     Make_Implicit_Exception_Handler (Loc,
1027                       Exception_Choices => Exception_Choices (Handler),
1028
1029                       Statements => New_List (
1030                         Make_Block_Statement (Loc,
1031                           Declarations => New_List (Obj_Decl),
1032                           Handled_Statement_Sequence =>
1033                             Make_Handled_Sequence_Of_Statements (Loc,
1034                               Statements => Statements (Handler))))));
1035
1036                   Analyze_List (Statements (Handler), Suppress => All_Checks);
1037                end;
1038             end if;
1039
1040             --  The processing at this point is rather different for the JVM
1041             --  case, so we completely separate the processing.
1042
1043             --  For the JVM case, we unconditionally call Update_Exception,
1044             --  passing a call to the intrinsic Current_Target_Exception (see
1045             --  JVM version of Ada.Exceptions in 4jexcept.adb for details).
1046
1047             if VM_Target /= No_VM then
1048                declare
1049                   Arg : constant Node_Id :=
1050                           Make_Function_Call (Loc,
1051                             Name =>
1052                               New_Occurrence_Of
1053                                 (RTE (RE_Current_Target_Exception), Loc));
1054                begin
1055                   Prepend_Call_To_Handler
1056                     (RE_Update_Exception, New_List (Arg));
1057                end;
1058
1059                --  For the normal case, we have to worry about the state of
1060                --  abort deferral. Generally, we defer abort during runtime
1061                --  handling of exceptions. When control is passed to the
1062                --  handler, then in the normal case we undefer aborts. In any
1063                --  case this entire handling is relevant only if aborts are
1064                --  allowed!
1065
1066             elsif Abort_Allowed then
1067
1068                --  There are some special cases in which we do not do the
1069                --  undefer. In particular a finalization (AT END) handler
1070                --  wants to operate with aborts still deferred.
1071
1072                --  We also suppress the call if this is the special handler
1073                --  for Abort_Signal, since if we are aborting, we want to keep
1074                --  aborts deferred (one abort is enough).
1075
1076                --  If abort really needs to be deferred the expander must add
1077                --  this call explicitly, see Expand_N_Asynchronous_Select.
1078
1079                Others_Choice :=
1080                  Nkind (First (Exception_Choices (Handler))) = N_Others_Choice;
1081
1082                if (Others_Choice
1083                    or else Entity (First (Exception_Choices (Handler))) /=
1084                      Stand.Abort_Signal)
1085                  and then not
1086                    (Others_Choice
1087                     and then All_Others (First (Exception_Choices (Handler))))
1088                  and then Abort_Allowed
1089                then
1090                   Prepend_Call_To_Handler (RE_Abort_Undefer);
1091                end if;
1092             end if;
1093          end if;
1094
1095          Handler := Next_Handler;
1096       end loop Handler_Loop;
1097
1098       --  If all handlers got removed, then remove the list. Note we cannot
1099       --  reference HSS here, since expanding local handlers may have buried
1100       --  the handlers in an inner block.
1101
1102       if Is_Empty_List (Handlrs) then
1103          Set_Exception_Handlers (Parent (Handlrs), No_List);
1104       end if;
1105    end Expand_Exception_Handlers;
1106
1107    ------------------------------------
1108    -- Expand_N_Exception_Declaration --
1109    ------------------------------------
1110
1111    --  Generates:
1112    --     exceptE : constant String := "A.B.EXCEP";   -- static data
1113    --     except : exception_data :=  (
1114    --                    Handled_By_Other => False,
1115    --                    Lang             => 'A',
1116    --                    Name_Length      => exceptE'Length,
1117    --                    Full_Name        => exceptE'Address,
1118    --                    HTable_Ptr       => null,
1119    --                    Import_Code      => 0,
1120    --                    Raise_Hook       => null,
1121    --                    );
1122
1123    --  (protecting test only needed if not at library level)
1124    --
1125    --     exceptF : Boolean := True --  static data
1126    --     if exceptF then
1127    --        exceptF := False;
1128    --        Register_Exception (except'Unchecked_Access);
1129    --     end if;
1130
1131    procedure Expand_N_Exception_Declaration (N : Node_Id) is
1132       Loc     : constant Source_Ptr := Sloc (N);
1133       Id      : constant Entity_Id  := Defining_Identifier (N);
1134       L       : List_Id             := New_List;
1135       Flag_Id : Entity_Id;
1136
1137       Name_Exname : constant Name_Id := New_External_Name (Chars (Id), 'E');
1138       Exname      : constant Node_Id :=
1139                       Make_Defining_Identifier (Loc, Name_Exname);
1140
1141    begin
1142       --  There is no expansion needed when compiling for the JVM since the
1143       --  JVM has a built-in exception mechanism. See 4jexcept.ads for details.
1144
1145       if VM_Target /= No_VM then
1146          return;
1147       end if;
1148
1149       --  Definition of the external name: nam : constant String := "A.B.NAME";
1150
1151       Insert_Action (N,
1152         Make_Object_Declaration (Loc,
1153           Defining_Identifier => Exname,
1154           Constant_Present    => True,
1155           Object_Definition   => New_Occurrence_Of (Standard_String, Loc),
1156           Expression => Make_String_Literal (Loc, Full_Qualified_Name (Id))));
1157
1158       Set_Is_Statically_Allocated (Exname);
1159
1160       --  Create the aggregate list for type Standard.Exception_Type:
1161       --  Handled_By_Other component: False
1162
1163       Append_To (L, New_Occurrence_Of (Standard_False, Loc));
1164
1165       --  Lang component: 'A'
1166
1167       Append_To (L,
1168         Make_Character_Literal (Loc,
1169           Chars              =>  Name_uA,
1170           Char_Literal_Value =>  UI_From_Int (Character'Pos ('A'))));
1171
1172       --  Name_Length component: Nam'Length
1173
1174       Append_To (L,
1175         Make_Attribute_Reference (Loc,
1176           Prefix         => New_Occurrence_Of (Exname, Loc),
1177           Attribute_Name => Name_Length));
1178
1179       --  Full_Name component: Standard.A_Char!(Nam'Address)
1180
1181       Append_To (L, Unchecked_Convert_To (Standard_A_Char,
1182         Make_Attribute_Reference (Loc,
1183           Prefix         => New_Occurrence_Of (Exname, Loc),
1184           Attribute_Name => Name_Address)));
1185
1186       --  HTable_Ptr component: null
1187
1188       Append_To (L, Make_Null (Loc));
1189
1190       --  Import_Code component: 0
1191
1192       Append_To (L, Make_Integer_Literal (Loc, 0));
1193
1194       --  Raise_Hook component: null
1195
1196       Append_To (L, Make_Null (Loc));
1197
1198       Set_Expression (N, Make_Aggregate (Loc, Expressions => L));
1199       Analyze_And_Resolve (Expression (N), Etype (Id));
1200
1201       --  Register_Exception (except'Unchecked_Access);
1202
1203       if not No_Exception_Handlers_Set
1204         and then not Restriction_Active (No_Exception_Registration)
1205       then
1206          L := New_List (
1207                 Make_Procedure_Call_Statement (Loc,
1208                   Name => New_Occurrence_Of (RTE (RE_Register_Exception), Loc),
1209                   Parameter_Associations => New_List (
1210                     Unchecked_Convert_To (RTE (RE_Exception_Data_Ptr),
1211                       Make_Attribute_Reference (Loc,
1212                         Prefix         => New_Occurrence_Of (Id, Loc),
1213                         Attribute_Name => Name_Unrestricted_Access)))));
1214
1215          Set_Register_Exception_Call (Id, First (L));
1216
1217          if not Is_Library_Level_Entity (Id) then
1218             Flag_Id :=  Make_Defining_Identifier (Loc,
1219                           New_External_Name (Chars (Id), 'F'));
1220
1221             Insert_Action (N,
1222               Make_Object_Declaration (Loc,
1223                 Defining_Identifier => Flag_Id,
1224                 Object_Definition   =>
1225                   New_Occurrence_Of (Standard_Boolean, Loc),
1226                 Expression          =>
1227                   New_Occurrence_Of (Standard_True, Loc)));
1228
1229             Set_Is_Statically_Allocated (Flag_Id);
1230
1231             Append_To (L,
1232               Make_Assignment_Statement (Loc,
1233                 Name       => New_Occurrence_Of (Flag_Id, Loc),
1234                 Expression => New_Occurrence_Of (Standard_False, Loc)));
1235
1236             Insert_After_And_Analyze (N,
1237               Make_Implicit_If_Statement (N,
1238                 Condition       => New_Occurrence_Of (Flag_Id, Loc),
1239                 Then_Statements => L));
1240
1241          else
1242             Insert_List_After_And_Analyze (N, L);
1243          end if;
1244       end if;
1245
1246    end Expand_N_Exception_Declaration;
1247
1248    ---------------------------------------------
1249    -- Expand_N_Handled_Sequence_Of_Statements --
1250    ---------------------------------------------
1251
1252    procedure Expand_N_Handled_Sequence_Of_Statements (N : Node_Id) is
1253    begin
1254       --  Expand exception handlers
1255
1256       if Present (Exception_Handlers (N))
1257         and then not Restriction_Active (No_Exception_Handlers)
1258       then
1259          Expand_Exception_Handlers (N);
1260       end if;
1261
1262       --  If local exceptions are being expanded, the previous call will
1263       --  have rewritten the construct as a block and reanalyzed it. No
1264       --  further expansion is needed.
1265
1266       if Analyzed (N) then
1267          return;
1268       end if;
1269
1270       --  Add clean up actions if required
1271
1272       if Nkind (Parent (N)) /= N_Package_Body
1273         and then Nkind (Parent (N)) /= N_Accept_Statement
1274         and then Nkind (Parent (N)) /= N_Extended_Return_Statement
1275         and then not Delay_Cleanups (Current_Scope)
1276       then
1277          Expand_Cleanup_Actions (Parent (N));
1278       else
1279          Set_First_Real_Statement (N, First (Statements (N)));
1280       end if;
1281    end Expand_N_Handled_Sequence_Of_Statements;
1282
1283    -------------------------------------
1284    -- Expand_N_Raise_Constraint_Error --
1285    -------------------------------------
1286
1287    procedure Expand_N_Raise_Constraint_Error (N : Node_Id) is
1288    begin
1289       --  We adjust the condition to deal with the C/Fortran boolean case. This
1290       --  may well not be necessary, as all such conditions are generated by
1291       --  the expander and probably are all standard boolean, but who knows
1292       --  what strange optimization in future may require this adjustment!
1293
1294       Adjust_Condition (Condition (N));
1295
1296       --  Now deal with possible local raise handling
1297
1298       Possible_Local_Raise (N, Standard_Constraint_Error);
1299    end Expand_N_Raise_Constraint_Error;
1300
1301    ----------------------------------
1302    -- Expand_N_Raise_Program_Error --
1303    ----------------------------------
1304
1305    procedure Expand_N_Raise_Program_Error (N : Node_Id) is
1306    begin
1307       --  We adjust the condition to deal with the C/Fortran boolean case. This
1308       --  may well not be necessary, as all such conditions are generated by
1309       --  the expander and probably are all standard boolean, but who knows
1310       --  what strange optimization in future may require this adjustment!
1311
1312       Adjust_Condition (Condition (N));
1313
1314       --  Now deal with possible local raise handling
1315
1316       Possible_Local_Raise (N, Standard_Program_Error);
1317    end Expand_N_Raise_Program_Error;
1318
1319    ------------------------------
1320    -- Expand_N_Raise_Statement --
1321    ------------------------------
1322
1323    procedure Expand_N_Raise_Statement (N : Node_Id) is
1324       Loc   : constant Source_Ptr := Sloc (N);
1325       Ehand : Node_Id;
1326       E     : Entity_Id;
1327       Str   : String_Id;
1328       H     : Node_Id;
1329
1330    begin
1331       --  Debug_Flag_Dot_G := True;
1332
1333       --  Processing for locally handled exception (exclude reraise case)
1334
1335       if Present (Name (N)) and then Nkind (Name (N)) = N_Identifier then
1336          if Debug_Flag_Dot_G
1337            or else Restriction_Active (No_Exception_Propagation)
1338          then
1339             --  If we have a local handler, then note that this is potentially
1340             --  able to be transformed into a goto statement.
1341
1342             H := Find_Local_Handler (Entity (Name (N)), N);
1343
1344             if Present (H) then
1345                if Local_Raise_Statements (H) = No_Elist then
1346                   Set_Local_Raise_Statements (H, New_Elmt_List);
1347                end if;
1348
1349                --  Append the new entry if it is not there already. Sometimes
1350                --  we have situations where due to reexpansion, the same node
1351                --  is analyzed twice and would otherwise be added twice.
1352
1353                Append_Unique_Elmt (N, Local_Raise_Statements (H));
1354                Set_Has_Local_Raise (H);
1355
1356             --  If no local handler, then generate no propagation warning
1357
1358             else
1359                Warn_If_No_Propagation (N);
1360             end if;
1361
1362          end if;
1363       end if;
1364
1365       --  If a string expression is present, then the raise statement is
1366       --  converted to a call:
1367
1368       --     Raise_Exception (exception-name'Identity, string);
1369
1370       --  and there is nothing else to do
1371
1372       if Present (Expression (N)) then
1373          Rewrite (N,
1374            Make_Procedure_Call_Statement (Loc,
1375              Name => New_Occurrence_Of (RTE (RE_Raise_Exception), Loc),
1376              Parameter_Associations => New_List (
1377                Make_Attribute_Reference (Loc,
1378                  Prefix => Name (N),
1379                  Attribute_Name => Name_Identity),
1380                Expression (N))));
1381          Analyze (N);
1382          return;
1383       end if;
1384
1385       --  Remaining processing is for the case where no string expression
1386       --  is present.
1387
1388       --  There is no expansion needed for statement "raise <exception>;" when
1389       --  compiling for the JVM since the JVM has a built-in exception
1390       --  mechanism. However we need to keep the expansion for "raise;"
1391       --  statements. See 4jexcept.ads for details.
1392
1393       if Present (Name (N)) and then VM_Target /= No_VM then
1394          return;
1395       end if;
1396
1397       --  Don't expand a raise statement that does not come from source
1398       --  if we have already had configurable run-time violations, since
1399       --  most likely it will be junk cascaded nonsense.
1400
1401       if Configurable_Run_Time_Violations > 0
1402         and then not Comes_From_Source (N)
1403       then
1404          return;
1405       end if;
1406
1407       --  Convert explicit raise of Program_Error, Constraint_Error, and
1408       --  Storage_Error into the corresponding raise (in High_Integrity_Mode
1409       --  all other raises will get normal expansion and be disallowed,
1410       --  but this is also faster in all modes).
1411
1412       if Present (Name (N)) and then Nkind (Name (N)) = N_Identifier then
1413          if Entity (Name (N)) = Standard_Constraint_Error then
1414             Rewrite (N,
1415               Make_Raise_Constraint_Error (Loc,
1416                 Reason => CE_Explicit_Raise));
1417             Analyze (N);
1418             return;
1419
1420          elsif Entity (Name (N)) = Standard_Program_Error then
1421             Rewrite (N,
1422               Make_Raise_Program_Error (Loc,
1423                 Reason => PE_Explicit_Raise));
1424             Analyze (N);
1425             return;
1426
1427          elsif Entity (Name (N)) = Standard_Storage_Error then
1428             Rewrite (N,
1429               Make_Raise_Storage_Error (Loc,
1430                 Reason => SE_Explicit_Raise));
1431             Analyze (N);
1432             return;
1433          end if;
1434       end if;
1435
1436       --  Case of name present, in this case we expand raise name to
1437
1438       --    Raise_Exception (name'Identity, location_string);
1439
1440       --  where location_string identifies the file/line of the raise
1441
1442       if Present (Name (N)) then
1443          declare
1444             Id : Entity_Id := Entity (Name (N));
1445
1446          begin
1447             Build_Location_String (Loc);
1448
1449             --  If the exception is a renaming, use the exception that it
1450             --  renames (which might be a predefined exception, e.g.).
1451
1452             if Present (Renamed_Object (Id)) then
1453                Id := Renamed_Object (Id);
1454             end if;
1455
1456             --  Build a C-compatible string in case of no exception handlers,
1457             --  since this is what the last chance handler is expecting.
1458
1459             if No_Exception_Handlers_Set then
1460
1461                --  Generate an empty message if configuration pragma
1462                --  Suppress_Exception_Locations is set for this unit.
1463
1464                if Opt.Exception_Locations_Suppressed then
1465                   Name_Len := 1;
1466                else
1467                   Name_Len := Name_Len + 1;
1468                end if;
1469
1470                Name_Buffer (Name_Len) := ASCII.NUL;
1471             end if;
1472
1473             if Opt.Exception_Locations_Suppressed then
1474                Name_Len := 0;
1475             end if;
1476
1477             Str := String_From_Name_Buffer;
1478
1479             --  For VMS exceptions, convert the raise into a call to
1480             --  lib$stop so it will be handled by __gnat_error_handler.
1481
1482             if Is_VMS_Exception (Id) then
1483                declare
1484                   Excep_Image : String_Id;
1485                   Cond        : Node_Id;
1486
1487                begin
1488                   if Present (Interface_Name (Id)) then
1489                      Excep_Image := Strval (Interface_Name (Id));
1490                   else
1491                      Get_Name_String (Chars (Id));
1492                      Set_All_Upper_Case;
1493                      Excep_Image := String_From_Name_Buffer;
1494                   end if;
1495
1496                   if Exception_Code (Id) /= No_Uint then
1497                      Cond :=
1498                        Make_Integer_Literal (Loc, Exception_Code (Id));
1499                   else
1500                      Cond :=
1501                        Unchecked_Convert_To (Standard_Integer,
1502                          Make_Function_Call (Loc,
1503                            Name => New_Occurrence_Of
1504                              (RTE (RE_Import_Value), Loc),
1505                            Parameter_Associations => New_List
1506                              (Make_String_Literal (Loc,
1507                                Strval => Excep_Image))));
1508                   end if;
1509
1510                   Rewrite (N,
1511                     Make_Procedure_Call_Statement (Loc,
1512                       Name =>
1513                         New_Occurrence_Of (RTE (RE_Lib_Stop), Loc),
1514                       Parameter_Associations => New_List (Cond)));
1515                         Analyze_And_Resolve (Cond, Standard_Integer);
1516                end;
1517
1518             --  Not VMS exception case, convert raise to call to the
1519             --  Raise_Exception routine.
1520
1521             else
1522                Rewrite (N,
1523                  Make_Procedure_Call_Statement (Loc,
1524                     Name => New_Occurrence_Of (RTE (RE_Raise_Exception), Loc),
1525                     Parameter_Associations => New_List (
1526                       Make_Attribute_Reference (Loc,
1527                         Prefix => Name (N),
1528                         Attribute_Name => Name_Identity),
1529                       Make_String_Literal (Loc,
1530                         Strval => Str))));
1531             end if;
1532          end;
1533
1534       --  Case of no name present (reraise). We rewrite the raise to:
1535
1536       --    Reraise_Occurrence_Always (EO);
1537
1538       --  where EO is the current exception occurrence. If the current handler
1539       --  does not have a choice parameter specification, then we provide one.
1540
1541       else
1542          --  Find innermost enclosing exception handler (there must be one,
1543          --  since the semantics has already verified that this raise statement
1544          --  is valid, and a raise with no arguments is only permitted in the
1545          --  context of an exception handler.
1546
1547          Ehand := Parent (N);
1548          while Nkind (Ehand) /= N_Exception_Handler loop
1549             Ehand := Parent (Ehand);
1550          end loop;
1551
1552          --  Make exception choice parameter if none present. Note that we do
1553          --  not need to put the entity on the entity chain, since no one will
1554          --  be referencing this entity by normal visibility methods.
1555
1556          if No (Choice_Parameter (Ehand)) then
1557             E := Make_Defining_Identifier (Loc, New_Internal_Name ('E'));
1558             Set_Choice_Parameter (Ehand, E);
1559             Set_Ekind (E, E_Variable);
1560             Set_Etype (E, RTE (RE_Exception_Occurrence));
1561             Set_Scope (E, Current_Scope);
1562          end if;
1563
1564          --  Now rewrite the raise as a call to Reraise. A special case arises
1565          --  if this raise statement occurs in the context of a handler for
1566          --  all others (i.e. an at end handler). in this case we avoid
1567          --  the call to defer abort, cleanup routines are expected to be
1568          --  called in this case with aborts deferred.
1569
1570          declare
1571             Ech : constant Node_Id := First (Exception_Choices (Ehand));
1572             Ent : Entity_Id;
1573
1574          begin
1575             if Nkind (Ech) = N_Others_Choice
1576               and then All_Others (Ech)
1577             then
1578                Ent := RTE (RE_Reraise_Occurrence_No_Defer);
1579             else
1580                Ent := RTE (RE_Reraise_Occurrence_Always);
1581             end if;
1582
1583             Rewrite (N,
1584               Make_Procedure_Call_Statement (Loc,
1585                 Name => New_Occurrence_Of (Ent, Loc),
1586                 Parameter_Associations => New_List (
1587                   New_Occurrence_Of (Choice_Parameter (Ehand), Loc))));
1588          end;
1589       end if;
1590
1591       Analyze (N);
1592    end Expand_N_Raise_Statement;
1593
1594    ----------------------------------
1595    -- Expand_N_Raise_Storage_Error --
1596    ----------------------------------
1597
1598    procedure Expand_N_Raise_Storage_Error (N : Node_Id) is
1599    begin
1600       --  We adjust the condition to deal with the C/Fortran boolean case. This
1601       --  may well not be necessary, as all such conditions are generated by
1602       --  the expander and probably are all standard boolean, but who knows
1603       --  what strange optimization in future may require this adjustment!
1604
1605       Adjust_Condition (Condition (N));
1606
1607       --  Now deal with possible local raise handling
1608
1609       Possible_Local_Raise (N, Standard_Storage_Error);
1610    end Expand_N_Raise_Storage_Error;
1611
1612    --------------------------
1613    -- Possible_Local_Raise --
1614    --------------------------
1615
1616    procedure Possible_Local_Raise (N : Node_Id; E : Entity_Id) is
1617    begin
1618       --  Nothing to do if local raise optimization not active
1619
1620       if not Debug_Flag_Dot_G
1621         and then not Restriction_Active (No_Exception_Propagation)
1622       then
1623          return;
1624       end if;
1625
1626       --  Nothing to do if original node was an explicit raise, because in
1627       --  that case, we already generated the required warning for the raise.
1628
1629       if Nkind (Original_Node (N)) = N_Raise_Statement then
1630          return;
1631       end if;
1632
1633       --  Otherwise see if we have a local handler for the exception
1634
1635       declare
1636          H : constant Node_Id := Find_Local_Handler (E, N);
1637
1638       begin
1639          --  If so, mark that it has a local raise
1640
1641          if Present (H) then
1642             Set_Has_Local_Raise (H, True);
1643
1644          --  Otherwise, if the No_Exception_Propagation restriction is active
1645          --  and the warning is enabled, generate the appropriate warnings.
1646
1647          elsif Warn_On_Non_Local_Exception
1648            and then Restriction_Active (No_Exception_Propagation)
1649          then
1650             Warn_No_Exception_Propagation_Active (N);
1651
1652             if Configurable_Run_Time_Mode then
1653                Error_Msg_NE
1654                  ("\?& may call Last_Chance_Handler", N, E);
1655             else
1656                Error_Msg_NE
1657                  ("\?& may result in unhandled exception", N, E);
1658             end if;
1659          end if;
1660       end;
1661    end Possible_Local_Raise;
1662
1663    ------------------------------
1664    -- Expand_N_Subprogram_Info --
1665    ------------------------------
1666
1667    procedure Expand_N_Subprogram_Info (N : Node_Id) is
1668       Loc : constant Source_Ptr := Sloc (N);
1669
1670    begin
1671       --  For now, we replace an Expand_N_Subprogram_Info node with an
1672       --  attribute reference that gives the address of the procedure.
1673       --  This is because gigi does not yet recognize this node, and
1674       --  for the initial targets, this is the right value anyway.
1675
1676       Rewrite (N,
1677         Make_Attribute_Reference (Loc,
1678           Prefix => Identifier (N),
1679           Attribute_Name => Name_Code_Address));
1680
1681       Analyze_And_Resolve (N, RTE (RE_Code_Loc));
1682    end Expand_N_Subprogram_Info;
1683
1684    ------------------------
1685    -- Find_Local_Handler --
1686    ------------------------
1687
1688    function Find_Local_Handler
1689      (Ename : Entity_Id;
1690       Nod   : Node_Id) return Node_Id
1691    is
1692       N : Node_Id;
1693       P : Node_Id;
1694       H : Node_Id;
1695       C : Node_Id;
1696
1697       SSE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
1698       --  This is used to test for wrapped actions below
1699
1700       ERaise  : Entity_Id;
1701       EHandle : Entity_Id;
1702       --  The entity Id's for the exception we are raising and handling, using
1703       --  the renamed exception if a Renamed_Entity is present.
1704
1705    begin
1706       --  Never any local handler if all handlers removed
1707
1708       if Debug_Flag_Dot_X then
1709          return Empty;
1710       end if;
1711
1712       --  Get the exception we are raising, allowing for renaming
1713
1714       ERaise := Get_Renamed_Entity (Ename);
1715
1716       --  We need to check if the node we are looking at is contained in
1717       --
1718
1719       --  Loop to search up the tree
1720
1721       N := Nod;
1722       loop
1723          P := Parent (N);
1724
1725          --  If we get to the top of the tree, or to a subprogram, task, entry,
1726          --  protected body, or accept statement without having found a
1727          --  matching handler, then there is no local handler.
1728
1729          if No (P)
1730            or else Nkind (P) = N_Subprogram_Body
1731            or else Nkind (P) = N_Task_Body
1732            or else Nkind (P) = N_Protected_Body
1733            or else Nkind (P) = N_Entry_Body
1734            or else Nkind (P) = N_Accept_Statement
1735          then
1736             return Empty;
1737
1738             --  Test for handled sequence of statements with at least one
1739             --  exception handler which might be the one we are looking for.
1740
1741          elsif Nkind (P) = N_Handled_Sequence_Of_Statements
1742            and then Present (Exception_Handlers (P))
1743          then
1744             --  Before we proceed we need to check if the node N is covered
1745             --  by the statement part of P rather than one of its exception
1746             --  handlers (an exception handler obviously does not cover its
1747             --  own statements).
1748
1749             --  This test is more delicate than might be thought. It is not
1750             --  just a matter of checking the Statements (P), because the node
1751             --  might be waiting to be wrapped in a transient scope, in which
1752             --  case it will end up in the block statements, even though it
1753             --  is not there now.
1754
1755             if Is_List_Member (N)
1756               and then (List_Containing (N) = Statements (P)
1757                           or else
1758                         List_Containing (N) = SSE.Actions_To_Be_Wrapped_Before
1759                           or else
1760                         List_Containing (N) = SSE.Actions_To_Be_Wrapped_After)
1761             then
1762                --  Loop through exception handlers
1763
1764                H := First (Exception_Handlers (P));
1765                while Present (H) loop
1766
1767                   --  Loop through choices in one handler
1768
1769                   C := First (Exception_Choices (H));
1770                   while Present (C) loop
1771
1772                      --  Deal with others case
1773
1774                      if Nkind (C) = N_Others_Choice then
1775
1776                         --  Matching others handler, but we need to ensure
1777                         --  there is no choice parameter. If there is, then we
1778                         --  don't have a local handler after all (since we do
1779                         --  not allow choice parameters for local handlers).
1780
1781                         if No (Choice_Parameter (H)) then
1782                            return H;
1783                         else
1784                            return Empty;
1785                         end if;
1786
1787                      --  If not others must be entity name
1788
1789                      elsif Nkind (C) /= N_Others_Choice then
1790                         pragma Assert (Is_Entity_Name (C));
1791                         pragma Assert (Present (Entity (C)));
1792
1793                         --  Get exception being handled, dealing with renaming
1794
1795                         EHandle := Get_Renamed_Entity (Entity (C));
1796
1797                         --  If match, then check choice parameter
1798
1799                         if ERaise = EHandle then
1800                            if No (Choice_Parameter (H)) then
1801                               return H;
1802                            else
1803                               return Empty;
1804                            end if;
1805                         end if;
1806                      end if;
1807
1808                      Next (C);
1809                   end loop;
1810
1811                   Next (H);
1812                end loop;
1813             end if;
1814          end if;
1815
1816          N := P;
1817       end loop;
1818    end Find_Local_Handler;
1819
1820    ---------------------------------
1821    -- Get_Local_Raise_Call_Entity --
1822    ---------------------------------
1823
1824    --  Note: this is primary provided for use by the back end in generating
1825    --  calls to Local_Raise. But it would be too late in the back end to call
1826    --  RTE if this actually caused a load/analyze of the unit. So what we do
1827    --  is to ensure there is a dummy call to this function during front end
1828    --  processing so that the unit gets loaded then, and not later.
1829
1830    Local_Raise_Call_Entity     : Entity_Id;
1831    Local_Raise_Call_Entity_Set : Boolean := False;
1832
1833    function Get_Local_Raise_Call_Entity return Entity_Id is
1834    begin
1835       if not Local_Raise_Call_Entity_Set then
1836          Local_Raise_Call_Entity_Set := True;
1837
1838          if RTE_Available (RE_Local_Raise) then
1839             Local_Raise_Call_Entity := RTE (RE_Local_Raise);
1840          else
1841             Local_Raise_Call_Entity := Empty;
1842          end if;
1843       end if;
1844
1845       return Local_Raise_Call_Entity;
1846    end Get_Local_Raise_Call_Entity;
1847
1848    -----------------------------
1849    -- Get_RT_Exception_Entity --
1850    -----------------------------
1851
1852    function Get_RT_Exception_Entity (R : RT_Exception_Code) return Entity_Id is
1853    begin
1854       case R is
1855          when RT_CE_Exceptions => return Standard_Constraint_Error;
1856          when RT_PE_Exceptions => return Standard_Program_Error;
1857          when RT_SE_Exceptions => return Standard_Storage_Error;
1858       end case;
1859    end Get_RT_Exception_Entity;
1860
1861    ----------------------
1862    -- Is_Non_Ada_Error --
1863    ----------------------
1864
1865    function Is_Non_Ada_Error (E : Entity_Id) return Boolean is
1866    begin
1867       if not OpenVMS_On_Target then
1868          return False;
1869       end if;
1870
1871       Get_Name_String (Chars (E));
1872
1873       --  Note: it is a little irregular for the body of exp_ch11 to know
1874       --  the details of the encoding scheme for names, but on the other
1875       --  hand, gigi knows them, and this is for gigi's benefit anyway!
1876
1877       if Name_Buffer (1 .. 30) /= "system__aux_dec__non_ada_error" then
1878          return False;
1879       end if;
1880
1881       return True;
1882    end Is_Non_Ada_Error;
1883
1884    ----------------------------
1885    -- Warn_If_No_Propagation --
1886    ----------------------------
1887
1888    procedure Warn_If_No_Propagation (N : Node_Id) is
1889    begin
1890       if Restriction_Active (No_Exception_Propagation)
1891         and then Warn_On_Non_Local_Exception
1892       then
1893          Warn_No_Exception_Propagation_Active (N);
1894
1895          if Configurable_Run_Time_Mode then
1896             Error_Msg_N
1897               ("\?Last_Chance_Handler will be called on exception", N);
1898          else
1899             Error_Msg_N
1900               ("\?execution may raise unhandled exception", N);
1901          end if;
1902       end if;
1903    end Warn_If_No_Propagation;
1904
1905    ------------------------------------------
1906    -- Warn_No_Exception_Propagation_Active --
1907    ------------------------------------------
1908
1909    procedure Warn_No_Exception_Propagation_Active (N : Node_Id) is
1910    begin
1911       Error_Msg_N
1912         ("?pragma Restrictions (No_Exception_Propagation) in effect", N);
1913    end Warn_No_Exception_Propagation_Active;
1914
1915 end Exp_Ch11;