PR c++/86288
[official-gcc.git] / gcc / ada / exp_ch7.adb
blobee04b22254a8585723787fbf01031a0c4c30c64e
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- E X P _ C H 7 --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2018, 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 3, 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 COPYING3. If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license. --
20 -- --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
23 -- --
24 ------------------------------------------------------------------------------
26 -- This package contains virtually all expansion mechanisms related to
27 -- - controlled types
28 -- - transient scopes
30 with Atree; use Atree;
31 with Debug; use Debug;
32 with Einfo; use Einfo;
33 with Elists; use Elists;
34 with Errout; use Errout;
35 with Exp_Ch6; use Exp_Ch6;
36 with Exp_Ch9; use Exp_Ch9;
37 with Exp_Ch11; use Exp_Ch11;
38 with Exp_Dbug; use Exp_Dbug;
39 with Exp_Dist; use Exp_Dist;
40 with Exp_Disp; use Exp_Disp;
41 with Exp_Prag; use Exp_Prag;
42 with Exp_Tss; use Exp_Tss;
43 with Exp_Util; use Exp_Util;
44 with Freeze; use Freeze;
45 with Lib; use Lib;
46 with Nlists; use Nlists;
47 with Nmake; use Nmake;
48 with Opt; use Opt;
49 with Output; use Output;
50 with Restrict; use Restrict;
51 with Rident; use Rident;
52 with Rtsfind; use Rtsfind;
53 with Sinfo; use Sinfo;
54 with Sem; use Sem;
55 with Sem_Aux; use Sem_Aux;
56 with Sem_Ch3; use Sem_Ch3;
57 with Sem_Ch7; use Sem_Ch7;
58 with Sem_Ch8; use Sem_Ch8;
59 with Sem_Res; use Sem_Res;
60 with Sem_Util; use Sem_Util;
61 with Snames; use Snames;
62 with Stand; use Stand;
63 with Tbuild; use Tbuild;
64 with Ttypes; use Ttypes;
65 with Uintp; use Uintp;
67 package body Exp_Ch7 is
69 --------------------------------
70 -- Transient Scope Management --
71 --------------------------------
73 -- A transient scope is created when temporary objects are created by the
74 -- compiler. These temporary objects are allocated on the secondary stack
75 -- and the transient scope is responsible for finalizing the object when
76 -- appropriate and reclaiming the memory at the right time. The temporary
77 -- objects are generally the objects allocated to store the result of a
78 -- function returning an unconstrained or a tagged value. Expressions
79 -- needing to be wrapped in a transient scope (functions calls returning
80 -- unconstrained or tagged values) may appear in 3 different contexts which
81 -- lead to 3 different kinds of transient scope expansion:
83 -- 1. In a simple statement (procedure call, assignment, ...). In this
84 -- case the instruction is wrapped into a transient block. See
85 -- Wrap_Transient_Statement for details.
87 -- 2. In an expression of a control structure (test in a IF statement,
88 -- expression in a CASE statement, ...). See Wrap_Transient_Expression
89 -- for details.
91 -- 3. In a expression of an object_declaration. No wrapping is possible
92 -- here, so the finalization actions, if any, are done right after the
93 -- declaration and the secondary stack deallocation is done in the
94 -- proper enclosing scope. See Wrap_Transient_Declaration for details.
96 -- Note about functions returning tagged types: it has been decided to
97 -- always allocate their result in the secondary stack, even though is not
98 -- absolutely mandatory when the tagged type is constrained because the
99 -- caller knows the size of the returned object and thus could allocate the
100 -- result in the primary stack. An exception to this is when the function
101 -- builds its result in place, as is done for functions with inherently
102 -- limited result types for Ada 2005. In that case, certain callers may
103 -- pass the address of a constrained object as the target object for the
104 -- function result.
106 -- By allocating tagged results in the secondary stack a number of
107 -- implementation difficulties are avoided:
109 -- - If it is a dispatching function call, the computation of the size of
110 -- the result is possible but complex from the outside.
112 -- - If the returned type is controlled, the assignment of the returned
113 -- value to the anonymous object involves an Adjust, and we have no
114 -- easy way to access the anonymous object created by the back end.
116 -- - If the returned type is class-wide, this is an unconstrained type
117 -- anyway.
119 -- Furthermore, the small loss in efficiency which is the result of this
120 -- decision is not such a big deal because functions returning tagged types
121 -- are not as common in practice compared to functions returning access to
122 -- a tagged type.
124 --------------------------------------------------
125 -- Transient Blocks and Finalization Management --
126 --------------------------------------------------
128 function Find_Transient_Context (N : Node_Id) return Node_Id;
129 -- Locate a suitable context for arbitrary node N which may need to be
130 -- serviced by a transient scope. Return Empty if no suitable context is
131 -- available.
133 procedure Insert_Actions_In_Scope_Around
134 (N : Node_Id;
135 Clean : Boolean;
136 Manage_SS : Boolean);
137 -- Insert the before-actions kept in the scope stack before N, and the
138 -- after-actions after N, which must be a member of a list. If flag Clean
139 -- is set, insert any cleanup actions. If flag Manage_SS is set, insert
140 -- calls to mark and release the secondary stack.
142 function Make_Transient_Block
143 (Loc : Source_Ptr;
144 Action : Node_Id;
145 Par : Node_Id) return Node_Id;
146 -- Action is a single statement or object declaration. Par is the proper
147 -- parent of the generated block. Create a transient block whose name is
148 -- the current scope and the only handled statement is Action. If Action
149 -- involves controlled objects or secondary stack usage, the corresponding
150 -- cleanup actions are performed at the end of the block.
152 procedure Set_Node_To_Be_Wrapped (N : Node_Id);
153 -- Set the field Node_To_Be_Wrapped of the current scope
155 -- ??? The entire comment needs to be rewritten
156 -- ??? which entire comment?
158 procedure Store_Actions_In_Scope (AK : Scope_Action_Kind; L : List_Id);
159 -- Shared processing for Store_xxx_Actions_In_Scope
161 -----------------------------
162 -- Finalization Management --
163 -----------------------------
165 -- This part describe how Initialization/Adjustment/Finalization procedures
166 -- are generated and called. Two cases must be considered, types that are
167 -- Controlled (Is_Controlled flag set) and composite types that contain
168 -- controlled components (Has_Controlled_Component flag set). In the first
169 -- case the procedures to call are the user-defined primitive operations
170 -- Initialize/Adjust/Finalize. In the second case, GNAT generates
171 -- Deep_Initialize, Deep_Adjust and Deep_Finalize that are in charge
172 -- of calling the former procedures on the controlled components.
174 -- For records with Has_Controlled_Component set, a hidden "controller"
175 -- component is inserted. This controller component contains its own
176 -- finalization list on which all controlled components are attached
177 -- creating an indirection on the upper-level Finalization list. This
178 -- technique facilitates the management of objects whose number of
179 -- controlled components changes during execution. This controller
180 -- component is itself controlled and is attached to the upper-level
181 -- finalization chain. Its adjust primitive is in charge of calling adjust
182 -- on the components and adjusting the finalization pointer to match their
183 -- new location (see a-finali.adb).
185 -- It is not possible to use a similar technique for arrays that have
186 -- Has_Controlled_Component set. In this case, deep procedures are
187 -- generated that call initialize/adjust/finalize + attachment or
188 -- detachment on the finalization list for all component.
190 -- Initialize calls: they are generated for declarations or dynamic
191 -- allocations of Controlled objects with no initial value. They are always
192 -- followed by an attachment to the current Finalization Chain. For the
193 -- dynamic allocation case this the chain attached to the scope of the
194 -- access type definition otherwise, this is the chain of the current
195 -- scope.
197 -- Adjust Calls: They are generated on 2 occasions: (1) for declarations
198 -- or dynamic allocations of Controlled objects with an initial value.
199 -- (2) after an assignment. In the first case they are followed by an
200 -- attachment to the final chain, in the second case they are not.
202 -- Finalization Calls: They are generated on (1) scope exit, (2)
203 -- assignments, (3) unchecked deallocations. In case (3) they have to
204 -- be detached from the final chain, in case (2) they must not and in
205 -- case (1) this is not important since we are exiting the scope anyway.
207 -- Other details:
209 -- Type extensions will have a new record controller at each derivation
210 -- level containing controlled components. The record controller for
211 -- the parent/ancestor is attached to the finalization list of the
212 -- extension's record controller (i.e. the parent is like a component
213 -- of the extension).
215 -- For types that are both Is_Controlled and Has_Controlled_Components,
216 -- the record controller and the object itself are handled separately.
217 -- It could seem simpler to attach the object at the end of its record
218 -- controller but this would not tackle view conversions properly.
220 -- A classwide type can always potentially have controlled components
221 -- but the record controller of the corresponding actual type may not
222 -- be known at compile time so the dispatch table contains a special
223 -- field that allows computation of the offset of the record controller
224 -- dynamically. See s-finimp.Deep_Tag_Attach and a-tags.RC_Offset.
226 -- Here is a simple example of the expansion of a controlled block :
228 -- declare
229 -- X : Controlled;
230 -- Y : Controlled := Init;
232 -- type R is record
233 -- C : Controlled;
234 -- end record;
235 -- W : R;
236 -- Z : R := (C => X);
238 -- begin
239 -- X := Y;
240 -- W := Z;
241 -- end;
243 -- is expanded into
245 -- declare
246 -- _L : System.FI.Finalizable_Ptr;
248 -- procedure _Clean is
249 -- begin
250 -- Abort_Defer;
251 -- System.FI.Finalize_List (_L);
252 -- Abort_Undefer;
253 -- end _Clean;
255 -- X : Controlled;
256 -- begin
257 -- Abort_Defer;
258 -- Initialize (X);
259 -- Attach_To_Final_List (_L, Finalizable (X), 1);
260 -- at end: Abort_Undefer;
261 -- Y : Controlled := Init;
262 -- Adjust (Y);
263 -- Attach_To_Final_List (_L, Finalizable (Y), 1);
265 -- type R is record
266 -- C : Controlled;
267 -- end record;
268 -- W : R;
269 -- begin
270 -- Abort_Defer;
271 -- Deep_Initialize (W, _L, 1);
272 -- at end: Abort_Under;
273 -- Z : R := (C => X);
274 -- Deep_Adjust (Z, _L, 1);
276 -- begin
277 -- _Assign (X, Y);
278 -- Deep_Finalize (W, False);
279 -- <save W's final pointers>
280 -- W := Z;
281 -- <restore W's final pointers>
282 -- Deep_Adjust (W, _L, 0);
283 -- at end
284 -- _Clean;
285 -- end;
287 type Final_Primitives is
288 (Initialize_Case, Adjust_Case, Finalize_Case, Address_Case);
289 -- This enumeration type is defined in order to ease sharing code for
290 -- building finalization procedures for composite types.
292 Name_Of : constant array (Final_Primitives) of Name_Id :=
293 (Initialize_Case => Name_Initialize,
294 Adjust_Case => Name_Adjust,
295 Finalize_Case => Name_Finalize,
296 Address_Case => Name_Finalize_Address);
297 Deep_Name_Of : constant array (Final_Primitives) of TSS_Name_Type :=
298 (Initialize_Case => TSS_Deep_Initialize,
299 Adjust_Case => TSS_Deep_Adjust,
300 Finalize_Case => TSS_Deep_Finalize,
301 Address_Case => TSS_Finalize_Address);
303 function Allows_Finalization_Master (Typ : Entity_Id) return Boolean;
304 -- Determine whether access type Typ may have a finalization master
306 procedure Build_Array_Deep_Procs (Typ : Entity_Id);
307 -- Build the deep Initialize/Adjust/Finalize for a record Typ with
308 -- Has_Controlled_Component set and store them using the TSS mechanism.
310 function Build_Cleanup_Statements
311 (N : Node_Id;
312 Additional_Cleanup : List_Id) return List_Id;
313 -- Create the cleanup calls for an asynchronous call block, task master,
314 -- protected subprogram body, task allocation block or task body, or
315 -- additional cleanup actions parked on a transient block. If the context
316 -- does not contain the above constructs, the routine returns an empty
317 -- list.
319 procedure Build_Finalizer
320 (N : Node_Id;
321 Clean_Stmts : List_Id;
322 Mark_Id : Entity_Id;
323 Top_Decls : List_Id;
324 Defer_Abort : Boolean;
325 Fin_Id : out Entity_Id);
326 -- N may denote an accept statement, block, entry body, package body,
327 -- package spec, protected body, subprogram body, or a task body. Create
328 -- a procedure which contains finalization calls for all controlled objects
329 -- declared in the declarative or statement region of N. The calls are
330 -- built in reverse order relative to the original declarations. In the
331 -- case of a task body, the routine delays the creation of the finalizer
332 -- until all statements have been moved to the task body procedure.
333 -- Clean_Stmts may contain additional context-dependent code used to abort
334 -- asynchronous calls or complete tasks (see Build_Cleanup_Statements).
335 -- Mark_Id is the secondary stack used in the current context or Empty if
336 -- missing. Top_Decls is the list on which the declaration of the finalizer
337 -- is attached in the non-package case. Defer_Abort indicates that the
338 -- statements passed in perform actions that require abort to be deferred,
339 -- such as for task termination. Fin_Id is the finalizer declaration
340 -- entity.
342 procedure Build_Finalizer_Call (N : Node_Id; Fin_Id : Entity_Id);
343 -- N is a construct which contains a handled sequence of statements, Fin_Id
344 -- is the entity of a finalizer. Create an At_End handler which covers the
345 -- statements of N and calls Fin_Id. If the handled statement sequence has
346 -- an exception handler, the statements will be wrapped in a block to avoid
347 -- unwanted interaction with the new At_End handler.
349 procedure Build_Record_Deep_Procs (Typ : Entity_Id);
350 -- Build the deep Initialize/Adjust/Finalize for a record Typ with
351 -- Has_Component_Component set and store them using the TSS mechanism.
353 procedure Check_Unnesting_Elaboration_Code (N : Node_Id);
354 -- The statement part of a package body that is a compilation unit may
355 -- contain blocks that declare local subprograms. In Subprogram_Unnesting
356 -- Mode such subprograms must be handled as nested inside the (implicit)
357 -- elaboration procedure that executes that statement part. To handle
358 -- properly uplevel references we construct that subprogram explicitly,
359 -- to contain blocks and inner subprograms, The statement part becomes
360 -- a call to this subprogram. This is only done if blocks are present
361 -- in the statement list of the body.
363 procedure Check_Visibly_Controlled
364 (Prim : Final_Primitives;
365 Typ : Entity_Id;
366 E : in out Entity_Id;
367 Cref : in out Node_Id);
368 -- The controlled operation declared for a derived type may not be
369 -- overriding, if the controlled operations of the parent type are hidden,
370 -- for example when the parent is a private type whose full view is
371 -- controlled. For other primitive operations we modify the name of the
372 -- operation to indicate that it is not overriding, but this is not
373 -- possible for Initialize, etc. because they have to be retrievable by
374 -- name. Before generating the proper call to one of these operations we
375 -- check whether Typ is known to be controlled at the point of definition.
376 -- If it is not then we must retrieve the hidden operation of the parent
377 -- and use it instead. This is one case that might be solved more cleanly
378 -- once Overriding pragmas or declarations are in place.
380 function Convert_View
381 (Proc : Entity_Id;
382 Arg : Node_Id;
383 Ind : Pos := 1) return Node_Id;
384 -- Proc is one of the Initialize/Adjust/Finalize operations, and Arg is the
385 -- argument being passed to it. Ind indicates which formal of procedure
386 -- Proc we are trying to match. This function will, if necessary, generate
387 -- a conversion between the partial and full view of Arg to match the type
388 -- of the formal of Proc, or force a conversion to the class-wide type in
389 -- the case where the operation is abstract.
391 function Enclosing_Function (E : Entity_Id) return Entity_Id;
392 -- Given an arbitrary entity, traverse the scope chain looking for the
393 -- first enclosing function. Return Empty if no function was found.
395 function Make_Call
396 (Loc : Source_Ptr;
397 Proc_Id : Entity_Id;
398 Param : Node_Id;
399 Skip_Self : Boolean := False) return Node_Id;
400 -- Subsidiary to Make_Adjust_Call and Make_Final_Call. Given the entity of
401 -- routine [Deep_]Adjust or [Deep_]Finalize and an object parameter, create
402 -- an adjust or finalization call. Wnen flag Skip_Self is set, the related
403 -- action has an effect on the components only (if any).
405 function Make_Deep_Proc
406 (Prim : Final_Primitives;
407 Typ : Entity_Id;
408 Stmts : List_Id) return Node_Id;
409 -- This function generates the tree for Deep_Initialize, Deep_Adjust or
410 -- Deep_Finalize procedures according to the first parameter, these
411 -- procedures operate on the type Typ. The Stmts parameter gives the body
412 -- of the procedure.
414 function Make_Deep_Array_Body
415 (Prim : Final_Primitives;
416 Typ : Entity_Id) return List_Id;
417 -- This function generates the list of statements for implementing
418 -- Deep_Initialize, Deep_Adjust or Deep_Finalize procedures according to
419 -- the first parameter, these procedures operate on the array type Typ.
421 function Make_Deep_Record_Body
422 (Prim : Final_Primitives;
423 Typ : Entity_Id;
424 Is_Local : Boolean := False) return List_Id;
425 -- This function generates the list of statements for implementing
426 -- Deep_Initialize, Deep_Adjust or Deep_Finalize procedures according to
427 -- the first parameter, these procedures operate on the record type Typ.
428 -- Flag Is_Local is used in conjunction with Deep_Finalize to designate
429 -- whether the inner logic should be dictated by state counters.
431 function Make_Finalize_Address_Stmts (Typ : Entity_Id) return List_Id;
432 -- Subsidiary to Make_Finalize_Address_Body, Make_Deep_Array_Body and
433 -- Make_Deep_Record_Body. Generate the following statements:
435 -- declare
436 -- type Acc_Typ is access all Typ;
437 -- for Acc_Typ'Storage_Size use 0;
438 -- begin
439 -- [Deep_]Finalize (Acc_Typ (V).all);
440 -- end;
442 --------------------------------
443 -- Allows_Finalization_Master --
444 --------------------------------
446 function Allows_Finalization_Master (Typ : Entity_Id) return Boolean is
447 function In_Deallocation_Instance (E : Entity_Id) return Boolean;
448 -- Determine whether entity E is inside a wrapper package created for
449 -- an instance of Ada.Unchecked_Deallocation.
451 ------------------------------
452 -- In_Deallocation_Instance --
453 ------------------------------
455 function In_Deallocation_Instance (E : Entity_Id) return Boolean is
456 Pkg : constant Entity_Id := Scope (E);
457 Par : Node_Id := Empty;
459 begin
460 if Ekind (Pkg) = E_Package
461 and then Present (Related_Instance (Pkg))
462 and then Ekind (Related_Instance (Pkg)) = E_Procedure
463 then
464 Par := Generic_Parent (Parent (Related_Instance (Pkg)));
466 return
467 Present (Par)
468 and then Chars (Par) = Name_Unchecked_Deallocation
469 and then Chars (Scope (Par)) = Name_Ada
470 and then Scope (Scope (Par)) = Standard_Standard;
471 end if;
473 return False;
474 end In_Deallocation_Instance;
476 -- Local variables
478 Desig_Typ : constant Entity_Id := Designated_Type (Typ);
479 Ptr_Typ : constant Entity_Id :=
480 Root_Type_Of_Full_View (Base_Type (Typ));
482 -- Start of processing for Allows_Finalization_Master
484 begin
485 -- Certain run-time configurations and targets do not provide support
486 -- for controlled types and therefore do not need masters.
488 if Restriction_Active (No_Finalization) then
489 return False;
491 -- Do not consider C and C++ types since it is assumed that the non-Ada
492 -- side will handle their cleanup.
494 elsif Convention (Desig_Typ) = Convention_C
495 or else Convention (Desig_Typ) = Convention_CPP
496 then
497 return False;
499 -- Do not consider an access type that returns on the secondary stack
501 elsif Present (Associated_Storage_Pool (Ptr_Typ))
502 and then Is_RTE (Associated_Storage_Pool (Ptr_Typ), RE_SS_Pool)
503 then
504 return False;
506 -- Do not consider an access type that can never allocate an object
508 elsif No_Pool_Assigned (Ptr_Typ) then
509 return False;
511 -- Do not consider an access type coming from an Unchecked_Deallocation
512 -- instance. Even though the designated type may be controlled, the
513 -- access type will never participate in any allocations.
515 elsif In_Deallocation_Instance (Ptr_Typ) then
516 return False;
518 -- Do not consider a non-library access type when No_Nested_Finalization
519 -- is in effect since finalization masters are controlled objects and if
520 -- created will violate the restriction.
522 elsif Restriction_Active (No_Nested_Finalization)
523 and then not Is_Library_Level_Entity (Ptr_Typ)
524 then
525 return False;
527 -- Do not consider an access type subject to pragma No_Heap_Finalization
528 -- because objects allocated through such a type are not to be finalized
529 -- when the access type goes out of scope.
531 elsif No_Heap_Finalization (Ptr_Typ) then
532 return False;
534 -- Do not create finalization masters in GNATprove mode because this
535 -- causes unwanted extra expansion. A compilation in this mode must
536 -- keep the tree as close as possible to the original sources.
538 elsif GNATprove_Mode then
539 return False;
541 -- Otherwise the access type may use a finalization master
543 else
544 return True;
545 end if;
546 end Allows_Finalization_Master;
548 ----------------------------
549 -- Build_Anonymous_Master --
550 ----------------------------
552 procedure Build_Anonymous_Master (Ptr_Typ : Entity_Id) is
553 function Create_Anonymous_Master
554 (Desig_Typ : Entity_Id;
555 Unit_Id : Entity_Id;
556 Unit_Decl : Node_Id) return Entity_Id;
557 -- Create a new anonymous master for access type Ptr_Typ with designated
558 -- type Desig_Typ. The declaration of the master and its initialization
559 -- are inserted in the declarative part of unit Unit_Decl. Unit_Id is
560 -- the entity of Unit_Decl.
562 function Current_Anonymous_Master
563 (Desig_Typ : Entity_Id;
564 Unit_Id : Entity_Id) return Entity_Id;
565 -- Find an anonymous master declared within unit Unit_Id which services
566 -- designated type Desig_Typ. If there is no such master, return Empty.
568 -----------------------------
569 -- Create_Anonymous_Master --
570 -----------------------------
572 function Create_Anonymous_Master
573 (Desig_Typ : Entity_Id;
574 Unit_Id : Entity_Id;
575 Unit_Decl : Node_Id) return Entity_Id
577 Loc : constant Source_Ptr := Sloc (Unit_Id);
579 All_FMs : Elist_Id;
580 Decls : List_Id;
581 FM_Decl : Node_Id;
582 FM_Id : Entity_Id;
583 FM_Init : Node_Id;
584 Unit_Spec : Node_Id;
586 begin
587 -- Generate:
588 -- <FM_Id> : Finalization_Master;
590 FM_Id := Make_Temporary (Loc, 'A');
592 FM_Decl :=
593 Make_Object_Declaration (Loc,
594 Defining_Identifier => FM_Id,
595 Object_Definition =>
596 New_Occurrence_Of (RTE (RE_Finalization_Master), Loc));
598 -- Generate:
599 -- Set_Base_Pool
600 -- (<FM_Id>, Global_Pool_Object'Unrestricted_Access);
602 FM_Init :=
603 Make_Procedure_Call_Statement (Loc,
604 Name =>
605 New_Occurrence_Of (RTE (RE_Set_Base_Pool), Loc),
606 Parameter_Associations => New_List (
607 New_Occurrence_Of (FM_Id, Loc),
608 Make_Attribute_Reference (Loc,
609 Prefix =>
610 New_Occurrence_Of (RTE (RE_Global_Pool_Object), Loc),
611 Attribute_Name => Name_Unrestricted_Access)));
613 -- Find the declarative list of the unit
615 if Nkind (Unit_Decl) = N_Package_Declaration then
616 Unit_Spec := Specification (Unit_Decl);
617 Decls := Visible_Declarations (Unit_Spec);
619 if No (Decls) then
620 Decls := New_List;
621 Set_Visible_Declarations (Unit_Spec, Decls);
622 end if;
624 -- Package body or subprogram case
626 -- ??? A subprogram spec or body that acts as a compilation unit may
627 -- contain a formal parameter of an anonymous access-to-controlled
628 -- type initialized by an allocator.
630 -- procedure Comp_Unit_Proc (Param : access Ctrl := new Ctrl);
632 -- There is no suitable place to create the master as the subprogram
633 -- is not in a declarative list.
635 else
636 Decls := Declarations (Unit_Decl);
638 if No (Decls) then
639 Decls := New_List;
640 Set_Declarations (Unit_Decl, Decls);
641 end if;
642 end if;
644 Prepend_To (Decls, FM_Init);
645 Prepend_To (Decls, FM_Decl);
647 -- Use the scope of the unit when analyzing the declaration of the
648 -- master and its initialization actions.
650 Push_Scope (Unit_Id);
651 Analyze (FM_Decl);
652 Analyze (FM_Init);
653 Pop_Scope;
655 -- Mark the master as servicing this specific designated type
657 Set_Anonymous_Designated_Type (FM_Id, Desig_Typ);
659 -- Include the anonymous master in the list of existing masters which
660 -- appear in this unit. This effectively creates a mapping between a
661 -- master and a designated type which in turn allows for the reuse of
662 -- masters on a per-unit basis.
664 All_FMs := Anonymous_Masters (Unit_Id);
666 if No (All_FMs) then
667 All_FMs := New_Elmt_List;
668 Set_Anonymous_Masters (Unit_Id, All_FMs);
669 end if;
671 Prepend_Elmt (FM_Id, All_FMs);
673 return FM_Id;
674 end Create_Anonymous_Master;
676 ------------------------------
677 -- Current_Anonymous_Master --
678 ------------------------------
680 function Current_Anonymous_Master
681 (Desig_Typ : Entity_Id;
682 Unit_Id : Entity_Id) return Entity_Id
684 All_FMs : constant Elist_Id := Anonymous_Masters (Unit_Id);
685 FM_Elmt : Elmt_Id;
686 FM_Id : Entity_Id;
688 begin
689 -- Inspect the list of anonymous masters declared within the unit
690 -- looking for an existing master which services the same designated
691 -- type.
693 if Present (All_FMs) then
694 FM_Elmt := First_Elmt (All_FMs);
695 while Present (FM_Elmt) loop
696 FM_Id := Node (FM_Elmt);
698 -- The currect master services the same designated type. As a
699 -- result the master can be reused and associated with another
700 -- anonymous access-to-controlled type.
702 if Anonymous_Designated_Type (FM_Id) = Desig_Typ then
703 return FM_Id;
704 end if;
706 Next_Elmt (FM_Elmt);
707 end loop;
708 end if;
710 return Empty;
711 end Current_Anonymous_Master;
713 -- Local variables
715 Desig_Typ : Entity_Id;
716 FM_Id : Entity_Id;
717 Priv_View : Entity_Id;
718 Unit_Decl : Node_Id;
719 Unit_Id : Entity_Id;
721 -- Start of processing for Build_Anonymous_Master
723 begin
724 -- Nothing to do if the circumstances do not allow for a finalization
725 -- master.
727 if not Allows_Finalization_Master (Ptr_Typ) then
728 return;
729 end if;
731 Unit_Decl := Unit (Cunit (Current_Sem_Unit));
732 Unit_Id := Unique_Defining_Entity (Unit_Decl);
734 -- The compilation unit is a package instantiation. In this case the
735 -- anonymous master is associated with the package spec as both the
736 -- spec and body appear at the same level.
738 if Nkind (Unit_Decl) = N_Package_Body
739 and then Nkind (Original_Node (Unit_Decl)) = N_Package_Instantiation
740 then
741 Unit_Id := Corresponding_Spec (Unit_Decl);
742 Unit_Decl := Unit_Declaration_Node (Unit_Id);
743 end if;
745 -- Use the initial declaration of the designated type when it denotes
746 -- the full view of an incomplete or private type. This ensures that
747 -- types with one and two views are treated the same.
749 Desig_Typ := Directly_Designated_Type (Ptr_Typ);
750 Priv_View := Incomplete_Or_Partial_View (Desig_Typ);
752 if Present (Priv_View) then
753 Desig_Typ := Priv_View;
754 end if;
756 -- Determine whether the current semantic unit already has an anonymous
757 -- master which services the designated type.
759 FM_Id := Current_Anonymous_Master (Desig_Typ, Unit_Id);
761 -- If this is not the case, create a new master
763 if No (FM_Id) then
764 FM_Id := Create_Anonymous_Master (Desig_Typ, Unit_Id, Unit_Decl);
765 end if;
767 Set_Finalization_Master (Ptr_Typ, FM_Id);
768 end Build_Anonymous_Master;
770 ----------------------------
771 -- Build_Array_Deep_Procs --
772 ----------------------------
774 procedure Build_Array_Deep_Procs (Typ : Entity_Id) is
775 begin
776 Set_TSS (Typ,
777 Make_Deep_Proc
778 (Prim => Initialize_Case,
779 Typ => Typ,
780 Stmts => Make_Deep_Array_Body (Initialize_Case, Typ)));
782 if not Is_Limited_View (Typ) then
783 Set_TSS (Typ,
784 Make_Deep_Proc
785 (Prim => Adjust_Case,
786 Typ => Typ,
787 Stmts => Make_Deep_Array_Body (Adjust_Case, Typ)));
788 end if;
790 -- Do not generate Deep_Finalize and Finalize_Address if finalization is
791 -- suppressed since these routine will not be used.
793 if not Restriction_Active (No_Finalization) then
794 Set_TSS (Typ,
795 Make_Deep_Proc
796 (Prim => Finalize_Case,
797 Typ => Typ,
798 Stmts => Make_Deep_Array_Body (Finalize_Case, Typ)));
800 -- Create TSS primitive Finalize_Address (unless CodePeer_Mode)
802 if not CodePeer_Mode then
803 Set_TSS (Typ,
804 Make_Deep_Proc
805 (Prim => Address_Case,
806 Typ => Typ,
807 Stmts => Make_Deep_Array_Body (Address_Case, Typ)));
808 end if;
809 end if;
810 end Build_Array_Deep_Procs;
812 ------------------------------
813 -- Build_Cleanup_Statements --
814 ------------------------------
816 function Build_Cleanup_Statements
817 (N : Node_Id;
818 Additional_Cleanup : List_Id) return List_Id
820 Is_Asynchronous_Call : constant Boolean :=
821 Nkind (N) = N_Block_Statement
822 and then Is_Asynchronous_Call_Block (N);
823 Is_Master : constant Boolean :=
824 Nkind (N) /= N_Entry_Body
825 and then Is_Task_Master (N);
826 Is_Protected_Body : constant Boolean :=
827 Nkind (N) = N_Subprogram_Body
828 and then Is_Protected_Subprogram_Body (N);
829 Is_Task_Allocation : constant Boolean :=
830 Nkind (N) = N_Block_Statement
831 and then Is_Task_Allocation_Block (N);
832 Is_Task_Body : constant Boolean :=
833 Nkind (Original_Node (N)) = N_Task_Body;
835 Loc : constant Source_Ptr := Sloc (N);
836 Stmts : constant List_Id := New_List;
838 begin
839 if Is_Task_Body then
840 if Restricted_Profile then
841 Append_To (Stmts,
842 Build_Runtime_Call (Loc, RE_Complete_Restricted_Task));
843 else
844 Append_To (Stmts, Build_Runtime_Call (Loc, RE_Complete_Task));
845 end if;
847 elsif Is_Master then
848 if Restriction_Active (No_Task_Hierarchy) = False then
849 Append_To (Stmts, Build_Runtime_Call (Loc, RE_Complete_Master));
850 end if;
852 -- Add statements to unlock the protected object parameter and to
853 -- undefer abort. If the context is a protected procedure and the object
854 -- has entries, call the entry service routine.
856 -- NOTE: The generated code references _object, a parameter to the
857 -- procedure.
859 elsif Is_Protected_Body then
860 declare
861 Spec : constant Node_Id := Parent (Corresponding_Spec (N));
862 Conc_Typ : Entity_Id;
863 Param : Node_Id;
864 Param_Typ : Entity_Id;
866 begin
867 -- Find the _object parameter representing the protected object
869 Param := First (Parameter_Specifications (Spec));
870 loop
871 Param_Typ := Etype (Parameter_Type (Param));
873 if Ekind (Param_Typ) = E_Record_Type then
874 Conc_Typ := Corresponding_Concurrent_Type (Param_Typ);
875 end if;
877 exit when No (Param) or else Present (Conc_Typ);
878 Next (Param);
879 end loop;
881 pragma Assert (Present (Param));
883 -- Historical note: In earlier versions of GNAT, there was code
884 -- at this point to generate stuff to service entry queues. It is
885 -- now abstracted in Build_Protected_Subprogram_Call_Cleanup.
887 Build_Protected_Subprogram_Call_Cleanup
888 (Specification (N), Conc_Typ, Loc, Stmts);
889 end;
891 -- Add a call to Expunge_Unactivated_Tasks for dynamically allocated
892 -- tasks. Other unactivated tasks are completed by Complete_Task or
893 -- Complete_Master.
895 -- NOTE: The generated code references _chain, a local object
897 elsif Is_Task_Allocation then
899 -- Generate:
900 -- Expunge_Unactivated_Tasks (_chain);
902 -- where _chain is the list of tasks created by the allocator but not
903 -- yet activated. This list will be empty unless the block completes
904 -- abnormally.
906 Append_To (Stmts,
907 Make_Procedure_Call_Statement (Loc,
908 Name =>
909 New_Occurrence_Of
910 (RTE (RE_Expunge_Unactivated_Tasks), Loc),
911 Parameter_Associations => New_List (
912 New_Occurrence_Of (Activation_Chain_Entity (N), Loc))));
914 -- Attempt to cancel an asynchronous entry call whenever the block which
915 -- contains the abortable part is exited.
917 -- NOTE: The generated code references Cnn, a local object
919 elsif Is_Asynchronous_Call then
920 declare
921 Cancel_Param : constant Entity_Id :=
922 Entry_Cancel_Parameter (Entity (Identifier (N)));
924 begin
925 -- If it is of type Communication_Block, this must be a protected
926 -- entry call. Generate:
928 -- if Enqueued (Cancel_Param) then
929 -- Cancel_Protected_Entry_Call (Cancel_Param);
930 -- end if;
932 if Is_RTE (Etype (Cancel_Param), RE_Communication_Block) then
933 Append_To (Stmts,
934 Make_If_Statement (Loc,
935 Condition =>
936 Make_Function_Call (Loc,
937 Name =>
938 New_Occurrence_Of (RTE (RE_Enqueued), Loc),
939 Parameter_Associations => New_List (
940 New_Occurrence_Of (Cancel_Param, Loc))),
942 Then_Statements => New_List (
943 Make_Procedure_Call_Statement (Loc,
944 Name =>
945 New_Occurrence_Of
946 (RTE (RE_Cancel_Protected_Entry_Call), Loc),
947 Parameter_Associations => New_List (
948 New_Occurrence_Of (Cancel_Param, Loc))))));
950 -- Asynchronous delay, generate:
951 -- Cancel_Async_Delay (Cancel_Param);
953 elsif Is_RTE (Etype (Cancel_Param), RE_Delay_Block) then
954 Append_To (Stmts,
955 Make_Procedure_Call_Statement (Loc,
956 Name =>
957 New_Occurrence_Of (RTE (RE_Cancel_Async_Delay), Loc),
958 Parameter_Associations => New_List (
959 Make_Attribute_Reference (Loc,
960 Prefix =>
961 New_Occurrence_Of (Cancel_Param, Loc),
962 Attribute_Name => Name_Unchecked_Access))));
964 -- Task entry call, generate:
965 -- Cancel_Task_Entry_Call (Cancel_Param);
967 else
968 Append_To (Stmts,
969 Make_Procedure_Call_Statement (Loc,
970 Name =>
971 New_Occurrence_Of (RTE (RE_Cancel_Task_Entry_Call), Loc),
972 Parameter_Associations => New_List (
973 New_Occurrence_Of (Cancel_Param, Loc))));
974 end if;
975 end;
976 end if;
978 Append_List_To (Stmts, Additional_Cleanup);
979 return Stmts;
980 end Build_Cleanup_Statements;
982 -----------------------------
983 -- Build_Controlling_Procs --
984 -----------------------------
986 procedure Build_Controlling_Procs (Typ : Entity_Id) is
987 begin
988 if Is_Array_Type (Typ) then
989 Build_Array_Deep_Procs (Typ);
990 else pragma Assert (Is_Record_Type (Typ));
991 Build_Record_Deep_Procs (Typ);
992 end if;
993 end Build_Controlling_Procs;
995 -----------------------------
996 -- Build_Exception_Handler --
997 -----------------------------
999 function Build_Exception_Handler
1000 (Data : Finalization_Exception_Data;
1001 For_Library : Boolean := False) return Node_Id
1003 Actuals : List_Id;
1004 Proc_To_Call : Entity_Id;
1005 Except : Node_Id;
1006 Stmts : List_Id;
1008 begin
1009 pragma Assert (Present (Data.Raised_Id));
1011 if Exception_Extra_Info
1012 or else (For_Library and not Restricted_Profile)
1013 then
1014 if Exception_Extra_Info then
1016 -- Generate:
1018 -- Get_Current_Excep.all
1020 Except :=
1021 Make_Function_Call (Data.Loc,
1022 Name =>
1023 Make_Explicit_Dereference (Data.Loc,
1024 Prefix =>
1025 New_Occurrence_Of
1026 (RTE (RE_Get_Current_Excep), Data.Loc)));
1028 else
1029 -- Generate:
1031 -- null
1033 Except := Make_Null (Data.Loc);
1034 end if;
1036 if For_Library and then not Restricted_Profile then
1037 Proc_To_Call := RTE (RE_Save_Library_Occurrence);
1038 Actuals := New_List (Except);
1040 else
1041 Proc_To_Call := RTE (RE_Save_Occurrence);
1043 -- The dereference occurs only when Exception_Extra_Info is true,
1044 -- and therefore Except is not null.
1046 Actuals :=
1047 New_List (
1048 New_Occurrence_Of (Data.E_Id, Data.Loc),
1049 Make_Explicit_Dereference (Data.Loc, Except));
1050 end if;
1052 -- Generate:
1054 -- when others =>
1055 -- if not Raised_Id then
1056 -- Raised_Id := True;
1058 -- Save_Occurrence (E_Id, Get_Current_Excep.all.all);
1059 -- or
1060 -- Save_Library_Occurrence (Get_Current_Excep.all);
1061 -- end if;
1063 Stmts :=
1064 New_List (
1065 Make_If_Statement (Data.Loc,
1066 Condition =>
1067 Make_Op_Not (Data.Loc,
1068 Right_Opnd => New_Occurrence_Of (Data.Raised_Id, Data.Loc)),
1070 Then_Statements => New_List (
1071 Make_Assignment_Statement (Data.Loc,
1072 Name => New_Occurrence_Of (Data.Raised_Id, Data.Loc),
1073 Expression => New_Occurrence_Of (Standard_True, Data.Loc)),
1075 Make_Procedure_Call_Statement (Data.Loc,
1076 Name =>
1077 New_Occurrence_Of (Proc_To_Call, Data.Loc),
1078 Parameter_Associations => Actuals))));
1080 else
1081 -- Generate:
1083 -- Raised_Id := True;
1085 Stmts := New_List (
1086 Make_Assignment_Statement (Data.Loc,
1087 Name => New_Occurrence_Of (Data.Raised_Id, Data.Loc),
1088 Expression => New_Occurrence_Of (Standard_True, Data.Loc)));
1089 end if;
1091 -- Generate:
1093 -- when others =>
1095 return
1096 Make_Exception_Handler (Data.Loc,
1097 Exception_Choices => New_List (Make_Others_Choice (Data.Loc)),
1098 Statements => Stmts);
1099 end Build_Exception_Handler;
1101 -------------------------------
1102 -- Build_Finalization_Master --
1103 -------------------------------
1105 procedure Build_Finalization_Master
1106 (Typ : Entity_Id;
1107 For_Lib_Level : Boolean := False;
1108 For_Private : Boolean := False;
1109 Context_Scope : Entity_Id := Empty;
1110 Insertion_Node : Node_Id := Empty)
1112 procedure Add_Pending_Access_Type
1113 (Typ : Entity_Id;
1114 Ptr_Typ : Entity_Id);
1115 -- Add access type Ptr_Typ to the pending access type list for type Typ
1117 -----------------------------
1118 -- Add_Pending_Access_Type --
1119 -----------------------------
1121 procedure Add_Pending_Access_Type
1122 (Typ : Entity_Id;
1123 Ptr_Typ : Entity_Id)
1125 List : Elist_Id;
1127 begin
1128 if Present (Pending_Access_Types (Typ)) then
1129 List := Pending_Access_Types (Typ);
1130 else
1131 List := New_Elmt_List;
1132 Set_Pending_Access_Types (Typ, List);
1133 end if;
1135 Prepend_Elmt (Ptr_Typ, List);
1136 end Add_Pending_Access_Type;
1138 -- Local variables
1140 Desig_Typ : constant Entity_Id := Designated_Type (Typ);
1142 Ptr_Typ : constant Entity_Id := Root_Type_Of_Full_View (Base_Type (Typ));
1143 -- A finalization master created for a named access type is associated
1144 -- with the full view (if applicable) as a consequence of freezing. The
1145 -- full view criteria does not apply to anonymous access types because
1146 -- those cannot have a private and a full view.
1148 -- Start of processing for Build_Finalization_Master
1150 begin
1151 -- Nothing to do if the circumstances do not allow for a finalization
1152 -- master.
1154 if not Allows_Finalization_Master (Typ) then
1155 return;
1157 -- Various machinery such as freezing may have already created a
1158 -- finalization master.
1160 elsif Present (Finalization_Master (Ptr_Typ)) then
1161 return;
1162 end if;
1164 declare
1165 Actions : constant List_Id := New_List;
1166 Loc : constant Source_Ptr := Sloc (Ptr_Typ);
1167 Fin_Mas_Id : Entity_Id;
1168 Pool_Id : Entity_Id;
1170 begin
1171 -- Source access types use fixed master names since the master is
1172 -- inserted in the same source unit only once. The only exception to
1173 -- this are instances using the same access type as generic actual.
1175 if Comes_From_Source (Ptr_Typ) and then not Inside_A_Generic then
1176 Fin_Mas_Id :=
1177 Make_Defining_Identifier (Loc,
1178 Chars => New_External_Name (Chars (Ptr_Typ), "FM"));
1180 -- Internally generated access types use temporaries as their names
1181 -- due to possible collision with identical names coming from other
1182 -- packages.
1184 else
1185 Fin_Mas_Id := Make_Temporary (Loc, 'F');
1186 end if;
1188 Set_Finalization_Master (Ptr_Typ, Fin_Mas_Id);
1190 -- Generate:
1191 -- <Ptr_Typ>FM : aliased Finalization_Master;
1193 Append_To (Actions,
1194 Make_Object_Declaration (Loc,
1195 Defining_Identifier => Fin_Mas_Id,
1196 Aliased_Present => True,
1197 Object_Definition =>
1198 New_Occurrence_Of (RTE (RE_Finalization_Master), Loc)));
1200 -- Set the associated pool and primitive Finalize_Address of the new
1201 -- finalization master.
1203 -- The access type has a user-defined storage pool, use it
1205 if Present (Associated_Storage_Pool (Ptr_Typ)) then
1206 Pool_Id := Associated_Storage_Pool (Ptr_Typ);
1208 -- Otherwise the default choice is the global storage pool
1210 else
1211 Pool_Id := RTE (RE_Global_Pool_Object);
1212 Set_Associated_Storage_Pool (Ptr_Typ, Pool_Id);
1213 end if;
1215 -- Generate:
1216 -- Set_Base_Pool (<Ptr_Typ>FM, Pool_Id'Unchecked_Access);
1218 Append_To (Actions,
1219 Make_Procedure_Call_Statement (Loc,
1220 Name =>
1221 New_Occurrence_Of (RTE (RE_Set_Base_Pool), Loc),
1222 Parameter_Associations => New_List (
1223 New_Occurrence_Of (Fin_Mas_Id, Loc),
1224 Make_Attribute_Reference (Loc,
1225 Prefix => New_Occurrence_Of (Pool_Id, Loc),
1226 Attribute_Name => Name_Unrestricted_Access))));
1228 -- Finalize_Address is not generated in CodePeer mode because the
1229 -- body contains address arithmetic. Skip this step.
1231 if CodePeer_Mode then
1232 null;
1234 -- Associate the Finalize_Address primitive of the designated type
1235 -- with the finalization master of the access type. The designated
1236 -- type must be forzen as Finalize_Address is generated when the
1237 -- freeze node is expanded.
1239 elsif Is_Frozen (Desig_Typ)
1240 and then Present (Finalize_Address (Desig_Typ))
1242 -- The finalization master of an anonymous access type may need
1243 -- to be inserted in a specific place in the tree. For instance:
1245 -- type Comp_Typ;
1247 -- <finalization master of "access Comp_Typ">
1249 -- type Rec_Typ is record
1250 -- Comp : access Comp_Typ;
1251 -- end record;
1253 -- <freeze node for Comp_Typ>
1254 -- <freeze node for Rec_Typ>
1256 -- Due to this oddity, the anonymous access type is stored for
1257 -- later processing (see below).
1259 and then Ekind (Ptr_Typ) /= E_Anonymous_Access_Type
1260 then
1261 -- Generate:
1262 -- Set_Finalize_Address
1263 -- (<Ptr_Typ>FM, <Desig_Typ>FD'Unrestricted_Access);
1265 Append_To (Actions,
1266 Make_Set_Finalize_Address_Call
1267 (Loc => Loc,
1268 Ptr_Typ => Ptr_Typ));
1270 -- Otherwise the designated type is either anonymous access or a
1271 -- Taft-amendment type and has not been frozen. Store the access
1272 -- type for later processing (see Freeze_Type).
1274 else
1275 Add_Pending_Access_Type (Desig_Typ, Ptr_Typ);
1276 end if;
1278 -- A finalization master created for an access designating a type
1279 -- with private components is inserted before a context-dependent
1280 -- node.
1282 if For_Private then
1284 -- At this point both the scope of the context and the insertion
1285 -- mode must be known.
1287 pragma Assert (Present (Context_Scope));
1288 pragma Assert (Present (Insertion_Node));
1290 Push_Scope (Context_Scope);
1292 -- Treat use clauses as declarations and insert directly in front
1293 -- of them.
1295 if Nkind_In (Insertion_Node, N_Use_Package_Clause,
1296 N_Use_Type_Clause)
1297 then
1298 Insert_List_Before_And_Analyze (Insertion_Node, Actions);
1299 else
1300 Insert_Actions (Insertion_Node, Actions);
1301 end if;
1303 Pop_Scope;
1305 -- The finalization master belongs to an access result type related
1306 -- to a build-in-place function call used to initialize a library
1307 -- level object. The master must be inserted in front of the access
1308 -- result type declaration denoted by Insertion_Node.
1310 elsif For_Lib_Level then
1311 pragma Assert (Present (Insertion_Node));
1312 Insert_Actions (Insertion_Node, Actions);
1314 -- Otherwise the finalization master and its initialization become a
1315 -- part of the freeze node.
1317 else
1318 Append_Freeze_Actions (Ptr_Typ, Actions);
1319 end if;
1320 end;
1321 end Build_Finalization_Master;
1323 ---------------------
1324 -- Build_Finalizer --
1325 ---------------------
1327 procedure Build_Finalizer
1328 (N : Node_Id;
1329 Clean_Stmts : List_Id;
1330 Mark_Id : Entity_Id;
1331 Top_Decls : List_Id;
1332 Defer_Abort : Boolean;
1333 Fin_Id : out Entity_Id)
1335 Acts_As_Clean : constant Boolean :=
1336 Present (Mark_Id)
1337 or else
1338 (Present (Clean_Stmts)
1339 and then Is_Non_Empty_List (Clean_Stmts));
1340 Exceptions_OK : constant Boolean := Exceptions_In_Finalization_OK;
1341 For_Package_Body : constant Boolean := Nkind (N) = N_Package_Body;
1342 For_Package_Spec : constant Boolean := Nkind (N) = N_Package_Declaration;
1343 For_Package : constant Boolean :=
1344 For_Package_Body or else For_Package_Spec;
1345 Loc : constant Source_Ptr := Sloc (N);
1347 -- NOTE: Local variable declarations are conservative and do not create
1348 -- structures right from the start. Entities and lists are created once
1349 -- it has been established that N has at least one controlled object.
1351 Components_Built : Boolean := False;
1352 -- A flag used to avoid double initialization of entities and lists. If
1353 -- the flag is set then the following variables have been initialized:
1354 -- Counter_Id
1355 -- Finalizer_Decls
1356 -- Finalizer_Stmts
1357 -- Jump_Alts
1359 Counter_Id : Entity_Id := Empty;
1360 Counter_Val : Nat := 0;
1361 -- Name and value of the state counter
1363 Decls : List_Id := No_List;
1364 -- Declarative region of N (if available). If N is a package declaration
1365 -- Decls denotes the visible declarations.
1367 Finalizer_Data : Finalization_Exception_Data;
1368 -- Data for the exception
1370 Finalizer_Decls : List_Id := No_List;
1371 -- Local variable declarations. This list holds the label declarations
1372 -- of all jump block alternatives as well as the declaration of the
1373 -- local exception occurrence and the raised flag:
1374 -- E : Exception_Occurrence;
1375 -- Raised : Boolean := False;
1376 -- L<counter value> : label;
1378 Finalizer_Insert_Nod : Node_Id := Empty;
1379 -- Insertion point for the finalizer body. Depending on the context
1380 -- (Nkind of N) and the individual grouping of controlled objects, this
1381 -- node may denote a package declaration or body, package instantiation,
1382 -- block statement or a counter update statement.
1384 Finalizer_Stmts : List_Id := No_List;
1385 -- The statement list of the finalizer body. It contains the following:
1387 -- Abort_Defer; -- Added if abort is allowed
1388 -- <call to Prev_At_End> -- Added if exists
1389 -- <cleanup statements> -- Added if Acts_As_Clean
1390 -- <jump block> -- Added if Has_Ctrl_Objs
1391 -- <finalization statements> -- Added if Has_Ctrl_Objs
1392 -- <stack release> -- Added if Mark_Id exists
1393 -- Abort_Undefer; -- Added if abort is allowed
1395 Has_Ctrl_Objs : Boolean := False;
1396 -- A general flag which denotes whether N has at least one controlled
1397 -- object.
1399 Has_Tagged_Types : Boolean := False;
1400 -- A general flag which indicates whether N has at least one library-
1401 -- level tagged type declaration.
1403 HSS : Node_Id := Empty;
1404 -- The sequence of statements of N (if available)
1406 Jump_Alts : List_Id := No_List;
1407 -- Jump block alternatives. Depending on the value of the state counter,
1408 -- the control flow jumps to a sequence of finalization statements. This
1409 -- list contains the following:
1411 -- when <counter value> =>
1412 -- goto L<counter value>;
1414 Jump_Block_Insert_Nod : Node_Id := Empty;
1415 -- Specific point in the finalizer statements where the jump block is
1416 -- inserted.
1418 Last_Top_Level_Ctrl_Construct : Node_Id := Empty;
1419 -- The last controlled construct encountered when processing the top
1420 -- level lists of N. This can be a nested package, an instantiation or
1421 -- an object declaration.
1423 Prev_At_End : Entity_Id := Empty;
1424 -- The previous at end procedure of the handled statements block of N
1426 Priv_Decls : List_Id := No_List;
1427 -- The private declarations of N if N is a package declaration
1429 Spec_Id : Entity_Id := Empty;
1430 Spec_Decls : List_Id := Top_Decls;
1431 Stmts : List_Id := No_List;
1433 Tagged_Type_Stmts : List_Id := No_List;
1434 -- Contains calls to Ada.Tags.Unregister_Tag for all library-level
1435 -- tagged types found in N.
1437 -----------------------
1438 -- Local subprograms --
1439 -----------------------
1441 procedure Build_Components;
1442 -- Create all entites and initialize all lists used in the creation of
1443 -- the finalizer.
1445 procedure Create_Finalizer;
1446 -- Create the spec and body of the finalizer and insert them in the
1447 -- proper place in the tree depending on the context.
1449 procedure Process_Declarations
1450 (Decls : List_Id;
1451 Preprocess : Boolean := False;
1452 Top_Level : Boolean := False);
1453 -- Inspect a list of declarations or statements which may contain
1454 -- objects that need finalization. When flag Preprocess is set, the
1455 -- routine will simply count the total number of controlled objects in
1456 -- Decls. Flag Top_Level denotes whether the processing is done for
1457 -- objects in nested package declarations or instances.
1459 procedure Process_Object_Declaration
1460 (Decl : Node_Id;
1461 Has_No_Init : Boolean := False;
1462 Is_Protected : Boolean := False);
1463 -- Generate all the machinery associated with the finalization of a
1464 -- single object. Flag Has_No_Init is used to denote certain contexts
1465 -- where Decl does not have initialization call(s). Flag Is_Protected
1466 -- is set when Decl denotes a simple protected object.
1468 procedure Process_Tagged_Type_Declaration (Decl : Node_Id);
1469 -- Generate all the code necessary to unregister the external tag of a
1470 -- tagged type.
1472 ----------------------
1473 -- Build_Components --
1474 ----------------------
1476 procedure Build_Components is
1477 Counter_Decl : Node_Id;
1478 Counter_Typ : Entity_Id;
1479 Counter_Typ_Decl : Node_Id;
1481 begin
1482 pragma Assert (Present (Decls));
1484 -- This routine might be invoked several times when dealing with
1485 -- constructs that have two lists (either two declarative regions
1486 -- or declarations and statements). Avoid double initialization.
1488 if Components_Built then
1489 return;
1490 end if;
1492 Components_Built := True;
1494 if Has_Ctrl_Objs then
1496 -- Create entities for the counter, its type, the local exception
1497 -- and the raised flag.
1499 Counter_Id := Make_Temporary (Loc, 'C');
1500 Counter_Typ := Make_Temporary (Loc, 'T');
1502 Finalizer_Decls := New_List;
1504 Build_Object_Declarations
1505 (Finalizer_Data, Finalizer_Decls, Loc, For_Package);
1507 -- Since the total number of controlled objects is always known,
1508 -- build a subtype of Natural with precise bounds. This allows
1509 -- the backend to optimize the case statement. Generate:
1511 -- subtype Tnn is Natural range 0 .. Counter_Val;
1513 Counter_Typ_Decl :=
1514 Make_Subtype_Declaration (Loc,
1515 Defining_Identifier => Counter_Typ,
1516 Subtype_Indication =>
1517 Make_Subtype_Indication (Loc,
1518 Subtype_Mark => New_Occurrence_Of (Standard_Natural, Loc),
1519 Constraint =>
1520 Make_Range_Constraint (Loc,
1521 Range_Expression =>
1522 Make_Range (Loc,
1523 Low_Bound =>
1524 Make_Integer_Literal (Loc, Uint_0),
1525 High_Bound =>
1526 Make_Integer_Literal (Loc, Counter_Val)))));
1528 -- Generate the declaration of the counter itself:
1530 -- Counter : Integer := 0;
1532 Counter_Decl :=
1533 Make_Object_Declaration (Loc,
1534 Defining_Identifier => Counter_Id,
1535 Object_Definition => New_Occurrence_Of (Counter_Typ, Loc),
1536 Expression => Make_Integer_Literal (Loc, 0));
1538 -- Set the type of the counter explicitly to prevent errors when
1539 -- examining object declarations later on.
1541 Set_Etype (Counter_Id, Counter_Typ);
1543 -- The counter and its type are inserted before the source
1544 -- declarations of N.
1546 Prepend_To (Decls, Counter_Decl);
1547 Prepend_To (Decls, Counter_Typ_Decl);
1549 -- The counter and its associated type must be manually analyzed
1550 -- since N has already been analyzed. Use the scope of the spec
1551 -- when inserting in a package.
1553 if For_Package then
1554 Push_Scope (Spec_Id);
1555 Analyze (Counter_Typ_Decl);
1556 Analyze (Counter_Decl);
1557 Pop_Scope;
1559 else
1560 Analyze (Counter_Typ_Decl);
1561 Analyze (Counter_Decl);
1562 end if;
1564 Jump_Alts := New_List;
1565 end if;
1567 -- If the context requires additional cleanup, the finalization
1568 -- machinery is added after the cleanup code.
1570 if Acts_As_Clean then
1571 Finalizer_Stmts := Clean_Stmts;
1572 Jump_Block_Insert_Nod := Last (Finalizer_Stmts);
1573 else
1574 Finalizer_Stmts := New_List;
1575 end if;
1577 if Has_Tagged_Types then
1578 Tagged_Type_Stmts := New_List;
1579 end if;
1580 end Build_Components;
1582 ----------------------
1583 -- Create_Finalizer --
1584 ----------------------
1586 procedure Create_Finalizer is
1587 function New_Finalizer_Name return Name_Id;
1588 -- Create a fully qualified name of a package spec or body finalizer.
1589 -- The generated name is of the form: xx__yy__finalize_[spec|body].
1591 ------------------------
1592 -- New_Finalizer_Name --
1593 ------------------------
1595 function New_Finalizer_Name return Name_Id is
1596 procedure New_Finalizer_Name (Id : Entity_Id);
1597 -- Place "__<name-of-Id>" in the name buffer. If the identifier
1598 -- has a non-standard scope, process the scope first.
1600 ------------------------
1601 -- New_Finalizer_Name --
1602 ------------------------
1604 procedure New_Finalizer_Name (Id : Entity_Id) is
1605 begin
1606 if Scope (Id) = Standard_Standard then
1607 Get_Name_String (Chars (Id));
1609 else
1610 New_Finalizer_Name (Scope (Id));
1611 Add_Str_To_Name_Buffer ("__");
1612 Add_Str_To_Name_Buffer (Get_Name_String (Chars (Id)));
1613 end if;
1614 end New_Finalizer_Name;
1616 -- Start of processing for New_Finalizer_Name
1618 begin
1619 -- Create the fully qualified name of the enclosing scope
1621 New_Finalizer_Name (Spec_Id);
1623 -- Generate:
1624 -- __finalize_[spec|body]
1626 Add_Str_To_Name_Buffer ("__finalize_");
1628 if For_Package_Spec then
1629 Add_Str_To_Name_Buffer ("spec");
1630 else
1631 Add_Str_To_Name_Buffer ("body");
1632 end if;
1634 return Name_Find;
1635 end New_Finalizer_Name;
1637 -- Local variables
1639 Body_Id : Entity_Id;
1640 Fin_Body : Node_Id;
1641 Fin_Spec : Node_Id;
1642 Jump_Block : Node_Id;
1643 Label : Node_Id;
1644 Label_Id : Entity_Id;
1646 -- Start of processing for Create_Finalizer
1648 begin
1649 -- Step 1: Creation of the finalizer name
1651 -- Packages must use a distinct name for their finalizers since the
1652 -- binder will have to generate calls to them by name. The name is
1653 -- of the following form:
1655 -- xx__yy__finalize_[spec|body]
1657 if For_Package then
1658 Fin_Id := Make_Defining_Identifier (Loc, New_Finalizer_Name);
1659 Set_Has_Qualified_Name (Fin_Id);
1660 Set_Has_Fully_Qualified_Name (Fin_Id);
1662 -- The default name is _finalizer
1664 else
1665 Fin_Id :=
1666 Make_Defining_Identifier (Loc,
1667 Chars => New_External_Name (Name_uFinalizer));
1669 -- The visibility semantics of AT_END handlers force a strange
1670 -- separation of spec and body for stack-related finalizers:
1672 -- declare : Enclosing_Scope
1673 -- procedure _finalizer;
1674 -- begin
1675 -- <controlled objects>
1676 -- procedure _finalizer is
1677 -- ...
1678 -- at end
1679 -- _finalizer;
1680 -- end;
1682 -- Both spec and body are within the same construct and scope, but
1683 -- the body is part of the handled sequence of statements. This
1684 -- placement confuses the elaboration mechanism on targets where
1685 -- AT_END handlers are expanded into "when all others" handlers:
1687 -- exception
1688 -- when all others =>
1689 -- _finalizer; -- appears to require elab checks
1690 -- at end
1691 -- _finalizer;
1692 -- end;
1694 -- Since the compiler guarantees that the body of a _finalizer is
1695 -- always inserted in the same construct where the AT_END handler
1696 -- resides, there is no need for elaboration checks.
1698 Set_Kill_Elaboration_Checks (Fin_Id);
1700 -- Inlining the finalizer produces a substantial speedup at -O2.
1701 -- It is inlined by default at -O3. Either way, it is called
1702 -- exactly twice (once on the normal path, and once for
1703 -- exceptions/abort), so this won't bloat the code too much.
1705 Set_Is_Inlined (Fin_Id);
1706 end if;
1708 -- Step 2: Creation of the finalizer specification
1710 -- Generate:
1711 -- procedure Fin_Id;
1713 Fin_Spec :=
1714 Make_Subprogram_Declaration (Loc,
1715 Specification =>
1716 Make_Procedure_Specification (Loc,
1717 Defining_Unit_Name => Fin_Id));
1719 -- Step 3: Creation of the finalizer body
1721 if Has_Ctrl_Objs then
1723 -- Add L0, the default destination to the jump block
1725 Label_Id := Make_Identifier (Loc, New_External_Name ('L', 0));
1726 Set_Entity (Label_Id,
1727 Make_Defining_Identifier (Loc, Chars (Label_Id)));
1728 Label := Make_Label (Loc, Label_Id);
1730 -- Generate:
1731 -- L0 : label;
1733 Prepend_To (Finalizer_Decls,
1734 Make_Implicit_Label_Declaration (Loc,
1735 Defining_Identifier => Entity (Label_Id),
1736 Label_Construct => Label));
1738 -- Generate:
1739 -- when others =>
1740 -- goto L0;
1742 Append_To (Jump_Alts,
1743 Make_Case_Statement_Alternative (Loc,
1744 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
1745 Statements => New_List (
1746 Make_Goto_Statement (Loc,
1747 Name => New_Occurrence_Of (Entity (Label_Id), Loc)))));
1749 -- Generate:
1750 -- <<L0>>
1752 Append_To (Finalizer_Stmts, Label);
1754 -- Create the jump block which controls the finalization flow
1755 -- depending on the value of the state counter.
1757 Jump_Block :=
1758 Make_Case_Statement (Loc,
1759 Expression => Make_Identifier (Loc, Chars (Counter_Id)),
1760 Alternatives => Jump_Alts);
1762 if Acts_As_Clean and then Present (Jump_Block_Insert_Nod) then
1763 Insert_After (Jump_Block_Insert_Nod, Jump_Block);
1764 else
1765 Prepend_To (Finalizer_Stmts, Jump_Block);
1766 end if;
1767 end if;
1769 -- Add the library-level tagged type unregistration machinery before
1770 -- the jump block circuitry. This ensures that external tags will be
1771 -- removed even if a finalization exception occurs at some point.
1773 if Has_Tagged_Types then
1774 Prepend_List_To (Finalizer_Stmts, Tagged_Type_Stmts);
1775 end if;
1777 -- Add a call to the previous At_End handler if it exists. The call
1778 -- must always precede the jump block.
1780 if Present (Prev_At_End) then
1781 Prepend_To (Finalizer_Stmts,
1782 Make_Procedure_Call_Statement (Loc, Prev_At_End));
1784 -- Clear the At_End handler since we have already generated the
1785 -- proper replacement call for it.
1787 Set_At_End_Proc (HSS, Empty);
1788 end if;
1790 -- Release the secondary stack
1792 if Present (Mark_Id) then
1793 declare
1794 Release : Node_Id := Build_SS_Release_Call (Loc, Mark_Id);
1796 begin
1797 -- If the context is a build-in-place function, the secondary
1798 -- stack must be released, unless the build-in-place function
1799 -- itself is returning on the secondary stack. Generate:
1801 -- if BIP_Alloc_Form /= Secondary_Stack then
1802 -- SS_Release (Mark_Id);
1803 -- end if;
1805 -- Note that if the function returns on the secondary stack,
1806 -- then the responsibility of reclaiming the space is always
1807 -- left to the caller (recursively if needed).
1809 if Nkind (N) = N_Subprogram_Body then
1810 declare
1811 Spec_Id : constant Entity_Id :=
1812 Unique_Defining_Entity (N);
1813 BIP_SS : constant Boolean :=
1814 Is_Build_In_Place_Function (Spec_Id)
1815 and then Needs_BIP_Alloc_Form (Spec_Id);
1816 begin
1817 if BIP_SS then
1818 Release :=
1819 Make_If_Statement (Loc,
1820 Condition =>
1821 Make_Op_Ne (Loc,
1822 Left_Opnd =>
1823 New_Occurrence_Of
1824 (Build_In_Place_Formal
1825 (Spec_Id, BIP_Alloc_Form), Loc),
1826 Right_Opnd =>
1827 Make_Integer_Literal (Loc,
1828 UI_From_Int
1829 (BIP_Allocation_Form'Pos
1830 (Secondary_Stack)))),
1832 Then_Statements => New_List (Release));
1833 end if;
1834 end;
1835 end if;
1837 Append_To (Finalizer_Stmts, Release);
1838 end;
1839 end if;
1841 -- Protect the statements with abort defer/undefer. This is only when
1842 -- aborts are allowed and the cleanup statements require deferral or
1843 -- there are controlled objects to be finalized. Note that the abort
1844 -- defer/undefer pair does not require an extra block because each
1845 -- finalization exception is caught in its corresponding finalization
1846 -- block. As a result, the call to Abort_Defer always takes place.
1848 if Abort_Allowed and then (Defer_Abort or Has_Ctrl_Objs) then
1849 Prepend_To (Finalizer_Stmts,
1850 Build_Runtime_Call (Loc, RE_Abort_Defer));
1852 Append_To (Finalizer_Stmts,
1853 Build_Runtime_Call (Loc, RE_Abort_Undefer));
1854 end if;
1856 -- The local exception does not need to be reraised for library-level
1857 -- finalizers. Note that this action must be carried out after object
1858 -- cleanup, secondary stack release, and abort undeferral. Generate:
1860 -- if Raised and then not Abort then
1861 -- Raise_From_Controlled_Operation (E);
1862 -- end if;
1864 if Has_Ctrl_Objs and Exceptions_OK and not For_Package then
1865 Append_To (Finalizer_Stmts,
1866 Build_Raise_Statement (Finalizer_Data));
1867 end if;
1869 -- Generate:
1870 -- procedure Fin_Id is
1871 -- Abort : constant Boolean := Triggered_By_Abort;
1872 -- <or>
1873 -- Abort : constant Boolean := False; -- no abort
1875 -- E : Exception_Occurrence; -- All added if flag
1876 -- Raised : Boolean := False; -- Has_Ctrl_Objs is set
1877 -- L0 : label;
1878 -- ...
1879 -- Lnn : label;
1881 -- begin
1882 -- Abort_Defer; -- Added if abort is allowed
1883 -- <call to Prev_At_End> -- Added if exists
1884 -- <cleanup statements> -- Added if Acts_As_Clean
1885 -- <jump block> -- Added if Has_Ctrl_Objs
1886 -- <finalization statements> -- Added if Has_Ctrl_Objs
1887 -- <stack release> -- Added if Mark_Id exists
1888 -- Abort_Undefer; -- Added if abort is allowed
1889 -- <exception propagation> -- Added if Has_Ctrl_Objs
1890 -- end Fin_Id;
1892 -- Create the body of the finalizer
1894 Body_Id := Make_Defining_Identifier (Loc, Chars (Fin_Id));
1896 if For_Package then
1897 Set_Has_Qualified_Name (Body_Id);
1898 Set_Has_Fully_Qualified_Name (Body_Id);
1899 end if;
1901 Fin_Body :=
1902 Make_Subprogram_Body (Loc,
1903 Specification =>
1904 Make_Procedure_Specification (Loc,
1905 Defining_Unit_Name => Body_Id),
1906 Declarations => Finalizer_Decls,
1907 Handled_Statement_Sequence =>
1908 Make_Handled_Sequence_Of_Statements (Loc,
1909 Statements => Finalizer_Stmts));
1911 -- Step 4: Spec and body insertion, analysis
1913 if For_Package then
1915 -- If the package spec has private declarations, the finalizer
1916 -- body must be added to the end of the list in order to have
1917 -- visibility of all private controlled objects.
1919 if For_Package_Spec then
1920 if Present (Priv_Decls) then
1921 Append_To (Priv_Decls, Fin_Spec);
1922 Append_To (Priv_Decls, Fin_Body);
1923 else
1924 Append_To (Decls, Fin_Spec);
1925 Append_To (Decls, Fin_Body);
1926 end if;
1928 -- For package bodies, both the finalizer spec and body are
1929 -- inserted at the end of the package declarations.
1931 else
1932 Append_To (Decls, Fin_Spec);
1933 Append_To (Decls, Fin_Body);
1934 end if;
1936 -- Push the name of the package
1938 Push_Scope (Spec_Id);
1939 Analyze (Fin_Spec);
1940 Analyze (Fin_Body);
1941 Pop_Scope;
1943 -- Non-package case
1945 else
1946 -- Create the spec for the finalizer. The At_End handler must be
1947 -- able to call the body which resides in a nested structure.
1949 -- Generate:
1950 -- declare
1951 -- procedure Fin_Id; -- Spec
1952 -- begin
1953 -- <objects and possibly statements>
1954 -- procedure Fin_Id is ... -- Body
1955 -- <statements>
1956 -- at end
1957 -- Fin_Id; -- At_End handler
1958 -- end;
1960 pragma Assert (Present (Spec_Decls));
1962 Append_To (Spec_Decls, Fin_Spec);
1963 Analyze (Fin_Spec);
1965 -- When the finalizer acts solely as a cleanup routine, the body
1966 -- is inserted right after the spec.
1968 if Acts_As_Clean and not Has_Ctrl_Objs then
1969 Insert_After (Fin_Spec, Fin_Body);
1971 -- In all other cases the body is inserted after either:
1973 -- 1) The counter update statement of the last controlled object
1974 -- 2) The last top level nested controlled package
1975 -- 3) The last top level controlled instantiation
1977 else
1978 -- Manually freeze the spec. This is somewhat of a hack because
1979 -- a subprogram is frozen when its body is seen and the freeze
1980 -- node appears right before the body. However, in this case,
1981 -- the spec must be frozen earlier since the At_End handler
1982 -- must be able to call it.
1984 -- declare
1985 -- procedure Fin_Id; -- Spec
1986 -- [Fin_Id] -- Freeze node
1987 -- begin
1988 -- ...
1989 -- at end
1990 -- Fin_Id; -- At_End handler
1991 -- end;
1993 Ensure_Freeze_Node (Fin_Id);
1994 Insert_After (Fin_Spec, Freeze_Node (Fin_Id));
1995 Set_Is_Frozen (Fin_Id);
1997 -- In the case where the last construct to contain a controlled
1998 -- object is either a nested package, an instantiation or a
1999 -- freeze node, the body must be inserted directly after the
2000 -- construct.
2002 if Nkind_In (Last_Top_Level_Ctrl_Construct,
2003 N_Freeze_Entity,
2004 N_Package_Declaration,
2005 N_Package_Body)
2006 then
2007 Finalizer_Insert_Nod := Last_Top_Level_Ctrl_Construct;
2008 end if;
2010 Insert_After (Finalizer_Insert_Nod, Fin_Body);
2011 end if;
2013 Analyze (Fin_Body, Suppress => All_Checks);
2014 end if;
2015 end Create_Finalizer;
2017 --------------------------
2018 -- Process_Declarations --
2019 --------------------------
2021 procedure Process_Declarations
2022 (Decls : List_Id;
2023 Preprocess : Boolean := False;
2024 Top_Level : Boolean := False)
2026 Decl : Node_Id;
2027 Expr : Node_Id;
2028 Obj_Id : Entity_Id;
2029 Obj_Typ : Entity_Id;
2030 Pack_Id : Entity_Id;
2031 Spec : Node_Id;
2032 Typ : Entity_Id;
2034 Old_Counter_Val : Nat;
2035 -- This variable is used to determine whether a nested package or
2036 -- instance contains at least one controlled object.
2038 procedure Processing_Actions
2039 (Has_No_Init : Boolean := False;
2040 Is_Protected : Boolean := False);
2041 -- Depending on the mode of operation of Process_Declarations, either
2042 -- increment the controlled object counter, set the controlled object
2043 -- flag and store the last top level construct or process the current
2044 -- declaration. Flag Has_No_Init is used to propagate scenarios where
2045 -- the current declaration may not have initialization proc(s). Flag
2046 -- Is_Protected should be set when the current declaration denotes a
2047 -- simple protected object.
2049 ------------------------
2050 -- Processing_Actions --
2051 ------------------------
2053 procedure Processing_Actions
2054 (Has_No_Init : Boolean := False;
2055 Is_Protected : Boolean := False)
2057 begin
2058 -- Library-level tagged type
2060 if Nkind (Decl) = N_Full_Type_Declaration then
2061 if Preprocess then
2062 Has_Tagged_Types := True;
2064 if Top_Level and then No (Last_Top_Level_Ctrl_Construct) then
2065 Last_Top_Level_Ctrl_Construct := Decl;
2066 end if;
2068 else
2069 Process_Tagged_Type_Declaration (Decl);
2070 end if;
2072 -- Controlled object declaration
2074 else
2075 if Preprocess then
2076 Counter_Val := Counter_Val + 1;
2077 Has_Ctrl_Objs := True;
2079 if Top_Level and then No (Last_Top_Level_Ctrl_Construct) then
2080 Last_Top_Level_Ctrl_Construct := Decl;
2081 end if;
2083 else
2084 Process_Object_Declaration (Decl, Has_No_Init, Is_Protected);
2085 end if;
2086 end if;
2087 end Processing_Actions;
2089 -- Start of processing for Process_Declarations
2091 begin
2092 if No (Decls) or else Is_Empty_List (Decls) then
2093 return;
2094 end if;
2096 -- Process all declarations in reverse order
2098 Decl := Last_Non_Pragma (Decls);
2099 while Present (Decl) loop
2101 -- Library-level tagged types
2103 if Nkind (Decl) = N_Full_Type_Declaration then
2104 Typ := Defining_Identifier (Decl);
2106 -- Ignored Ghost types do not need any cleanup actions because
2107 -- they will not appear in the final tree.
2109 if Is_Ignored_Ghost_Entity (Typ) then
2110 null;
2112 elsif Is_Tagged_Type (Typ)
2113 and then Is_Library_Level_Entity (Typ)
2114 and then Convention (Typ) = Convention_Ada
2115 and then Present (Access_Disp_Table (Typ))
2116 and then RTE_Available (RE_Register_Tag)
2117 and then not Is_Abstract_Type (Typ)
2118 and then not No_Run_Time_Mode
2119 then
2120 Processing_Actions;
2121 end if;
2123 -- Regular object declarations
2125 elsif Nkind (Decl) = N_Object_Declaration then
2126 Obj_Id := Defining_Identifier (Decl);
2127 Obj_Typ := Base_Type (Etype (Obj_Id));
2128 Expr := Expression (Decl);
2130 -- Bypass any form of processing for objects which have their
2131 -- finalization disabled. This applies only to objects at the
2132 -- library level.
2134 if For_Package and then Finalize_Storage_Only (Obj_Typ) then
2135 null;
2137 -- Finalization of transient objects are treated separately in
2138 -- order to handle sensitive cases. These include:
2140 -- * Aggregate expansion
2141 -- * If, case, and expression with actions expansion
2142 -- * Transient scopes
2144 -- If one of those contexts has marked the transient object as
2145 -- ignored, do not generate finalization actions for it.
2147 elsif Is_Finalized_Transient (Obj_Id)
2148 or else Is_Ignored_Transient (Obj_Id)
2149 then
2150 null;
2152 -- Ignored Ghost objects do not need any cleanup actions
2153 -- because they will not appear in the final tree.
2155 elsif Is_Ignored_Ghost_Entity (Obj_Id) then
2156 null;
2158 -- The object is of the form:
2159 -- Obj : [constant] Typ [:= Expr];
2161 -- Do not process tag-to-class-wide conversions because they do
2162 -- not yield an object. Do not process the incomplete view of a
2163 -- deferred constant. Note that an object initialized by means
2164 -- of a build-in-place function call may appear as a deferred
2165 -- constant after expansion activities. These kinds of objects
2166 -- must be finalized.
2168 elsif not Is_Imported (Obj_Id)
2169 and then Needs_Finalization (Obj_Typ)
2170 and then not Is_Tag_To_Class_Wide_Conversion (Obj_Id)
2171 and then not (Ekind (Obj_Id) = E_Constant
2172 and then not Has_Completion (Obj_Id)
2173 and then No (BIP_Initialization_Call (Obj_Id)))
2174 then
2175 Processing_Actions;
2177 -- The object is of the form:
2178 -- Obj : Access_Typ := Non_BIP_Function_Call'reference;
2180 -- Obj : Access_Typ :=
2181 -- BIP_Function_Call (BIPalloc => 2, ...)'reference;
2183 elsif Is_Access_Type (Obj_Typ)
2184 and then Needs_Finalization
2185 (Available_View (Designated_Type (Obj_Typ)))
2186 and then Present (Expr)
2187 and then
2188 (Is_Secondary_Stack_BIP_Func_Call (Expr)
2189 or else
2190 (Is_Non_BIP_Func_Call (Expr)
2191 and then not Is_Related_To_Func_Return (Obj_Id)))
2192 then
2193 Processing_Actions (Has_No_Init => True);
2195 -- Processing for "hook" objects generated for transient
2196 -- objects declared inside an Expression_With_Actions.
2198 elsif Is_Access_Type (Obj_Typ)
2199 and then Present (Status_Flag_Or_Transient_Decl (Obj_Id))
2200 and then Nkind (Status_Flag_Or_Transient_Decl (Obj_Id)) =
2201 N_Object_Declaration
2202 then
2203 Processing_Actions (Has_No_Init => True);
2205 -- Process intermediate results of an if expression with one
2206 -- of the alternatives using a controlled function call.
2208 elsif Is_Access_Type (Obj_Typ)
2209 and then Present (Status_Flag_Or_Transient_Decl (Obj_Id))
2210 and then Nkind (Status_Flag_Or_Transient_Decl (Obj_Id)) =
2211 N_Defining_Identifier
2212 and then Present (Expr)
2213 and then Nkind (Expr) = N_Null
2214 then
2215 Processing_Actions (Has_No_Init => True);
2217 -- Simple protected objects which use type System.Tasking.
2218 -- Protected_Objects.Protection to manage their locks should
2219 -- be treated as controlled since they require manual cleanup.
2220 -- The only exception is illustrated in the following example:
2222 -- package Pkg is
2223 -- type Ctrl is new Controlled ...
2224 -- procedure Finalize (Obj : in out Ctrl);
2225 -- Lib_Obj : Ctrl;
2226 -- end Pkg;
2228 -- package body Pkg is
2229 -- protected Prot is
2230 -- procedure Do_Something (Obj : in out Ctrl);
2231 -- end Prot;
2233 -- protected body Prot is
2234 -- procedure Do_Something (Obj : in out Ctrl) is ...
2235 -- end Prot;
2237 -- procedure Finalize (Obj : in out Ctrl) is
2238 -- begin
2239 -- Prot.Do_Something (Obj);
2240 -- end Finalize;
2241 -- end Pkg;
2243 -- Since for the most part entities in package bodies depend on
2244 -- those in package specs, Prot's lock should be cleaned up
2245 -- first. The subsequent cleanup of the spec finalizes Lib_Obj.
2246 -- This act however attempts to invoke Do_Something and fails
2247 -- because the lock has disappeared.
2249 elsif Ekind (Obj_Id) = E_Variable
2250 and then not In_Library_Level_Package_Body (Obj_Id)
2251 and then (Is_Simple_Protected_Type (Obj_Typ)
2252 or else Has_Simple_Protected_Object (Obj_Typ))
2253 then
2254 Processing_Actions (Is_Protected => True);
2255 end if;
2257 -- Specific cases of object renamings
2259 elsif Nkind (Decl) = N_Object_Renaming_Declaration then
2260 Obj_Id := Defining_Identifier (Decl);
2261 Obj_Typ := Base_Type (Etype (Obj_Id));
2263 -- Bypass any form of processing for objects which have their
2264 -- finalization disabled. This applies only to objects at the
2265 -- library level.
2267 if For_Package and then Finalize_Storage_Only (Obj_Typ) then
2268 null;
2270 -- Ignored Ghost object renamings do not need any cleanup
2271 -- actions because they will not appear in the final tree.
2273 elsif Is_Ignored_Ghost_Entity (Obj_Id) then
2274 null;
2276 -- Return object of a build-in-place function. This case is
2277 -- recognized and marked by the expansion of an extended return
2278 -- statement (see Expand_N_Extended_Return_Statement).
2280 elsif Needs_Finalization (Obj_Typ)
2281 and then Is_Return_Object (Obj_Id)
2282 and then Present (Status_Flag_Or_Transient_Decl (Obj_Id))
2283 then
2284 Processing_Actions (Has_No_Init => True);
2286 -- Detect a case where a source object has been initialized by
2287 -- a controlled function call or another object which was later
2288 -- rewritten as a class-wide conversion of Ada.Tags.Displace.
2290 -- Obj1 : CW_Type := Src_Obj;
2291 -- Obj2 : CW_Type := Function_Call (...);
2293 -- Obj1 : CW_Type renames (... Ada.Tags.Displace (Src_Obj));
2294 -- Tmp : ... := Function_Call (...)'reference;
2295 -- Obj2 : CW_Type renames (... Ada.Tags.Displace (Tmp));
2297 elsif Is_Displacement_Of_Object_Or_Function_Result (Obj_Id) then
2298 Processing_Actions (Has_No_Init => True);
2299 end if;
2301 -- Inspect the freeze node of an access-to-controlled type and
2302 -- look for a delayed finalization master. This case arises when
2303 -- the freeze actions are inserted at a later time than the
2304 -- expansion of the context. Since Build_Finalizer is never called
2305 -- on a single construct twice, the master will be ultimately
2306 -- left out and never finalized. This is also needed for freeze
2307 -- actions of designated types themselves, since in some cases the
2308 -- finalization master is associated with a designated type's
2309 -- freeze node rather than that of the access type (see handling
2310 -- for freeze actions in Build_Finalization_Master).
2312 elsif Nkind (Decl) = N_Freeze_Entity
2313 and then Present (Actions (Decl))
2314 then
2315 Typ := Entity (Decl);
2317 -- Freeze nodes for ignored Ghost types do not need cleanup
2318 -- actions because they will never appear in the final tree.
2320 if Is_Ignored_Ghost_Entity (Typ) then
2321 null;
2323 elsif (Is_Access_Type (Typ)
2324 and then not Is_Access_Subprogram_Type (Typ)
2325 and then Needs_Finalization
2326 (Available_View (Designated_Type (Typ))))
2327 or else (Is_Type (Typ) and then Needs_Finalization (Typ))
2328 then
2329 Old_Counter_Val := Counter_Val;
2331 -- Freeze nodes are considered to be identical to packages
2332 -- and blocks in terms of nesting. The difference is that
2333 -- a finalization master created inside the freeze node is
2334 -- at the same nesting level as the node itself.
2336 Process_Declarations (Actions (Decl), Preprocess);
2338 -- The freeze node contains a finalization master
2340 if Preprocess
2341 and then Top_Level
2342 and then No (Last_Top_Level_Ctrl_Construct)
2343 and then Counter_Val > Old_Counter_Val
2344 then
2345 Last_Top_Level_Ctrl_Construct := Decl;
2346 end if;
2347 end if;
2349 -- Nested package declarations, avoid generics
2351 elsif Nkind (Decl) = N_Package_Declaration then
2352 Pack_Id := Defining_Entity (Decl);
2353 Spec := Specification (Decl);
2355 -- Do not inspect an ignored Ghost package because all code
2356 -- found within will not appear in the final tree.
2358 if Is_Ignored_Ghost_Entity (Pack_Id) then
2359 null;
2361 elsif Ekind (Pack_Id) /= E_Generic_Package then
2362 Old_Counter_Val := Counter_Val;
2363 Process_Declarations
2364 (Private_Declarations (Spec), Preprocess);
2365 Process_Declarations
2366 (Visible_Declarations (Spec), Preprocess);
2368 -- Either the visible or the private declarations contain a
2369 -- controlled object. The nested package declaration is the
2370 -- last such construct.
2372 if Preprocess
2373 and then Top_Level
2374 and then No (Last_Top_Level_Ctrl_Construct)
2375 and then Counter_Val > Old_Counter_Val
2376 then
2377 Last_Top_Level_Ctrl_Construct := Decl;
2378 end if;
2379 end if;
2381 -- Nested package bodies, avoid generics
2383 elsif Nkind (Decl) = N_Package_Body then
2385 -- Do not inspect an ignored Ghost package body because all
2386 -- code found within will not appear in the final tree.
2388 if Is_Ignored_Ghost_Entity (Defining_Entity (Decl)) then
2389 null;
2391 elsif Ekind (Corresponding_Spec (Decl)) /=
2392 E_Generic_Package
2393 then
2394 Old_Counter_Val := Counter_Val;
2395 Process_Declarations (Declarations (Decl), Preprocess);
2397 -- The nested package body is the last construct to contain
2398 -- a controlled object.
2400 if Preprocess
2401 and then Top_Level
2402 and then No (Last_Top_Level_Ctrl_Construct)
2403 and then Counter_Val > Old_Counter_Val
2404 then
2405 Last_Top_Level_Ctrl_Construct := Decl;
2406 end if;
2407 end if;
2409 -- Handle a rare case caused by a controlled transient object
2410 -- created as part of a record init proc. The variable is wrapped
2411 -- in a block, but the block is not associated with a transient
2412 -- scope.
2414 elsif Nkind (Decl) = N_Block_Statement
2415 and then Inside_Init_Proc
2416 then
2417 Old_Counter_Val := Counter_Val;
2419 if Present (Handled_Statement_Sequence (Decl)) then
2420 Process_Declarations
2421 (Statements (Handled_Statement_Sequence (Decl)),
2422 Preprocess);
2423 end if;
2425 Process_Declarations (Declarations (Decl), Preprocess);
2427 -- Either the declaration or statement list of the block has a
2428 -- controlled object.
2430 if Preprocess
2431 and then Top_Level
2432 and then No (Last_Top_Level_Ctrl_Construct)
2433 and then Counter_Val > Old_Counter_Val
2434 then
2435 Last_Top_Level_Ctrl_Construct := Decl;
2436 end if;
2438 -- Handle the case where the original context has been wrapped in
2439 -- a block to avoid interference between exception handlers and
2440 -- At_End handlers. Treat the block as transparent and process its
2441 -- contents.
2443 elsif Nkind (Decl) = N_Block_Statement
2444 and then Is_Finalization_Wrapper (Decl)
2445 then
2446 if Present (Handled_Statement_Sequence (Decl)) then
2447 Process_Declarations
2448 (Statements (Handled_Statement_Sequence (Decl)),
2449 Preprocess);
2450 end if;
2452 Process_Declarations (Declarations (Decl), Preprocess);
2453 end if;
2455 Prev_Non_Pragma (Decl);
2456 end loop;
2457 end Process_Declarations;
2459 --------------------------------
2460 -- Process_Object_Declaration --
2461 --------------------------------
2463 procedure Process_Object_Declaration
2464 (Decl : Node_Id;
2465 Has_No_Init : Boolean := False;
2466 Is_Protected : Boolean := False)
2468 Loc : constant Source_Ptr := Sloc (Decl);
2469 Obj_Id : constant Entity_Id := Defining_Identifier (Decl);
2471 Init_Typ : Entity_Id;
2472 -- The initialization type of the related object declaration. Note
2473 -- that this is not necessarily the same type as Obj_Typ because of
2474 -- possible type derivations.
2476 Obj_Typ : Entity_Id;
2477 -- The type of the related object declaration
2479 function Build_BIP_Cleanup_Stmts (Func_Id : Entity_Id) return Node_Id;
2480 -- Func_Id denotes a build-in-place function. Generate the following
2481 -- cleanup code:
2483 -- if BIPallocfrom > Secondary_Stack'Pos
2484 -- and then BIPfinalizationmaster /= null
2485 -- then
2486 -- declare
2487 -- type Ptr_Typ is access Obj_Typ;
2488 -- for Ptr_Typ'Storage_Pool
2489 -- use Base_Pool (BIPfinalizationmaster);
2490 -- begin
2491 -- Free (Ptr_Typ (Temp));
2492 -- end;
2493 -- end if;
2495 -- Obj_Typ is the type of the current object, Temp is the original
2496 -- allocation which Obj_Id renames.
2498 procedure Find_Last_Init
2499 (Last_Init : out Node_Id;
2500 Body_Insert : out Node_Id);
2501 -- Find the last initialization call related to object declaration
2502 -- Decl. Last_Init denotes the last initialization call which follows
2503 -- Decl. Body_Insert denotes a node where the finalizer body could be
2504 -- potentially inserted after (if blocks are involved).
2506 -----------------------------
2507 -- Build_BIP_Cleanup_Stmts --
2508 -----------------------------
2510 function Build_BIP_Cleanup_Stmts
2511 (Func_Id : Entity_Id) return Node_Id
2513 Decls : constant List_Id := New_List;
2514 Fin_Mas_Id : constant Entity_Id :=
2515 Build_In_Place_Formal
2516 (Func_Id, BIP_Finalization_Master);
2517 Func_Typ : constant Entity_Id := Etype (Func_Id);
2518 Temp_Id : constant Entity_Id :=
2519 Entity (Prefix (Name (Parent (Obj_Id))));
2521 Cond : Node_Id;
2522 Free_Blk : Node_Id;
2523 Free_Stmt : Node_Id;
2524 Pool_Id : Entity_Id;
2525 Ptr_Typ : Entity_Id;
2527 begin
2528 -- Generate:
2529 -- Pool_Id renames Base_Pool (BIPfinalizationmaster.all).all;
2531 Pool_Id := Make_Temporary (Loc, 'P');
2533 Append_To (Decls,
2534 Make_Object_Renaming_Declaration (Loc,
2535 Defining_Identifier => Pool_Id,
2536 Subtype_Mark =>
2537 New_Occurrence_Of (RTE (RE_Root_Storage_Pool), Loc),
2538 Name =>
2539 Make_Explicit_Dereference (Loc,
2540 Prefix =>
2541 Make_Function_Call (Loc,
2542 Name =>
2543 New_Occurrence_Of (RTE (RE_Base_Pool), Loc),
2544 Parameter_Associations => New_List (
2545 Make_Explicit_Dereference (Loc,
2546 Prefix =>
2547 New_Occurrence_Of (Fin_Mas_Id, Loc)))))));
2549 -- Create an access type which uses the storage pool of the
2550 -- caller's finalization master.
2552 -- Generate:
2553 -- type Ptr_Typ is access Func_Typ;
2555 Ptr_Typ := Make_Temporary (Loc, 'P');
2557 Append_To (Decls,
2558 Make_Full_Type_Declaration (Loc,
2559 Defining_Identifier => Ptr_Typ,
2560 Type_Definition =>
2561 Make_Access_To_Object_Definition (Loc,
2562 Subtype_Indication => New_Occurrence_Of (Func_Typ, Loc))));
2564 -- Perform minor decoration in order to set the master and the
2565 -- storage pool attributes.
2567 Set_Ekind (Ptr_Typ, E_Access_Type);
2568 Set_Finalization_Master (Ptr_Typ, Fin_Mas_Id);
2569 Set_Associated_Storage_Pool (Ptr_Typ, Pool_Id);
2571 -- Create an explicit free statement. Note that the free uses the
2572 -- caller's pool expressed as a renaming.
2574 Free_Stmt :=
2575 Make_Free_Statement (Loc,
2576 Expression =>
2577 Unchecked_Convert_To (Ptr_Typ,
2578 New_Occurrence_Of (Temp_Id, Loc)));
2580 Set_Storage_Pool (Free_Stmt, Pool_Id);
2582 -- Create a block to house the dummy type and the instantiation as
2583 -- well as to perform the cleanup the temporary.
2585 -- Generate:
2586 -- declare
2587 -- <Decls>
2588 -- begin
2589 -- Free (Ptr_Typ (Temp_Id));
2590 -- end;
2592 Free_Blk :=
2593 Make_Block_Statement (Loc,
2594 Declarations => Decls,
2595 Handled_Statement_Sequence =>
2596 Make_Handled_Sequence_Of_Statements (Loc,
2597 Statements => New_List (Free_Stmt)));
2599 -- Generate:
2600 -- if BIPfinalizationmaster /= null then
2602 Cond :=
2603 Make_Op_Ne (Loc,
2604 Left_Opnd => New_Occurrence_Of (Fin_Mas_Id, Loc),
2605 Right_Opnd => Make_Null (Loc));
2607 -- For constrained or tagged results escalate the condition to
2608 -- include the allocation format. Generate:
2610 -- if BIPallocform > Secondary_Stack'Pos
2611 -- and then BIPfinalizationmaster /= null
2612 -- then
2614 if not Is_Constrained (Func_Typ)
2615 or else Is_Tagged_Type (Func_Typ)
2616 then
2617 declare
2618 Alloc : constant Entity_Id :=
2619 Build_In_Place_Formal (Func_Id, BIP_Alloc_Form);
2620 begin
2621 Cond :=
2622 Make_And_Then (Loc,
2623 Left_Opnd =>
2624 Make_Op_Gt (Loc,
2625 Left_Opnd => New_Occurrence_Of (Alloc, Loc),
2626 Right_Opnd =>
2627 Make_Integer_Literal (Loc,
2628 UI_From_Int
2629 (BIP_Allocation_Form'Pos (Secondary_Stack)))),
2631 Right_Opnd => Cond);
2632 end;
2633 end if;
2635 -- Generate:
2636 -- if <Cond> then
2637 -- <Free_Blk>
2638 -- end if;
2640 return
2641 Make_If_Statement (Loc,
2642 Condition => Cond,
2643 Then_Statements => New_List (Free_Blk));
2644 end Build_BIP_Cleanup_Stmts;
2646 --------------------
2647 -- Find_Last_Init --
2648 --------------------
2650 procedure Find_Last_Init
2651 (Last_Init : out Node_Id;
2652 Body_Insert : out Node_Id)
2654 function Find_Last_Init_In_Block (Blk : Node_Id) return Node_Id;
2655 -- Find the last initialization call within the statements of
2656 -- block Blk.
2658 function Is_Init_Call (N : Node_Id) return Boolean;
2659 -- Determine whether node N denotes one of the initialization
2660 -- procedures of types Init_Typ or Obj_Typ.
2662 function Next_Suitable_Statement (Stmt : Node_Id) return Node_Id;
2663 -- Obtain the next statement which follows list member Stmt while
2664 -- ignoring artifacts related to access-before-elaboration checks.
2666 -----------------------------
2667 -- Find_Last_Init_In_Block --
2668 -----------------------------
2670 function Find_Last_Init_In_Block (Blk : Node_Id) return Node_Id is
2671 HSS : constant Node_Id := Handled_Statement_Sequence (Blk);
2672 Stmt : Node_Id;
2674 begin
2675 -- Examine the individual statements of the block in reverse to
2676 -- locate the last initialization call.
2678 if Present (HSS) and then Present (Statements (HSS)) then
2679 Stmt := Last (Statements (HSS));
2680 while Present (Stmt) loop
2682 -- Peek inside nested blocks in case aborts are allowed
2684 if Nkind (Stmt) = N_Block_Statement then
2685 return Find_Last_Init_In_Block (Stmt);
2687 elsif Is_Init_Call (Stmt) then
2688 return Stmt;
2689 end if;
2691 Prev (Stmt);
2692 end loop;
2693 end if;
2695 return Empty;
2696 end Find_Last_Init_In_Block;
2698 ------------------
2699 -- Is_Init_Call --
2700 ------------------
2702 function Is_Init_Call (N : Node_Id) return Boolean is
2703 function Is_Init_Proc_Of
2704 (Subp_Id : Entity_Id;
2705 Typ : Entity_Id) return Boolean;
2706 -- Determine whether subprogram Subp_Id is a valid init proc of
2707 -- type Typ.
2709 ---------------------
2710 -- Is_Init_Proc_Of --
2711 ---------------------
2713 function Is_Init_Proc_Of
2714 (Subp_Id : Entity_Id;
2715 Typ : Entity_Id) return Boolean
2717 Deep_Init : Entity_Id := Empty;
2718 Prim_Init : Entity_Id := Empty;
2719 Type_Init : Entity_Id := Empty;
2721 begin
2722 -- Obtain all possible initialization routines of the
2723 -- related type and try to match the subprogram entity
2724 -- against one of them.
2726 -- Deep_Initialize
2728 Deep_Init := TSS (Typ, TSS_Deep_Initialize);
2730 -- Primitive Initialize
2732 if Is_Controlled (Typ) then
2733 Prim_Init := Find_Optional_Prim_Op (Typ, Name_Initialize);
2735 if Present (Prim_Init) then
2736 Prim_Init := Ultimate_Alias (Prim_Init);
2737 end if;
2738 end if;
2740 -- Type initialization routine
2742 if Has_Non_Null_Base_Init_Proc (Typ) then
2743 Type_Init := Base_Init_Proc (Typ);
2744 end if;
2746 return
2747 (Present (Deep_Init) and then Subp_Id = Deep_Init)
2748 or else
2749 (Present (Prim_Init) and then Subp_Id = Prim_Init)
2750 or else
2751 (Present (Type_Init) and then Subp_Id = Type_Init);
2752 end Is_Init_Proc_Of;
2754 -- Local variables
2756 Call_Id : Entity_Id;
2758 -- Start of processing for Is_Init_Call
2760 begin
2761 if Nkind (N) = N_Procedure_Call_Statement
2762 and then Nkind (Name (N)) = N_Identifier
2763 then
2764 Call_Id := Entity (Name (N));
2766 -- Consider both the type of the object declaration and its
2767 -- related initialization type.
2769 return
2770 Is_Init_Proc_Of (Call_Id, Init_Typ)
2771 or else
2772 Is_Init_Proc_Of (Call_Id, Obj_Typ);
2773 end if;
2775 return False;
2776 end Is_Init_Call;
2778 -----------------------------
2779 -- Next_Suitable_Statement --
2780 -----------------------------
2782 function Next_Suitable_Statement (Stmt : Node_Id) return Node_Id is
2783 Result : Node_Id;
2785 begin
2786 -- Skip call markers and Program_Error raises installed by the
2787 -- ABE mechanism.
2789 Result := Next (Stmt);
2790 while Present (Result) loop
2791 if not Nkind_In (Result, N_Call_Marker,
2792 N_Raise_Program_Error)
2793 then
2794 exit;
2795 end if;
2797 Result := Next (Result);
2798 end loop;
2800 return Result;
2801 end Next_Suitable_Statement;
2803 -- Local variables
2805 Call : Node_Id;
2806 Stmt : Node_Id;
2807 Stmt_2 : Node_Id;
2809 Deep_Init_Found : Boolean := False;
2810 -- A flag set when a call to [Deep_]Initialize has been found
2812 -- Start of processing for Find_Last_Init
2814 begin
2815 Last_Init := Decl;
2816 Body_Insert := Empty;
2818 -- Object renamings and objects associated with controlled
2819 -- function results do not require initialization.
2821 if Has_No_Init then
2822 return;
2823 end if;
2825 Stmt := Next_Suitable_Statement (Decl);
2827 -- For an object with suppressed initialization, we check whether
2828 -- there is in fact no initialization expression. If there is not,
2829 -- then this is an object declaration that has been turned into a
2830 -- different object declaration that calls the build-in-place
2831 -- function in a 'Reference attribute, as in "F(...)'Reference".
2832 -- We search for that later object declaration, so that the
2833 -- Inc_Decl will be inserted after the call. Otherwise, if the
2834 -- call raises an exception, we will finalize the (uninitialized)
2835 -- object, which is wrong.
2837 if No_Initialization (Decl) then
2838 if No (Expression (Last_Init)) then
2839 loop
2840 Last_Init := Next (Last_Init);
2841 exit when No (Last_Init);
2842 exit when Nkind (Last_Init) = N_Object_Declaration
2843 and then Nkind (Expression (Last_Init)) = N_Reference
2844 and then Nkind (Prefix (Expression (Last_Init))) =
2845 N_Function_Call
2846 and then Is_Expanded_Build_In_Place_Call
2847 (Prefix (Expression (Last_Init)));
2848 end loop;
2849 end if;
2851 return;
2853 -- In all other cases the initialization calls follow the related
2854 -- object. The general structure of object initialization built by
2855 -- routine Default_Initialize_Object is as follows:
2857 -- [begin -- aborts allowed
2858 -- Abort_Defer;]
2859 -- Type_Init_Proc (Obj);
2860 -- [begin] -- exceptions allowed
2861 -- Deep_Initialize (Obj);
2862 -- [exception -- exceptions allowed
2863 -- when others =>
2864 -- Deep_Finalize (Obj, Self => False);
2865 -- raise;
2866 -- end;]
2867 -- [at end -- aborts allowed
2868 -- Abort_Undefer;
2869 -- end;]
2871 -- When aborts are allowed, the initialization calls are housed
2872 -- within a block.
2874 elsif Nkind (Stmt) = N_Block_Statement then
2875 Last_Init := Find_Last_Init_In_Block (Stmt);
2876 Body_Insert := Stmt;
2878 -- Otherwise the initialization calls follow the related object
2880 else
2881 Stmt_2 := Next_Suitable_Statement (Stmt);
2883 -- Check for an optional call to Deep_Initialize which may
2884 -- appear within a block depending on whether the object has
2885 -- controlled components.
2887 if Present (Stmt_2) then
2888 if Nkind (Stmt_2) = N_Block_Statement then
2889 Call := Find_Last_Init_In_Block (Stmt_2);
2891 if Present (Call) then
2892 Deep_Init_Found := True;
2893 Last_Init := Call;
2894 Body_Insert := Stmt_2;
2895 end if;
2897 elsif Is_Init_Call (Stmt_2) then
2898 Deep_Init_Found := True;
2899 Last_Init := Stmt_2;
2900 Body_Insert := Last_Init;
2901 end if;
2902 end if;
2904 -- If the object lacks a call to Deep_Initialize, then it must
2905 -- have a call to its related type init proc.
2907 if not Deep_Init_Found and then Is_Init_Call (Stmt) then
2908 Last_Init := Stmt;
2909 Body_Insert := Last_Init;
2910 end if;
2911 end if;
2912 end Find_Last_Init;
2914 -- Local variables
2916 Body_Ins : Node_Id;
2917 Count_Ins : Node_Id;
2918 Fin_Call : Node_Id;
2919 Fin_Stmts : List_Id := No_List;
2920 Inc_Decl : Node_Id;
2921 Label : Node_Id;
2922 Label_Id : Entity_Id;
2923 Obj_Ref : Node_Id;
2925 -- Start of processing for Process_Object_Declaration
2927 begin
2928 -- Handle the object type and the reference to the object
2930 Obj_Ref := New_Occurrence_Of (Obj_Id, Loc);
2931 Obj_Typ := Base_Type (Etype (Obj_Id));
2933 loop
2934 if Is_Access_Type (Obj_Typ) then
2935 Obj_Typ := Directly_Designated_Type (Obj_Typ);
2936 Obj_Ref := Make_Explicit_Dereference (Loc, Obj_Ref);
2938 elsif Is_Concurrent_Type (Obj_Typ)
2939 and then Present (Corresponding_Record_Type (Obj_Typ))
2940 then
2941 Obj_Typ := Corresponding_Record_Type (Obj_Typ);
2942 Obj_Ref := Unchecked_Convert_To (Obj_Typ, Obj_Ref);
2944 elsif Is_Private_Type (Obj_Typ)
2945 and then Present (Full_View (Obj_Typ))
2946 then
2947 Obj_Typ := Full_View (Obj_Typ);
2948 Obj_Ref := Unchecked_Convert_To (Obj_Typ, Obj_Ref);
2950 elsif Obj_Typ /= Base_Type (Obj_Typ) then
2951 Obj_Typ := Base_Type (Obj_Typ);
2952 Obj_Ref := Unchecked_Convert_To (Obj_Typ, Obj_Ref);
2954 else
2955 exit;
2956 end if;
2957 end loop;
2959 Set_Etype (Obj_Ref, Obj_Typ);
2961 -- Handle the initialization type of the object declaration
2963 Init_Typ := Obj_Typ;
2964 loop
2965 if Is_Private_Type (Init_Typ)
2966 and then Present (Full_View (Init_Typ))
2967 then
2968 Init_Typ := Full_View (Init_Typ);
2970 elsif Is_Untagged_Derivation (Init_Typ) then
2971 Init_Typ := Root_Type (Init_Typ);
2973 else
2974 exit;
2975 end if;
2976 end loop;
2978 -- Set a new value for the state counter and insert the statement
2979 -- after the object declaration. Generate:
2981 -- Counter := <value>;
2983 Inc_Decl :=
2984 Make_Assignment_Statement (Loc,
2985 Name => New_Occurrence_Of (Counter_Id, Loc),
2986 Expression => Make_Integer_Literal (Loc, Counter_Val));
2988 -- Insert the counter after all initialization has been done. The
2989 -- place of insertion depends on the context.
2991 if Ekind_In (Obj_Id, E_Constant, E_Variable) then
2993 -- The object is initialized by a build-in-place function call.
2994 -- The counter insertion point is after the function call.
2996 if Present (BIP_Initialization_Call (Obj_Id)) then
2997 Count_Ins := BIP_Initialization_Call (Obj_Id);
2998 Body_Ins := Empty;
3000 -- The object is initialized by an aggregate. Insert the counter
3001 -- after the last aggregate assignment.
3003 elsif Present (Last_Aggregate_Assignment (Obj_Id)) then
3004 Count_Ins := Last_Aggregate_Assignment (Obj_Id);
3005 Body_Ins := Empty;
3007 -- In all other cases the counter is inserted after the last call
3008 -- to either [Deep_]Initialize or the type-specific init proc.
3010 else
3011 Find_Last_Init (Count_Ins, Body_Ins);
3012 end if;
3014 -- In all other cases the counter is inserted after the last call to
3015 -- either [Deep_]Initialize or the type-specific init proc.
3017 else
3018 Find_Last_Init (Count_Ins, Body_Ins);
3019 end if;
3021 -- If the Initialize function is null or trivial, the call will have
3022 -- been replaced with a null statement, in which case place counter
3023 -- declaration after object declaration itself.
3025 if No (Count_Ins) then
3026 Count_Ins := Decl;
3027 end if;
3029 Insert_After (Count_Ins, Inc_Decl);
3030 Analyze (Inc_Decl);
3032 -- If the current declaration is the last in the list, the finalizer
3033 -- body needs to be inserted after the set counter statement for the
3034 -- current object declaration. This is complicated by the fact that
3035 -- the set counter statement may appear in abort deferred block. In
3036 -- that case, the proper insertion place is after the block.
3038 if No (Finalizer_Insert_Nod) then
3040 -- Insertion after an abort deferred block
3042 if Present (Body_Ins) then
3043 Finalizer_Insert_Nod := Body_Ins;
3044 else
3045 Finalizer_Insert_Nod := Inc_Decl;
3046 end if;
3047 end if;
3049 -- Create the associated label with this object, generate:
3051 -- L<counter> : label;
3053 Label_Id :=
3054 Make_Identifier (Loc, New_External_Name ('L', Counter_Val));
3055 Set_Entity
3056 (Label_Id, Make_Defining_Identifier (Loc, Chars (Label_Id)));
3057 Label := Make_Label (Loc, Label_Id);
3059 Prepend_To (Finalizer_Decls,
3060 Make_Implicit_Label_Declaration (Loc,
3061 Defining_Identifier => Entity (Label_Id),
3062 Label_Construct => Label));
3064 -- Create the associated jump with this object, generate:
3066 -- when <counter> =>
3067 -- goto L<counter>;
3069 Prepend_To (Jump_Alts,
3070 Make_Case_Statement_Alternative (Loc,
3071 Discrete_Choices => New_List (
3072 Make_Integer_Literal (Loc, Counter_Val)),
3073 Statements => New_List (
3074 Make_Goto_Statement (Loc,
3075 Name => New_Occurrence_Of (Entity (Label_Id), Loc)))));
3077 -- Insert the jump destination, generate:
3079 -- <<L<counter>>>
3081 Append_To (Finalizer_Stmts, Label);
3083 -- Processing for simple protected objects. Such objects require
3084 -- manual finalization of their lock managers.
3086 if Is_Protected then
3087 if Is_Simple_Protected_Type (Obj_Typ) then
3088 Fin_Call := Cleanup_Protected_Object (Decl, Obj_Ref);
3090 if Present (Fin_Call) then
3091 Fin_Stmts := New_List (Fin_Call);
3092 end if;
3094 elsif Has_Simple_Protected_Object (Obj_Typ) then
3095 if Is_Record_Type (Obj_Typ) then
3096 Fin_Stmts := Cleanup_Record (Decl, Obj_Ref, Obj_Typ);
3097 elsif Is_Array_Type (Obj_Typ) then
3098 Fin_Stmts := Cleanup_Array (Decl, Obj_Ref, Obj_Typ);
3099 end if;
3100 end if;
3102 -- Generate:
3103 -- begin
3104 -- System.Tasking.Protected_Objects.Finalize_Protection
3105 -- (Obj._object);
3107 -- exception
3108 -- when others =>
3109 -- null;
3110 -- end;
3112 if Present (Fin_Stmts) and then Exceptions_OK then
3113 Fin_Stmts := New_List (
3114 Make_Block_Statement (Loc,
3115 Handled_Statement_Sequence =>
3116 Make_Handled_Sequence_Of_Statements (Loc,
3117 Statements => Fin_Stmts,
3119 Exception_Handlers => New_List (
3120 Make_Exception_Handler (Loc,
3121 Exception_Choices => New_List (
3122 Make_Others_Choice (Loc)),
3124 Statements => New_List (
3125 Make_Null_Statement (Loc)))))));
3126 end if;
3128 -- Processing for regular controlled objects
3130 else
3131 -- Generate:
3132 -- begin
3133 -- [Deep_]Finalize (Obj);
3135 -- exception
3136 -- when Id : others =>
3137 -- if not Raised then
3138 -- Raised := True;
3139 -- Save_Occurrence (E, Id);
3140 -- end if;
3141 -- end;
3143 Fin_Call :=
3144 Make_Final_Call (
3145 Obj_Ref => Obj_Ref,
3146 Typ => Obj_Typ);
3148 -- Guard against a missing [Deep_]Finalize when the object type
3149 -- was not properly frozen.
3151 if No (Fin_Call) then
3152 Fin_Call := Make_Null_Statement (Loc);
3153 end if;
3155 -- For CodePeer, the exception handlers normally generated here
3156 -- generate complex flowgraphs which result in capacity problems.
3157 -- Omitting these handlers for CodePeer is justified as follows:
3159 -- If a handler is dead, then omitting it is surely ok
3161 -- If a handler is live, then CodePeer should flag the
3162 -- potentially-exception-raising construct that causes it
3163 -- to be live. That is what we are interested in, not what
3164 -- happens after the exception is raised.
3166 if Exceptions_OK and not CodePeer_Mode then
3167 Fin_Stmts := New_List (
3168 Make_Block_Statement (Loc,
3169 Handled_Statement_Sequence =>
3170 Make_Handled_Sequence_Of_Statements (Loc,
3171 Statements => New_List (Fin_Call),
3173 Exception_Handlers => New_List (
3174 Build_Exception_Handler
3175 (Finalizer_Data, For_Package)))));
3177 -- When exception handlers are prohibited, the finalization call
3178 -- appears unprotected. Any exception raised during finalization
3179 -- will bypass the circuitry which ensures the cleanup of all
3180 -- remaining objects.
3182 else
3183 Fin_Stmts := New_List (Fin_Call);
3184 end if;
3186 -- If we are dealing with a return object of a build-in-place
3187 -- function, generate the following cleanup statements:
3189 -- if BIPallocfrom > Secondary_Stack'Pos
3190 -- and then BIPfinalizationmaster /= null
3191 -- then
3192 -- declare
3193 -- type Ptr_Typ is access Obj_Typ;
3194 -- for Ptr_Typ'Storage_Pool use
3195 -- Base_Pool (BIPfinalizationmaster.all).all;
3196 -- begin
3197 -- Free (Ptr_Typ (Temp));
3198 -- end;
3199 -- end if;
3201 -- The generated code effectively detaches the temporary from the
3202 -- caller finalization master and deallocates the object.
3204 if Is_Return_Object (Obj_Id) then
3205 declare
3206 Func_Id : constant Entity_Id := Enclosing_Function (Obj_Id);
3207 begin
3208 if Is_Build_In_Place_Function (Func_Id)
3209 and then Needs_BIP_Finalization_Master (Func_Id)
3210 then
3211 Append_To (Fin_Stmts, Build_BIP_Cleanup_Stmts (Func_Id));
3212 end if;
3213 end;
3214 end if;
3216 if Ekind_In (Obj_Id, E_Constant, E_Variable)
3217 and then Present (Status_Flag_Or_Transient_Decl (Obj_Id))
3218 then
3219 -- Temporaries created for the purpose of "exporting" a
3220 -- transient object out of an Expression_With_Actions (EWA)
3221 -- need guards. The following illustrates the usage of such
3222 -- temporaries.
3224 -- Access_Typ : access [all] Obj_Typ;
3225 -- Temp : Access_Typ := null;
3226 -- <Counter> := ...;
3228 -- do
3229 -- Ctrl_Trans : [access [all]] Obj_Typ := ...;
3230 -- Temp := Access_Typ (Ctrl_Trans); -- when a pointer
3231 -- <or>
3232 -- Temp := Ctrl_Trans'Unchecked_Access;
3233 -- in ... end;
3235 -- The finalization machinery does not process EWA nodes as
3236 -- this may lead to premature finalization of expressions. Note
3237 -- that Temp is marked as being properly initialized regardless
3238 -- of whether the initialization of Ctrl_Trans succeeded. Since
3239 -- a failed initialization may leave Temp with a value of null,
3240 -- add a guard to handle this case:
3242 -- if Obj /= null then
3243 -- <object finalization statements>
3244 -- end if;
3246 if Nkind (Status_Flag_Or_Transient_Decl (Obj_Id)) =
3247 N_Object_Declaration
3248 then
3249 Fin_Stmts := New_List (
3250 Make_If_Statement (Loc,
3251 Condition =>
3252 Make_Op_Ne (Loc,
3253 Left_Opnd => New_Occurrence_Of (Obj_Id, Loc),
3254 Right_Opnd => Make_Null (Loc)),
3255 Then_Statements => Fin_Stmts));
3257 -- Return objects use a flag to aid in processing their
3258 -- potential finalization when the enclosing function fails
3259 -- to return properly. Generate:
3261 -- if not Flag then
3262 -- <object finalization statements>
3263 -- end if;
3265 else
3266 Fin_Stmts := New_List (
3267 Make_If_Statement (Loc,
3268 Condition =>
3269 Make_Op_Not (Loc,
3270 Right_Opnd =>
3271 New_Occurrence_Of
3272 (Status_Flag_Or_Transient_Decl (Obj_Id), Loc)),
3274 Then_Statements => Fin_Stmts));
3275 end if;
3276 end if;
3277 end if;
3279 Append_List_To (Finalizer_Stmts, Fin_Stmts);
3281 -- Since the declarations are examined in reverse, the state counter
3282 -- must be decremented in order to keep with the true position of
3283 -- objects.
3285 Counter_Val := Counter_Val - 1;
3286 end Process_Object_Declaration;
3288 -------------------------------------
3289 -- Process_Tagged_Type_Declaration --
3290 -------------------------------------
3292 procedure Process_Tagged_Type_Declaration (Decl : Node_Id) is
3293 Typ : constant Entity_Id := Defining_Identifier (Decl);
3294 DT_Ptr : constant Entity_Id :=
3295 Node (First_Elmt (Access_Disp_Table (Typ)));
3296 begin
3297 -- Generate:
3298 -- Ada.Tags.Unregister_Tag (<Typ>P);
3300 Append_To (Tagged_Type_Stmts,
3301 Make_Procedure_Call_Statement (Loc,
3302 Name =>
3303 New_Occurrence_Of (RTE (RE_Unregister_Tag), Loc),
3304 Parameter_Associations => New_List (
3305 New_Occurrence_Of (DT_Ptr, Loc))));
3306 end Process_Tagged_Type_Declaration;
3308 -- Start of processing for Build_Finalizer
3310 begin
3311 Fin_Id := Empty;
3313 -- Do not perform this expansion in SPARK mode because it is not
3314 -- necessary.
3316 if GNATprove_Mode then
3317 return;
3318 end if;
3320 -- Step 1: Extract all lists which may contain controlled objects or
3321 -- library-level tagged types.
3323 if For_Package_Spec then
3324 Decls := Visible_Declarations (Specification (N));
3325 Priv_Decls := Private_Declarations (Specification (N));
3327 -- Retrieve the package spec id
3329 Spec_Id := Defining_Unit_Name (Specification (N));
3331 if Nkind (Spec_Id) = N_Defining_Program_Unit_Name then
3332 Spec_Id := Defining_Identifier (Spec_Id);
3333 end if;
3335 -- Accept statement, block, entry body, package body, protected body,
3336 -- subprogram body or task body.
3338 else
3339 Decls := Declarations (N);
3340 HSS := Handled_Statement_Sequence (N);
3342 if Present (HSS) then
3343 if Present (Statements (HSS)) then
3344 Stmts := Statements (HSS);
3345 end if;
3347 if Present (At_End_Proc (HSS)) then
3348 Prev_At_End := At_End_Proc (HSS);
3349 end if;
3350 end if;
3352 -- Retrieve the package spec id for package bodies
3354 if For_Package_Body then
3355 Spec_Id := Corresponding_Spec (N);
3356 end if;
3357 end if;
3359 -- Do not process nested packages since those are handled by the
3360 -- enclosing scope's finalizer. Do not process non-expanded package
3361 -- instantiations since those will be re-analyzed and re-expanded.
3363 if For_Package
3364 and then
3365 (not Is_Library_Level_Entity (Spec_Id)
3367 -- Nested packages are considered to be library level entities,
3368 -- but do not need to be processed separately. True library level
3369 -- packages have a scope value of 1.
3371 or else Scope_Depth_Value (Spec_Id) /= Uint_1
3372 or else (Is_Generic_Instance (Spec_Id)
3373 and then Package_Instantiation (Spec_Id) /= N))
3374 then
3375 return;
3376 end if;
3378 -- Step 2: Object [pre]processing
3380 if For_Package then
3382 -- Preprocess the visible declarations now in order to obtain the
3383 -- correct number of controlled object by the time the private
3384 -- declarations are processed.
3386 Process_Declarations (Decls, Preprocess => True, Top_Level => True);
3388 -- From all the possible contexts, only package specifications may
3389 -- have private declarations.
3391 if For_Package_Spec then
3392 Process_Declarations
3393 (Priv_Decls, Preprocess => True, Top_Level => True);
3394 end if;
3396 -- The current context may lack controlled objects, but require some
3397 -- other form of completion (task termination for instance). In such
3398 -- cases, the finalizer must be created and carry the additional
3399 -- statements.
3401 if Acts_As_Clean or Has_Ctrl_Objs or Has_Tagged_Types then
3402 Build_Components;
3403 end if;
3405 -- The preprocessing has determined that the context has controlled
3406 -- objects or library-level tagged types.
3408 if Has_Ctrl_Objs or Has_Tagged_Types then
3410 -- Private declarations are processed first in order to preserve
3411 -- possible dependencies between public and private objects.
3413 if For_Package_Spec then
3414 Process_Declarations (Priv_Decls);
3415 end if;
3417 Process_Declarations (Decls);
3418 end if;
3420 -- Non-package case
3422 else
3423 -- Preprocess both declarations and statements
3425 Process_Declarations (Decls, Preprocess => True, Top_Level => True);
3426 Process_Declarations (Stmts, Preprocess => True, Top_Level => True);
3428 -- At this point it is known that N has controlled objects. Ensure
3429 -- that N has a declarative list since the finalizer spec will be
3430 -- attached to it.
3432 if Has_Ctrl_Objs and then No (Decls) then
3433 Set_Declarations (N, New_List);
3434 Decls := Declarations (N);
3435 Spec_Decls := Decls;
3436 end if;
3438 -- The current context may lack controlled objects, but require some
3439 -- other form of completion (task termination for instance). In such
3440 -- cases, the finalizer must be created and carry the additional
3441 -- statements.
3443 if Acts_As_Clean or Has_Ctrl_Objs or Has_Tagged_Types then
3444 Build_Components;
3445 end if;
3447 if Has_Ctrl_Objs or Has_Tagged_Types then
3448 Process_Declarations (Stmts);
3449 Process_Declarations (Decls);
3450 end if;
3451 end if;
3453 -- Step 3: Finalizer creation
3455 if Acts_As_Clean or Has_Ctrl_Objs or Has_Tagged_Types then
3456 Create_Finalizer;
3457 end if;
3458 end Build_Finalizer;
3460 --------------------------
3461 -- Build_Finalizer_Call --
3462 --------------------------
3464 procedure Build_Finalizer_Call (N : Node_Id; Fin_Id : Entity_Id) is
3465 Is_Prot_Body : constant Boolean :=
3466 Nkind (N) = N_Subprogram_Body
3467 and then Is_Protected_Subprogram_Body (N);
3468 -- Determine whether N denotes the protected version of a subprogram
3469 -- which belongs to a protected type.
3471 Loc : constant Source_Ptr := Sloc (N);
3472 HSS : Node_Id;
3474 begin
3475 -- Do not perform this expansion in SPARK mode because we do not create
3476 -- finalizers in the first place.
3478 if GNATprove_Mode then
3479 return;
3480 end if;
3482 -- The At_End handler should have been assimilated by the finalizer
3484 HSS := Handled_Statement_Sequence (N);
3485 pragma Assert (No (At_End_Proc (HSS)));
3487 -- If the construct to be cleaned up is a protected subprogram body, the
3488 -- finalizer call needs to be associated with the block which wraps the
3489 -- unprotected version of the subprogram. The following illustrates this
3490 -- scenario:
3492 -- procedure Prot_SubpP is
3493 -- procedure finalizer is
3494 -- begin
3495 -- Service_Entries (Prot_Obj);
3496 -- Abort_Undefer;
3497 -- end finalizer;
3499 -- begin
3500 -- . . .
3501 -- begin
3502 -- Prot_SubpN (Prot_Obj);
3503 -- at end
3504 -- finalizer;
3505 -- end;
3506 -- end Prot_SubpP;
3508 if Is_Prot_Body then
3509 HSS := Handled_Statement_Sequence (Last (Statements (HSS)));
3511 -- An At_End handler and regular exception handlers cannot coexist in
3512 -- the same statement sequence. Wrap the original statements in a block.
3514 elsif Present (Exception_Handlers (HSS)) then
3515 declare
3516 End_Lab : constant Node_Id := End_Label (HSS);
3517 Block : Node_Id;
3519 begin
3520 Block :=
3521 Make_Block_Statement (Loc, Handled_Statement_Sequence => HSS);
3523 Set_Handled_Statement_Sequence (N,
3524 Make_Handled_Sequence_Of_Statements (Loc, New_List (Block)));
3526 HSS := Handled_Statement_Sequence (N);
3527 Set_End_Label (HSS, End_Lab);
3528 end;
3529 end if;
3531 Set_At_End_Proc (HSS, New_Occurrence_Of (Fin_Id, Loc));
3533 -- Attach reference to finalizer to tree, for LLVM use
3535 Set_Parent (At_End_Proc (HSS), HSS);
3537 Analyze (At_End_Proc (HSS));
3538 Expand_At_End_Handler (HSS, Empty);
3539 end Build_Finalizer_Call;
3541 ---------------------
3542 -- Build_Late_Proc --
3543 ---------------------
3545 procedure Build_Late_Proc (Typ : Entity_Id; Nam : Name_Id) is
3546 begin
3547 for Final_Prim in Name_Of'Range loop
3548 if Name_Of (Final_Prim) = Nam then
3549 Set_TSS (Typ,
3550 Make_Deep_Proc
3551 (Prim => Final_Prim,
3552 Typ => Typ,
3553 Stmts => Make_Deep_Record_Body (Final_Prim, Typ)));
3554 end if;
3555 end loop;
3556 end Build_Late_Proc;
3558 -------------------------------
3559 -- Build_Object_Declarations --
3560 -------------------------------
3562 procedure Build_Object_Declarations
3563 (Data : out Finalization_Exception_Data;
3564 Decls : List_Id;
3565 Loc : Source_Ptr;
3566 For_Package : Boolean := False)
3568 Decl : Node_Id;
3570 Dummy : Entity_Id;
3571 -- This variable captures an unused dummy internal entity, see the
3572 -- comment associated with its use.
3574 begin
3575 pragma Assert (Decls /= No_List);
3577 -- Always set the proper location as it may be needed even when
3578 -- exception propagation is forbidden.
3580 Data.Loc := Loc;
3582 if Restriction_Active (No_Exception_Propagation) then
3583 Data.Abort_Id := Empty;
3584 Data.E_Id := Empty;
3585 Data.Raised_Id := Empty;
3586 return;
3587 end if;
3589 Data.Raised_Id := Make_Temporary (Loc, 'R');
3591 -- In certain scenarios, finalization can be triggered by an abort. If
3592 -- the finalization itself fails and raises an exception, the resulting
3593 -- Program_Error must be supressed and replaced by an abort signal. In
3594 -- order to detect this scenario, save the state of entry into the
3595 -- finalization code.
3597 -- This is not needed for library-level finalizers as they are called by
3598 -- the environment task and cannot be aborted.
3600 if not For_Package then
3601 if Abort_Allowed then
3602 Data.Abort_Id := Make_Temporary (Loc, 'A');
3604 -- Generate:
3605 -- Abort_Id : constant Boolean := <A_Expr>;
3607 Append_To (Decls,
3608 Make_Object_Declaration (Loc,
3609 Defining_Identifier => Data.Abort_Id,
3610 Constant_Present => True,
3611 Object_Definition =>
3612 New_Occurrence_Of (Standard_Boolean, Loc),
3613 Expression =>
3614 New_Occurrence_Of (RTE (RE_Triggered_By_Abort), Loc)));
3616 -- Abort is not required
3618 else
3619 -- Generate a dummy entity to ensure that the internal symbols are
3620 -- in sync when a unit is compiled with and without aborts.
3622 Dummy := Make_Temporary (Loc, 'A');
3623 Data.Abort_Id := Empty;
3624 end if;
3626 -- Library-level finalizers
3628 else
3629 Data.Abort_Id := Empty;
3630 end if;
3632 if Exception_Extra_Info then
3633 Data.E_Id := Make_Temporary (Loc, 'E');
3635 -- Generate:
3636 -- E_Id : Exception_Occurrence;
3638 Decl :=
3639 Make_Object_Declaration (Loc,
3640 Defining_Identifier => Data.E_Id,
3641 Object_Definition =>
3642 New_Occurrence_Of (RTE (RE_Exception_Occurrence), Loc));
3643 Set_No_Initialization (Decl);
3645 Append_To (Decls, Decl);
3647 else
3648 Data.E_Id := Empty;
3649 end if;
3651 -- Generate:
3652 -- Raised_Id : Boolean := False;
3654 Append_To (Decls,
3655 Make_Object_Declaration (Loc,
3656 Defining_Identifier => Data.Raised_Id,
3657 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
3658 Expression => New_Occurrence_Of (Standard_False, Loc)));
3659 end Build_Object_Declarations;
3661 ---------------------------
3662 -- Build_Raise_Statement --
3663 ---------------------------
3665 function Build_Raise_Statement
3666 (Data : Finalization_Exception_Data) return Node_Id
3668 Stmt : Node_Id;
3669 Expr : Node_Id;
3671 begin
3672 -- Standard run-time use the specialized routine
3673 -- Raise_From_Controlled_Operation.
3675 if Exception_Extra_Info
3676 and then RTE_Available (RE_Raise_From_Controlled_Operation)
3677 then
3678 Stmt :=
3679 Make_Procedure_Call_Statement (Data.Loc,
3680 Name =>
3681 New_Occurrence_Of
3682 (RTE (RE_Raise_From_Controlled_Operation), Data.Loc),
3683 Parameter_Associations =>
3684 New_List (New_Occurrence_Of (Data.E_Id, Data.Loc)));
3686 -- Restricted run-time: exception messages are not supported and hence
3687 -- Raise_From_Controlled_Operation is not supported. Raise Program_Error
3688 -- instead.
3690 else
3691 Stmt :=
3692 Make_Raise_Program_Error (Data.Loc,
3693 Reason => PE_Finalize_Raised_Exception);
3694 end if;
3696 -- Generate:
3698 -- Raised_Id and then not Abort_Id
3699 -- <or>
3700 -- Raised_Id
3702 Expr := New_Occurrence_Of (Data.Raised_Id, Data.Loc);
3704 if Present (Data.Abort_Id) then
3705 Expr := Make_And_Then (Data.Loc,
3706 Left_Opnd => Expr,
3707 Right_Opnd =>
3708 Make_Op_Not (Data.Loc,
3709 Right_Opnd => New_Occurrence_Of (Data.Abort_Id, Data.Loc)));
3710 end if;
3712 -- Generate:
3714 -- if Raised_Id and then not Abort_Id then
3715 -- Raise_From_Controlled_Operation (E_Id);
3716 -- <or>
3717 -- raise Program_Error; -- restricted runtime
3718 -- end if;
3720 return
3721 Make_If_Statement (Data.Loc,
3722 Condition => Expr,
3723 Then_Statements => New_List (Stmt));
3724 end Build_Raise_Statement;
3726 -----------------------------
3727 -- Build_Record_Deep_Procs --
3728 -----------------------------
3730 procedure Build_Record_Deep_Procs (Typ : Entity_Id) is
3731 begin
3732 Set_TSS (Typ,
3733 Make_Deep_Proc
3734 (Prim => Initialize_Case,
3735 Typ => Typ,
3736 Stmts => Make_Deep_Record_Body (Initialize_Case, Typ)));
3738 if not Is_Limited_View (Typ) then
3739 Set_TSS (Typ,
3740 Make_Deep_Proc
3741 (Prim => Adjust_Case,
3742 Typ => Typ,
3743 Stmts => Make_Deep_Record_Body (Adjust_Case, Typ)));
3744 end if;
3746 -- Do not generate Deep_Finalize and Finalize_Address if finalization is
3747 -- suppressed since these routine will not be used.
3749 if not Restriction_Active (No_Finalization) then
3750 Set_TSS (Typ,
3751 Make_Deep_Proc
3752 (Prim => Finalize_Case,
3753 Typ => Typ,
3754 Stmts => Make_Deep_Record_Body (Finalize_Case, Typ)));
3756 -- Create TSS primitive Finalize_Address (unless CodePeer_Mode)
3758 if not CodePeer_Mode then
3759 Set_TSS (Typ,
3760 Make_Deep_Proc
3761 (Prim => Address_Case,
3762 Typ => Typ,
3763 Stmts => Make_Deep_Record_Body (Address_Case, Typ)));
3764 end if;
3765 end if;
3766 end Build_Record_Deep_Procs;
3768 -------------------
3769 -- Cleanup_Array --
3770 -------------------
3772 function Cleanup_Array
3773 (N : Node_Id;
3774 Obj : Node_Id;
3775 Typ : Entity_Id) return List_Id
3777 Loc : constant Source_Ptr := Sloc (N);
3778 Index_List : constant List_Id := New_List;
3780 function Free_Component return List_Id;
3781 -- Generate the code to finalize the task or protected subcomponents
3782 -- of a single component of the array.
3784 function Free_One_Dimension (Dim : Int) return List_Id;
3785 -- Generate a loop over one dimension of the array
3787 --------------------
3788 -- Free_Component --
3789 --------------------
3791 function Free_Component return List_Id is
3792 Stmts : List_Id := New_List;
3793 Tsk : Node_Id;
3794 C_Typ : constant Entity_Id := Component_Type (Typ);
3796 begin
3797 -- Component type is known to contain tasks or protected objects
3799 Tsk :=
3800 Make_Indexed_Component (Loc,
3801 Prefix => Duplicate_Subexpr_No_Checks (Obj),
3802 Expressions => Index_List);
3804 Set_Etype (Tsk, C_Typ);
3806 if Is_Task_Type (C_Typ) then
3807 Append_To (Stmts, Cleanup_Task (N, Tsk));
3809 elsif Is_Simple_Protected_Type (C_Typ) then
3810 Append_To (Stmts, Cleanup_Protected_Object (N, Tsk));
3812 elsif Is_Record_Type (C_Typ) then
3813 Stmts := Cleanup_Record (N, Tsk, C_Typ);
3815 elsif Is_Array_Type (C_Typ) then
3816 Stmts := Cleanup_Array (N, Tsk, C_Typ);
3817 end if;
3819 return Stmts;
3820 end Free_Component;
3822 ------------------------
3823 -- Free_One_Dimension --
3824 ------------------------
3826 function Free_One_Dimension (Dim : Int) return List_Id is
3827 Index : Entity_Id;
3829 begin
3830 if Dim > Number_Dimensions (Typ) then
3831 return Free_Component;
3833 -- Here we generate the required loop
3835 else
3836 Index := Make_Temporary (Loc, 'J');
3837 Append (New_Occurrence_Of (Index, Loc), Index_List);
3839 return New_List (
3840 Make_Implicit_Loop_Statement (N,
3841 Identifier => Empty,
3842 Iteration_Scheme =>
3843 Make_Iteration_Scheme (Loc,
3844 Loop_Parameter_Specification =>
3845 Make_Loop_Parameter_Specification (Loc,
3846 Defining_Identifier => Index,
3847 Discrete_Subtype_Definition =>
3848 Make_Attribute_Reference (Loc,
3849 Prefix => Duplicate_Subexpr (Obj),
3850 Attribute_Name => Name_Range,
3851 Expressions => New_List (
3852 Make_Integer_Literal (Loc, Dim))))),
3853 Statements => Free_One_Dimension (Dim + 1)));
3854 end if;
3855 end Free_One_Dimension;
3857 -- Start of processing for Cleanup_Array
3859 begin
3860 return Free_One_Dimension (1);
3861 end Cleanup_Array;
3863 --------------------
3864 -- Cleanup_Record --
3865 --------------------
3867 function Cleanup_Record
3868 (N : Node_Id;
3869 Obj : Node_Id;
3870 Typ : Entity_Id) return List_Id
3872 Loc : constant Source_Ptr := Sloc (N);
3873 Tsk : Node_Id;
3874 Comp : Entity_Id;
3875 Stmts : constant List_Id := New_List;
3876 U_Typ : constant Entity_Id := Underlying_Type (Typ);
3878 begin
3879 if Has_Discriminants (U_Typ)
3880 and then Nkind (Parent (U_Typ)) = N_Full_Type_Declaration
3881 and then Nkind (Type_Definition (Parent (U_Typ))) = N_Record_Definition
3882 and then
3883 Present
3884 (Variant_Part (Component_List (Type_Definition (Parent (U_Typ)))))
3885 then
3886 -- For now, do not attempt to free a component that may appear in a
3887 -- variant, and instead issue a warning. Doing this "properly" would
3888 -- require building a case statement and would be quite a mess. Note
3889 -- that the RM only requires that free "work" for the case of a task
3890 -- access value, so already we go way beyond this in that we deal
3891 -- with the array case and non-discriminated record cases.
3893 Error_Msg_N
3894 ("task/protected object in variant record will not be freed??", N);
3895 return New_List (Make_Null_Statement (Loc));
3896 end if;
3898 Comp := First_Component (Typ);
3899 while Present (Comp) loop
3900 if Has_Task (Etype (Comp))
3901 or else Has_Simple_Protected_Object (Etype (Comp))
3902 then
3903 Tsk :=
3904 Make_Selected_Component (Loc,
3905 Prefix => Duplicate_Subexpr_No_Checks (Obj),
3906 Selector_Name => New_Occurrence_Of (Comp, Loc));
3907 Set_Etype (Tsk, Etype (Comp));
3909 if Is_Task_Type (Etype (Comp)) then
3910 Append_To (Stmts, Cleanup_Task (N, Tsk));
3912 elsif Is_Simple_Protected_Type (Etype (Comp)) then
3913 Append_To (Stmts, Cleanup_Protected_Object (N, Tsk));
3915 elsif Is_Record_Type (Etype (Comp)) then
3917 -- Recurse, by generating the prefix of the argument to
3918 -- the eventual cleanup call.
3920 Append_List_To (Stmts, Cleanup_Record (N, Tsk, Etype (Comp)));
3922 elsif Is_Array_Type (Etype (Comp)) then
3923 Append_List_To (Stmts, Cleanup_Array (N, Tsk, Etype (Comp)));
3924 end if;
3925 end if;
3927 Next_Component (Comp);
3928 end loop;
3930 return Stmts;
3931 end Cleanup_Record;
3933 ------------------------------
3934 -- Cleanup_Protected_Object --
3935 ------------------------------
3937 function Cleanup_Protected_Object
3938 (N : Node_Id;
3939 Ref : Node_Id) return Node_Id
3941 Loc : constant Source_Ptr := Sloc (N);
3943 begin
3944 -- For restricted run-time libraries (Ravenscar), tasks are
3945 -- non-terminating, and protected objects can only appear at library
3946 -- level, so we do not want finalization of protected objects.
3948 if Restricted_Profile then
3949 return Empty;
3951 else
3952 return
3953 Make_Procedure_Call_Statement (Loc,
3954 Name =>
3955 New_Occurrence_Of (RTE (RE_Finalize_Protection), Loc),
3956 Parameter_Associations => New_List (Concurrent_Ref (Ref)));
3957 end if;
3958 end Cleanup_Protected_Object;
3960 ------------------
3961 -- Cleanup_Task --
3962 ------------------
3964 function Cleanup_Task
3965 (N : Node_Id;
3966 Ref : Node_Id) return Node_Id
3968 Loc : constant Source_Ptr := Sloc (N);
3970 begin
3971 -- For restricted run-time libraries (Ravenscar), tasks are
3972 -- non-terminating and they can only appear at library level,
3973 -- so we do not want finalization of task objects.
3975 if Restricted_Profile then
3976 return Empty;
3978 else
3979 return
3980 Make_Procedure_Call_Statement (Loc,
3981 Name =>
3982 New_Occurrence_Of (RTE (RE_Free_Task), Loc),
3983 Parameter_Associations => New_List (Concurrent_Ref (Ref)));
3984 end if;
3985 end Cleanup_Task;
3987 --------------------------------------
3988 -- Check_Unnesting_Elaboration_Code --
3989 --------------------------------------
3991 procedure Check_Unnesting_Elaboration_Code (N : Node_Id) is
3992 Loc : constant Source_Ptr := Sloc (N);
3994 function Contains_Subprogram (Blk : Entity_Id) return Boolean;
3995 -- Check recursively whether a loop or block contains a subprogram that
3996 -- may need an activation record.
3998 function First_Local_Scope (L : List_Id) return Entity_Id;
3999 -- Find first block or loop that contains a subprogram and is not itself
4000 -- nested within another local scope.
4002 --------------------------
4003 -- Contains_Subprogram --
4004 --------------------------
4006 function Contains_Subprogram (Blk : Entity_Id) return Boolean is
4007 E : Entity_Id;
4009 begin
4010 E := First_Entity (Blk);
4012 while Present (E) loop
4013 if Is_Subprogram (E) then
4014 return True;
4016 elsif Ekind_In (E, E_Block, E_Loop)
4017 and then Contains_Subprogram (E)
4018 then
4019 return True;
4020 end if;
4022 Next_Entity (E);
4023 end loop;
4025 return False;
4026 end Contains_Subprogram;
4028 -----------------------
4029 -- Find_Local_Scope --
4030 -----------------------
4032 function First_Local_Scope (L : List_Id) return Entity_Id is
4033 Scop : Entity_Id;
4034 Stat : Node_Id;
4036 begin
4037 Stat := First (L);
4038 while Present (Stat) loop
4039 case Nkind (Stat) is
4040 when N_Block_Statement =>
4041 if Present (Identifier (Stat)) then
4042 return Entity (Identifier (Stat));
4043 end if;
4045 when N_Loop_Statement =>
4046 if Contains_Subprogram (Entity (Identifier (Stat))) then
4047 return Entity (Identifier (Stat));
4048 end if;
4050 when N_If_Statement =>
4051 Scop := First_Local_Scope (Then_Statements (Stat));
4053 if Present (Scop) then
4054 return Scop;
4055 end if;
4057 Scop := First_Local_Scope (Else_Statements (Stat));
4059 if Present (Scop) then
4060 return Scop;
4061 end if;
4063 declare
4064 Elif : Node_Id;
4065 begin
4066 Elif := First (Elsif_Parts (Stat));
4068 while Present (Elif) loop
4069 Scop := First_Local_Scope (Statements (Elif));
4071 if Present (Scop) then
4072 return Scop;
4073 end if;
4075 Next (Elif);
4076 end loop;
4077 end;
4079 when N_Case_Statement =>
4080 declare
4081 Alt : Node_Id;
4082 begin
4083 Alt := First (Alternatives (Stat));
4085 while Present (Alt) loop
4086 Scop := First_Local_Scope (Statements (Alt));
4088 if Present (Scop) then
4089 return Scop;
4090 end if;
4092 Next (Alt);
4093 end loop;
4094 end;
4096 when N_Subprogram_Body =>
4097 return Defining_Entity (Stat);
4099 when others =>
4100 null;
4101 end case;
4103 Next (Stat);
4104 end loop;
4106 return Empty;
4107 end First_Local_Scope;
4109 -- Local variables
4111 Elab_Body : Node_Id;
4112 Elab_Call : Node_Id;
4113 Elab_Proc : Entity_Id;
4114 Ent : Entity_Id;
4116 -- Start of processing for Check_Unnesting_Elaboration_Code
4118 begin
4119 if Unnest_Subprogram_Mode
4120 and then Present (Handled_Statement_Sequence (N))
4121 and then Is_Compilation_Unit (Current_Scope)
4122 then
4123 Ent :=
4124 First_Local_Scope (Statements (Handled_Statement_Sequence (N)));
4126 if Present (Ent) then
4127 Elab_Proc :=
4128 Make_Defining_Identifier (Loc,
4129 Chars => New_Internal_Name ('I'));
4131 Elab_Body :=
4132 Make_Subprogram_Body (Loc,
4133 Specification =>
4134 Make_Procedure_Specification (Loc,
4135 Defining_Unit_Name => Elab_Proc),
4136 Declarations => New_List,
4137 Handled_Statement_Sequence =>
4138 Relocate_Node (Handled_Statement_Sequence (N)));
4140 Elab_Call :=
4141 Make_Procedure_Call_Statement (Loc,
4142 Name => New_Occurrence_Of (Elab_Proc, Loc));
4144 Append_To (Declarations (N), Elab_Body);
4145 Analyze (Elab_Body);
4146 Set_Has_Nested_Subprogram (Elab_Proc);
4148 Set_Handled_Statement_Sequence (N,
4149 Make_Handled_Sequence_Of_Statements (Loc,
4150 Statements => New_List (Elab_Call)));
4152 Analyze (Elab_Call);
4154 -- The scope of all blocks and loops in the elaboration code is
4155 -- now the constructed elaboration procedure. Nested subprograms
4156 -- within those blocks will have activation records if they
4157 -- contain references to entities in the enclosing block.
4159 while Present (Ent) loop
4160 Set_Scope (Ent, Elab_Proc);
4161 Next_Entity (Ent);
4162 end loop;
4163 end if;
4164 end if;
4165 end Check_Unnesting_Elaboration_Code;
4167 ------------------------------
4168 -- Check_Visibly_Controlled --
4169 ------------------------------
4171 procedure Check_Visibly_Controlled
4172 (Prim : Final_Primitives;
4173 Typ : Entity_Id;
4174 E : in out Entity_Id;
4175 Cref : in out Node_Id)
4177 Parent_Type : Entity_Id;
4178 Op : Entity_Id;
4180 begin
4181 if Is_Derived_Type (Typ)
4182 and then Comes_From_Source (E)
4183 and then not Present (Overridden_Operation (E))
4184 then
4185 -- We know that the explicit operation on the type does not override
4186 -- the inherited operation of the parent, and that the derivation
4187 -- is from a private type that is not visibly controlled.
4189 Parent_Type := Etype (Typ);
4190 Op := Find_Optional_Prim_Op (Parent_Type, Name_Of (Prim));
4192 if Present (Op) then
4193 E := Op;
4195 -- Wrap the object to be initialized into the proper
4196 -- unchecked conversion, to be compatible with the operation
4197 -- to be called.
4199 if Nkind (Cref) = N_Unchecked_Type_Conversion then
4200 Cref := Unchecked_Convert_To (Parent_Type, Expression (Cref));
4201 else
4202 Cref := Unchecked_Convert_To (Parent_Type, Cref);
4203 end if;
4204 end if;
4205 end if;
4206 end Check_Visibly_Controlled;
4208 ------------------
4209 -- Convert_View --
4210 ------------------
4212 function Convert_View
4213 (Proc : Entity_Id;
4214 Arg : Node_Id;
4215 Ind : Pos := 1) return Node_Id
4217 Fent : Entity_Id := First_Entity (Proc);
4218 Ftyp : Entity_Id;
4219 Atyp : Entity_Id;
4221 begin
4222 for J in 2 .. Ind loop
4223 Next_Entity (Fent);
4224 end loop;
4226 Ftyp := Etype (Fent);
4228 if Nkind_In (Arg, N_Type_Conversion, N_Unchecked_Type_Conversion) then
4229 Atyp := Entity (Subtype_Mark (Arg));
4230 else
4231 Atyp := Etype (Arg);
4232 end if;
4234 if Is_Abstract_Subprogram (Proc) and then Is_Tagged_Type (Ftyp) then
4235 return Unchecked_Convert_To (Class_Wide_Type (Ftyp), Arg);
4237 elsif Ftyp /= Atyp
4238 and then Present (Atyp)
4239 and then (Is_Private_Type (Ftyp) or else Is_Private_Type (Atyp))
4240 and then Base_Type (Underlying_Type (Atyp)) =
4241 Base_Type (Underlying_Type (Ftyp))
4242 then
4243 return Unchecked_Convert_To (Ftyp, Arg);
4245 -- If the argument is already a conversion, as generated by
4246 -- Make_Init_Call, set the target type to the type of the formal
4247 -- directly, to avoid spurious typing problems.
4249 elsif Nkind_In (Arg, N_Unchecked_Type_Conversion, N_Type_Conversion)
4250 and then not Is_Class_Wide_Type (Atyp)
4251 then
4252 Set_Subtype_Mark (Arg, New_Occurrence_Of (Ftyp, Sloc (Arg)));
4253 Set_Etype (Arg, Ftyp);
4254 return Arg;
4256 -- Otherwise, introduce a conversion when the designated object
4257 -- has a type derived from the formal of the controlled routine.
4259 elsif Is_Private_Type (Ftyp)
4260 and then Present (Atyp)
4261 and then Is_Derived_Type (Underlying_Type (Base_Type (Atyp)))
4262 then
4263 return Unchecked_Convert_To (Ftyp, Arg);
4265 else
4266 return Arg;
4267 end if;
4268 end Convert_View;
4270 -------------------------------
4271 -- CW_Or_Has_Controlled_Part --
4272 -------------------------------
4274 function CW_Or_Has_Controlled_Part (T : Entity_Id) return Boolean is
4275 begin
4276 return Is_Class_Wide_Type (T) or else Needs_Finalization (T);
4277 end CW_Or_Has_Controlled_Part;
4279 ------------------------
4280 -- Enclosing_Function --
4281 ------------------------
4283 function Enclosing_Function (E : Entity_Id) return Entity_Id is
4284 Func_Id : Entity_Id;
4286 begin
4287 Func_Id := E;
4288 while Present (Func_Id) and then Func_Id /= Standard_Standard loop
4289 if Ekind (Func_Id) = E_Function then
4290 return Func_Id;
4291 end if;
4293 Func_Id := Scope (Func_Id);
4294 end loop;
4296 return Empty;
4297 end Enclosing_Function;
4299 -------------------------------
4300 -- Establish_Transient_Scope --
4301 -------------------------------
4303 -- This procedure is called each time a transient block has to be inserted
4304 -- that is to say for each call to a function with unconstrained or tagged
4305 -- result. It creates a new scope on the scope stack in order to enclose
4306 -- all transient variables generated.
4308 procedure Establish_Transient_Scope
4309 (N : Node_Id;
4310 Manage_Sec_Stack : Boolean)
4312 procedure Create_Transient_Scope (Constr : Node_Id);
4313 -- Place a new scope on the scope stack in order to service construct
4314 -- Constr. The new scope may also manage the secondary stack.
4316 procedure Delegate_Sec_Stack_Management;
4317 -- Move the management of the secondary stack to the nearest enclosing
4318 -- suitable scope.
4320 function Find_Enclosing_Transient_Scope return Entity_Id;
4321 -- Examine the scope stack looking for the nearest enclosing transient
4322 -- scope. Return Empty if no such scope exists.
4324 function Is_Package_Or_Subprogram (Id : Entity_Id) return Boolean;
4325 -- Determine whether arbitrary Id denotes a package or subprogram [body]
4327 ----------------------------
4328 -- Create_Transient_Scope --
4329 ----------------------------
4331 procedure Create_Transient_Scope (Constr : Node_Id) is
4332 Loc : constant Source_Ptr := Sloc (N);
4334 Iter_Loop : Entity_Id;
4335 Trans_Scop : Entity_Id;
4337 begin
4338 Trans_Scop := New_Internal_Entity (E_Block, Current_Scope, Loc, 'B');
4339 Set_Etype (Trans_Scop, Standard_Void_Type);
4341 Push_Scope (Trans_Scop);
4342 Set_Node_To_Be_Wrapped (Constr);
4343 Set_Scope_Is_Transient;
4345 -- The transient scope must also manage the secondary stack
4347 if Manage_Sec_Stack then
4348 Set_Uses_Sec_Stack (Trans_Scop);
4349 Check_Restriction (No_Secondary_Stack, N);
4351 -- The expansion of iterator loops generates references to objects
4352 -- in order to extract elements from a container:
4354 -- Ref : Reference_Type_Ptr := Reference (Container, Cursor);
4355 -- Obj : <object type> renames Ref.all.Element.all;
4357 -- These references are controlled and returned on the secondary
4358 -- stack. A new reference is created at each iteration of the loop
4359 -- and as a result it must be finalized and the space occupied by
4360 -- it on the secondary stack reclaimed at the end of the current
4361 -- iteration.
4363 -- When the context that requires a transient scope is a call to
4364 -- routine Reference, the node to be wrapped is the source object:
4366 -- for Obj of Container loop
4368 -- Routine Wrap_Transient_Declaration however does not generate
4369 -- a physical block as wrapping a declaration will kill it too
4370 -- early. To handle this peculiar case, mark the related iterator
4371 -- loop as requiring the secondary stack. This signals the
4372 -- finalization machinery to manage the secondary stack (see
4373 -- routine Process_Statements_For_Controlled_Objects).
4375 Iter_Loop := Find_Enclosing_Iterator_Loop (Trans_Scop);
4377 if Present (Iter_Loop) then
4378 Set_Uses_Sec_Stack (Iter_Loop);
4379 end if;
4380 end if;
4382 if Debug_Flag_W then
4383 Write_Str (" <Transient>");
4384 Write_Eol;
4385 end if;
4386 end Create_Transient_Scope;
4388 -----------------------------------
4389 -- Delegate_Sec_Stack_Management --
4390 -----------------------------------
4392 procedure Delegate_Sec_Stack_Management is
4393 Scop_Id : Entity_Id;
4394 Scop_Rec : Scope_Stack_Entry;
4396 begin
4397 for Index in reverse Scope_Stack.First .. Scope_Stack.Last loop
4398 Scop_Rec := Scope_Stack.Table (Index);
4399 Scop_Id := Scop_Rec.Entity;
4401 -- Prevent the search from going too far or within the scope space
4402 -- of another unit.
4404 if Scop_Id = Standard_Standard then
4405 return;
4407 -- No transient scope should be encountered during the traversal
4408 -- because Establish_Transient_Scope should have already handled
4409 -- this case.
4411 elsif Scop_Rec.Is_Transient then
4412 pragma Assert (False);
4413 return;
4415 -- The construct which requires secondary stack management is
4416 -- always enclosed by a package or subprogram scope.
4418 elsif Is_Package_Or_Subprogram (Scop_Id) then
4419 Set_Uses_Sec_Stack (Scop_Id);
4420 Check_Restriction (No_Secondary_Stack, N);
4422 return;
4423 end if;
4424 end loop;
4426 -- At this point no suitable scope was found. This should never occur
4427 -- because a construct is always enclosed by a compilation unit which
4428 -- has a scope.
4430 pragma Assert (False);
4431 end Delegate_Sec_Stack_Management;
4433 ------------------------------------
4434 -- Find_Enclosing_Transient_Scope --
4435 ------------------------------------
4437 function Find_Enclosing_Transient_Scope return Entity_Id is
4438 Scop_Id : Entity_Id;
4439 Scop_Rec : Scope_Stack_Entry;
4441 begin
4442 for Index in reverse Scope_Stack.First .. Scope_Stack.Last loop
4443 Scop_Rec := Scope_Stack.Table (Index);
4444 Scop_Id := Scop_Rec.Entity;
4446 -- Prevent the search from going too far or within the scope space
4447 -- of another unit.
4449 if Scop_Id = Standard_Standard
4450 or else Is_Package_Or_Subprogram (Scop_Id)
4451 then
4452 exit;
4454 elsif Scop_Rec.Is_Transient then
4455 return Scop_Id;
4456 end if;
4457 end loop;
4459 return Empty;
4460 end Find_Enclosing_Transient_Scope;
4462 ------------------------------
4463 -- Is_Package_Or_Subprogram --
4464 ------------------------------
4466 function Is_Package_Or_Subprogram (Id : Entity_Id) return Boolean is
4467 begin
4468 return Ekind_In (Id, E_Entry,
4469 E_Entry_Family,
4470 E_Function,
4471 E_Package,
4472 E_Procedure,
4473 E_Subprogram_Body);
4474 end Is_Package_Or_Subprogram;
4476 -- Local variables
4478 Trans_Id : constant Entity_Id := Find_Enclosing_Transient_Scope;
4479 Context : Node_Id;
4481 -- Start of processing for Establish_Transient_Scope
4483 begin
4484 -- Do not create a new transient scope if there is an existing transient
4485 -- scope on the stack.
4487 if Present (Trans_Id) then
4489 -- If the transient scope was requested for purposes of managing the
4490 -- secondary stack, then the existing scope must perform this task.
4492 if Manage_Sec_Stack then
4493 Set_Uses_Sec_Stack (Trans_Id);
4494 end if;
4496 return;
4497 end if;
4499 -- At this point it is known that the scope stack is free of transient
4500 -- scopes. Locate the proper construct which must be serviced by a new
4501 -- transient scope.
4503 Context := Find_Transient_Context (N);
4505 if Present (Context) then
4506 if Nkind (Context) = N_Assignment_Statement then
4508 -- An assignment statement with suppressed controlled semantics
4509 -- does not need a transient scope because finalization is not
4510 -- desirable at this point. Note that No_Ctrl_Actions is also
4511 -- set for non-controlled assignments to suppress dispatching
4512 -- _assign.
4514 if No_Ctrl_Actions (Context)
4515 and then Needs_Finalization (Etype (Name (Context)))
4516 then
4517 -- When a controlled component is initialized by a function
4518 -- call, the result on the secondary stack is always assigned
4519 -- to the component. Signal the nearest suitable scope that it
4520 -- is safe to manage the secondary stack.
4522 if Manage_Sec_Stack and then Within_Init_Proc then
4523 Delegate_Sec_Stack_Management;
4524 end if;
4526 -- Otherwise the assignment is a normal transient context and thus
4527 -- requires a transient scope.
4529 else
4530 Create_Transient_Scope (Context);
4531 end if;
4533 -- General case
4535 else
4536 Create_Transient_Scope (Context);
4537 end if;
4538 end if;
4539 end Establish_Transient_Scope;
4541 ----------------------------
4542 -- Expand_Cleanup_Actions --
4543 ----------------------------
4545 procedure Expand_Cleanup_Actions (N : Node_Id) is
4546 pragma Assert (Nkind_In (N, N_Block_Statement,
4547 N_Entry_Body,
4548 N_Extended_Return_Statement,
4549 N_Subprogram_Body,
4550 N_Task_Body));
4552 Scop : constant Entity_Id := Current_Scope;
4554 Is_Asynchronous_Call : constant Boolean :=
4555 Nkind (N) = N_Block_Statement
4556 and then Is_Asynchronous_Call_Block (N);
4557 Is_Master : constant Boolean :=
4558 Nkind (N) /= N_Extended_Return_Statement
4559 and then Nkind (N) /= N_Entry_Body
4560 and then Is_Task_Master (N);
4561 Is_Protected_Subp_Body : constant Boolean :=
4562 Nkind (N) = N_Subprogram_Body
4563 and then Is_Protected_Subprogram_Body (N);
4564 Is_Task_Allocation : constant Boolean :=
4565 Nkind (N) = N_Block_Statement
4566 and then Is_Task_Allocation_Block (N);
4567 Is_Task_Body : constant Boolean :=
4568 Nkind (Original_Node (N)) = N_Task_Body;
4570 -- We mark the secondary stack if it is used in this construct, and
4571 -- we're not returning a function result on the secondary stack, except
4572 -- that a build-in-place function that might or might not return on the
4573 -- secondary stack always needs a mark. A run-time test is required in
4574 -- the case where the build-in-place function has a BIP_Alloc extra
4575 -- parameter (see Create_Finalizer).
4577 Needs_Sec_Stack_Mark : constant Boolean :=
4578 (Uses_Sec_Stack (Scop)
4579 and then
4580 not Sec_Stack_Needed_For_Return (Scop))
4581 or else
4582 (Is_Build_In_Place_Function (Scop)
4583 and then Needs_BIP_Alloc_Form (Scop));
4585 Needs_Custom_Cleanup : constant Boolean :=
4586 Nkind (N) = N_Block_Statement
4587 and then Present (Cleanup_Actions (N));
4589 Actions_Required : constant Boolean :=
4590 Requires_Cleanup_Actions (N, True)
4591 or else Is_Asynchronous_Call
4592 or else Is_Master
4593 or else Is_Protected_Subp_Body
4594 or else Is_Task_Allocation
4595 or else Is_Task_Body
4596 or else Needs_Sec_Stack_Mark
4597 or else Needs_Custom_Cleanup;
4599 HSS : Node_Id := Handled_Statement_Sequence (N);
4600 Loc : Source_Ptr;
4601 Cln : List_Id;
4603 procedure Wrap_HSS_In_Block;
4604 -- Move HSS inside a new block along with the original exception
4605 -- handlers. Make the newly generated block the sole statement of HSS.
4607 -----------------------
4608 -- Wrap_HSS_In_Block --
4609 -----------------------
4611 procedure Wrap_HSS_In_Block is
4612 Block : Node_Id;
4613 Block_Id : Entity_Id;
4614 End_Lab : Node_Id;
4616 begin
4617 -- Preserve end label to provide proper cross-reference information
4619 End_Lab := End_Label (HSS);
4620 Block :=
4621 Make_Block_Statement (Loc, Handled_Statement_Sequence => HSS);
4623 Block_Id := New_Internal_Entity (E_Block, Current_Scope, Loc, 'B');
4624 Set_Identifier (Block, New_Occurrence_Of (Block_Id, Loc));
4625 Set_Etype (Block_Id, Standard_Void_Type);
4626 Set_Block_Node (Block_Id, Identifier (Block));
4628 -- Signal the finalization machinery that this particular block
4629 -- contains the original context.
4631 Set_Is_Finalization_Wrapper (Block);
4633 Set_Handled_Statement_Sequence (N,
4634 Make_Handled_Sequence_Of_Statements (Loc, New_List (Block)));
4635 HSS := Handled_Statement_Sequence (N);
4637 Set_First_Real_Statement (HSS, Block);
4638 Set_End_Label (HSS, End_Lab);
4640 -- Comment needed here, see RH for 1.306 ???
4642 if Nkind (N) = N_Subprogram_Body then
4643 Set_Has_Nested_Block_With_Handler (Scop);
4644 end if;
4645 end Wrap_HSS_In_Block;
4647 -- Start of processing for Expand_Cleanup_Actions
4649 begin
4650 -- The current construct does not need any form of servicing
4652 if not Actions_Required then
4653 return;
4655 -- If the current node is a rewritten task body and the descriptors have
4656 -- not been delayed (due to some nested instantiations), do not generate
4657 -- redundant cleanup actions.
4659 elsif Is_Task_Body
4660 and then Nkind (N) = N_Subprogram_Body
4661 and then not Delay_Subprogram_Descriptors (Corresponding_Spec (N))
4662 then
4663 return;
4664 end if;
4666 -- If an extended return statement contains something like
4668 -- X := F (...);
4670 -- where F is a build-in-place function call returning a controlled
4671 -- type, then a temporary object will be implicitly declared as part
4672 -- of the statement list, and this will need cleanup. In such cases,
4673 -- we transform:
4675 -- return Result : T := ... do
4676 -- <statements> -- possibly with handlers
4677 -- end return;
4679 -- into:
4681 -- return Result : T := ... do
4682 -- declare -- no declarations
4683 -- begin
4684 -- <statements> -- possibly with handlers
4685 -- end; -- no handlers
4686 -- end return;
4688 -- So Expand_Cleanup_Actions will end up being called recursively on the
4689 -- block statement.
4691 if Nkind (N) = N_Extended_Return_Statement then
4692 declare
4693 Block : constant Node_Id :=
4694 Make_Block_Statement (Sloc (N),
4695 Declarations => Empty_List,
4696 Handled_Statement_Sequence =>
4697 Handled_Statement_Sequence (N));
4698 begin
4699 Set_Handled_Statement_Sequence (N,
4700 Make_Handled_Sequence_Of_Statements (Sloc (N),
4701 Statements => New_List (Block)));
4703 Analyze (Block);
4704 end;
4706 -- Analysis of the block did all the work
4708 return;
4709 end if;
4711 if Needs_Custom_Cleanup then
4712 Cln := Cleanup_Actions (N);
4713 else
4714 Cln := No_List;
4715 end if;
4717 declare
4718 Decls : List_Id := Declarations (N);
4719 Fin_Id : Entity_Id;
4720 Mark : Entity_Id := Empty;
4721 New_Decls : List_Id;
4722 Old_Poll : Boolean;
4724 begin
4725 -- If we are generating expanded code for debugging purposes, use the
4726 -- Sloc of the point of insertion for the cleanup code. The Sloc will
4727 -- be updated subsequently to reference the proper line in .dg files.
4728 -- If we are not debugging generated code, use No_Location instead,
4729 -- so that no debug information is generated for the cleanup code.
4730 -- This makes the behavior of the NEXT command in GDB monotonic, and
4731 -- makes the placement of breakpoints more accurate.
4733 if Debug_Generated_Code then
4734 Loc := Sloc (Scop);
4735 else
4736 Loc := No_Location;
4737 end if;
4739 -- Set polling off. The finalization and cleanup code is executed
4740 -- with aborts deferred.
4742 Old_Poll := Polling_Required;
4743 Polling_Required := False;
4745 -- A task activation call has already been built for a task
4746 -- allocation block.
4748 if not Is_Task_Allocation then
4749 Build_Task_Activation_Call (N);
4750 end if;
4752 if Is_Master then
4753 Establish_Task_Master (N);
4754 end if;
4756 New_Decls := New_List;
4758 -- If secondary stack is in use, generate:
4760 -- Mnn : constant Mark_Id := SS_Mark;
4762 if Needs_Sec_Stack_Mark then
4763 Mark := Make_Temporary (Loc, 'M');
4765 Append_To (New_Decls, Build_SS_Mark_Call (Loc, Mark));
4766 Set_Uses_Sec_Stack (Scop, False);
4767 end if;
4769 -- If exception handlers are present, wrap the sequence of statements
4770 -- in a block since it is not possible to have exception handlers and
4771 -- an At_End handler in the same construct.
4773 if Present (Exception_Handlers (HSS)) then
4774 Wrap_HSS_In_Block;
4776 -- Ensure that the First_Real_Statement field is set
4778 elsif No (First_Real_Statement (HSS)) then
4779 Set_First_Real_Statement (HSS, First (Statements (HSS)));
4780 end if;
4782 -- Do not move the Activation_Chain declaration in the context of
4783 -- task allocation blocks. Task allocation blocks use _chain in their
4784 -- cleanup handlers and gigi complains if it is declared in the
4785 -- sequence of statements of the scope that declares the handler.
4787 if Is_Task_Allocation then
4788 declare
4789 Chain : constant Entity_Id := Activation_Chain_Entity (N);
4790 Decl : Node_Id;
4792 begin
4793 Decl := First (Decls);
4794 while Nkind (Decl) /= N_Object_Declaration
4795 or else Defining_Identifier (Decl) /= Chain
4796 loop
4797 Next (Decl);
4799 -- A task allocation block should always include a _chain
4800 -- declaration.
4802 pragma Assert (Present (Decl));
4803 end loop;
4805 Remove (Decl);
4806 Prepend_To (New_Decls, Decl);
4807 end;
4808 end if;
4810 -- Ensure the presence of a declaration list in order to successfully
4811 -- append all original statements to it.
4813 if No (Decls) then
4814 Set_Declarations (N, New_List);
4815 Decls := Declarations (N);
4816 end if;
4818 -- Move the declarations into the sequence of statements in order to
4819 -- have them protected by the At_End handler. It may seem weird to
4820 -- put declarations in the sequence of statement but in fact nothing
4821 -- forbids that at the tree level.
4823 Append_List_To (Decls, Statements (HSS));
4824 Set_Statements (HSS, Decls);
4826 -- Reset the Sloc of the handled statement sequence to properly
4827 -- reflect the new initial "statement" in the sequence.
4829 Set_Sloc (HSS, Sloc (First (Decls)));
4831 -- The declarations of finalizer spec and auxiliary variables replace
4832 -- the old declarations that have been moved inward.
4834 Set_Declarations (N, New_Decls);
4835 Analyze_Declarations (New_Decls);
4837 -- Generate finalization calls for all controlled objects appearing
4838 -- in the statements of N. Add context specific cleanup for various
4839 -- constructs.
4841 Build_Finalizer
4842 (N => N,
4843 Clean_Stmts => Build_Cleanup_Statements (N, Cln),
4844 Mark_Id => Mark,
4845 Top_Decls => New_Decls,
4846 Defer_Abort => Nkind (Original_Node (N)) = N_Task_Body
4847 or else Is_Master,
4848 Fin_Id => Fin_Id);
4850 if Present (Fin_Id) then
4851 Build_Finalizer_Call (N, Fin_Id);
4852 end if;
4854 -- Restore saved polling mode
4856 Polling_Required := Old_Poll;
4857 end;
4858 end Expand_Cleanup_Actions;
4860 ---------------------------
4861 -- Expand_N_Package_Body --
4862 ---------------------------
4864 -- Add call to Activate_Tasks if body is an activator (actual processing
4865 -- is in chapter 9).
4867 -- Generate subprogram descriptor for elaboration routine
4869 -- Encode entity names in package body
4871 procedure Expand_N_Package_Body (N : Node_Id) is
4872 Spec_Id : constant Entity_Id := Corresponding_Spec (N);
4873 Fin_Id : Entity_Id;
4875 begin
4876 -- This is done only for non-generic packages
4878 if Ekind (Spec_Id) = E_Package then
4879 Push_Scope (Spec_Id);
4881 -- Build dispatch tables of library level tagged types
4883 if Tagged_Type_Expansion
4884 and then Is_Library_Level_Entity (Spec_Id)
4885 then
4886 Build_Static_Dispatch_Tables (N);
4887 end if;
4889 Build_Task_Activation_Call (N);
4891 -- Verify the run-time semantics of pragma Initial_Condition at the
4892 -- end of the body statements.
4894 Expand_Pragma_Initial_Condition (Spec_Id, N);
4895 Check_Unnesting_Elaboration_Code (N);
4897 Pop_Scope;
4898 end if;
4900 Set_Elaboration_Flag (N, Spec_Id);
4901 Set_In_Package_Body (Spec_Id, False);
4903 -- Set to encode entity names in package body before gigi is called
4905 Qualify_Entity_Names (N);
4907 if Ekind (Spec_Id) /= E_Generic_Package then
4908 Build_Finalizer
4909 (N => N,
4910 Clean_Stmts => No_List,
4911 Mark_Id => Empty,
4912 Top_Decls => No_List,
4913 Defer_Abort => False,
4914 Fin_Id => Fin_Id);
4916 if Present (Fin_Id) then
4917 declare
4918 Body_Ent : Node_Id := Defining_Unit_Name (N);
4920 begin
4921 if Nkind (Body_Ent) = N_Defining_Program_Unit_Name then
4922 Body_Ent := Defining_Identifier (Body_Ent);
4923 end if;
4925 Set_Finalizer (Body_Ent, Fin_Id);
4926 end;
4927 end if;
4928 end if;
4929 end Expand_N_Package_Body;
4931 ----------------------------------
4932 -- Expand_N_Package_Declaration --
4933 ----------------------------------
4935 -- Add call to Activate_Tasks if there are tasks declared and the package
4936 -- has no body. Note that in Ada 83 this may result in premature activation
4937 -- of some tasks, given that we cannot tell whether a body will eventually
4938 -- appear.
4940 procedure Expand_N_Package_Declaration (N : Node_Id) is
4941 Id : constant Entity_Id := Defining_Entity (N);
4942 Spec : constant Node_Id := Specification (N);
4943 Decls : List_Id;
4944 Fin_Id : Entity_Id;
4946 No_Body : Boolean := False;
4947 -- True in the case of a package declaration that is a compilation
4948 -- unit and for which no associated body will be compiled in this
4949 -- compilation.
4951 begin
4952 -- Case of a package declaration other than a compilation unit
4954 if Nkind (Parent (N)) /= N_Compilation_Unit then
4955 null;
4957 -- Case of a compilation unit that does not require a body
4959 elsif not Body_Required (Parent (N))
4960 and then not Unit_Requires_Body (Id)
4961 then
4962 No_Body := True;
4964 -- Special case of generating calling stubs for a remote call interface
4965 -- package: even though the package declaration requires one, the body
4966 -- won't be processed in this compilation (so any stubs for RACWs
4967 -- declared in the package must be generated here, along with the spec).
4969 elsif Parent (N) = Cunit (Main_Unit)
4970 and then Is_Remote_Call_Interface (Id)
4971 and then Distribution_Stub_Mode = Generate_Caller_Stub_Body
4972 then
4973 No_Body := True;
4974 end if;
4976 -- For a nested instance, delay processing until freeze point
4978 if Has_Delayed_Freeze (Id)
4979 and then Nkind (Parent (N)) /= N_Compilation_Unit
4980 then
4981 return;
4982 end if;
4984 -- For a package declaration that implies no associated body, generate
4985 -- task activation call and RACW supporting bodies now (since we won't
4986 -- have a specific separate compilation unit for that).
4988 if No_Body then
4989 Push_Scope (Id);
4991 -- Generate RACW subprogram bodies
4993 if Has_RACW (Id) then
4994 Decls := Private_Declarations (Spec);
4996 if No (Decls) then
4997 Decls := Visible_Declarations (Spec);
4998 end if;
5000 if No (Decls) then
5001 Decls := New_List;
5002 Set_Visible_Declarations (Spec, Decls);
5003 end if;
5005 Append_RACW_Bodies (Decls, Id);
5006 Analyze_List (Decls);
5007 end if;
5009 -- Generate task activation call as last step of elaboration
5011 if Present (Activation_Chain_Entity (N)) then
5012 Build_Task_Activation_Call (N);
5013 end if;
5015 -- Verify the run-time semantics of pragma Initial_Condition at the
5016 -- end of the private declarations when the package lacks a body.
5018 Expand_Pragma_Initial_Condition (Id, N);
5020 Pop_Scope;
5021 end if;
5023 -- Build dispatch tables of library level tagged types
5025 if Tagged_Type_Expansion
5026 and then (Is_Compilation_Unit (Id)
5027 or else (Is_Generic_Instance (Id)
5028 and then Is_Library_Level_Entity (Id)))
5029 then
5030 Build_Static_Dispatch_Tables (N);
5031 end if;
5033 -- Note: it is not necessary to worry about generating a subprogram
5034 -- descriptor, since the only way to get exception handlers into a
5035 -- package spec is to include instantiations, and that would cause
5036 -- generation of subprogram descriptors to be delayed in any case.
5038 -- Set to encode entity names in package spec before gigi is called
5040 Qualify_Entity_Names (N);
5042 if Ekind (Id) /= E_Generic_Package then
5043 Build_Finalizer
5044 (N => N,
5045 Clean_Stmts => No_List,
5046 Mark_Id => Empty,
5047 Top_Decls => No_List,
5048 Defer_Abort => False,
5049 Fin_Id => Fin_Id);
5051 Set_Finalizer (Id, Fin_Id);
5052 end if;
5053 end Expand_N_Package_Declaration;
5055 ----------------------------
5056 -- Find_Transient_Context --
5057 ----------------------------
5059 function Find_Transient_Context (N : Node_Id) return Node_Id is
5060 Curr : Node_Id;
5061 Prev : Node_Id;
5063 begin
5064 Curr := N;
5065 Prev := Empty;
5066 while Present (Curr) loop
5067 case Nkind (Curr) is
5069 -- Declarations
5071 -- Declarations act as a boundary for a transient scope even if
5072 -- they are not wrapped, see Wrap_Transient_Declaration.
5074 when N_Object_Declaration
5075 | N_Object_Renaming_Declaration
5076 | N_Subtype_Declaration
5078 return Curr;
5080 -- Statements
5082 -- Statements and statement-like constructs act as a boundary for
5083 -- a transient scope.
5085 when N_Accept_Alternative
5086 | N_Attribute_Definition_Clause
5087 | N_Case_Statement
5088 | N_Case_Statement_Alternative
5089 | N_Code_Statement
5090 | N_Delay_Alternative
5091 | N_Delay_Until_Statement
5092 | N_Delay_Relative_Statement
5093 | N_Discriminant_Association
5094 | N_Elsif_Part
5095 | N_Entry_Body_Formal_Part
5096 | N_Exit_Statement
5097 | N_If_Statement
5098 | N_Iteration_Scheme
5099 | N_Terminate_Alternative
5101 pragma Assert (Present (Prev));
5102 return Prev;
5104 when N_Assignment_Statement =>
5105 return Curr;
5107 when N_Entry_Call_Statement
5108 | N_Procedure_Call_Statement
5110 -- When an entry or procedure call acts as the alternative of a
5111 -- conditional or timed entry call, the proper context is that
5112 -- of the alternative.
5114 if Nkind (Parent (Curr)) = N_Entry_Call_Alternative
5115 and then Nkind_In (Parent (Parent (Curr)),
5116 N_Conditional_Entry_Call,
5117 N_Timed_Entry_Call)
5118 then
5119 return Parent (Parent (Curr));
5121 -- General case for entry or procedure calls
5123 else
5124 return Curr;
5125 end if;
5127 when N_Pragma =>
5129 -- Pragma Check is not a valid transient context in GNATprove
5130 -- mode because the pragma must remain unchanged.
5132 if GNATprove_Mode
5133 and then Get_Pragma_Id (Curr) = Pragma_Check
5134 then
5135 return Empty;
5137 -- General case for pragmas
5139 else
5140 return Curr;
5141 end if;
5143 when N_Raise_Statement =>
5144 return Curr;
5146 when N_Simple_Return_Statement =>
5148 -- A return statement is not a valid transient context when the
5149 -- function itself requires transient scope management because
5150 -- the result will be reclaimed too early.
5152 if Requires_Transient_Scope (Etype
5153 (Return_Applies_To (Return_Statement_Entity (Curr))))
5154 then
5155 return Empty;
5157 -- General case for return statements
5159 else
5160 return Curr;
5161 end if;
5163 -- Special
5165 when N_Attribute_Reference =>
5166 if Is_Procedure_Attribute_Name (Attribute_Name (Curr)) then
5167 return Curr;
5168 end if;
5170 -- An Ada 2012 iterator specification is not a valid context
5171 -- because Analyze_Iterator_Specification already employs special
5172 -- processing for it.
5174 when N_Iterator_Specification =>
5175 return Empty;
5177 when N_Loop_Parameter_Specification =>
5179 -- An iteration scheme is not a valid context because routine
5180 -- Analyze_Iteration_Scheme already employs special processing.
5182 if Nkind (Parent (Curr)) = N_Iteration_Scheme then
5183 return Empty;
5184 else
5185 return Parent (Curr);
5186 end if;
5188 -- Termination
5190 -- The following nodes represent "dummy contexts" which do not
5191 -- need to be wrapped.
5193 when N_Component_Declaration
5194 | N_Discriminant_Specification
5195 | N_Parameter_Specification
5197 return Empty;
5199 -- If the traversal leaves a scope without having been able to
5200 -- find a construct to wrap, something is going wrong, but this
5201 -- can happen in error situations that are not detected yet (such
5202 -- as a dynamic string in a pragma Export).
5204 when N_Block_Statement
5205 | N_Entry_Body
5206 | N_Package_Body
5207 | N_Package_Declaration
5208 | N_Protected_Body
5209 | N_Subprogram_Body
5210 | N_Task_Body
5212 return Empty;
5214 -- Default
5216 when others =>
5217 null;
5218 end case;
5220 Prev := Curr;
5221 Curr := Parent (Curr);
5222 end loop;
5224 return Empty;
5225 end Find_Transient_Context;
5227 ----------------------------------
5228 -- Has_New_Controlled_Component --
5229 ----------------------------------
5231 function Has_New_Controlled_Component (E : Entity_Id) return Boolean is
5232 Comp : Entity_Id;
5234 begin
5235 if not Is_Tagged_Type (E) then
5236 return Has_Controlled_Component (E);
5237 elsif not Is_Derived_Type (E) then
5238 return Has_Controlled_Component (E);
5239 end if;
5241 Comp := First_Component (E);
5242 while Present (Comp) loop
5243 if Chars (Comp) = Name_uParent then
5244 null;
5246 elsif Scope (Original_Record_Component (Comp)) = E
5247 and then Needs_Finalization (Etype (Comp))
5248 then
5249 return True;
5250 end if;
5252 Next_Component (Comp);
5253 end loop;
5255 return False;
5256 end Has_New_Controlled_Component;
5258 ---------------------------------
5259 -- Has_Simple_Protected_Object --
5260 ---------------------------------
5262 function Has_Simple_Protected_Object (T : Entity_Id) return Boolean is
5263 begin
5264 if Has_Task (T) then
5265 return False;
5267 elsif Is_Simple_Protected_Type (T) then
5268 return True;
5270 elsif Is_Array_Type (T) then
5271 return Has_Simple_Protected_Object (Component_Type (T));
5273 elsif Is_Record_Type (T) then
5274 declare
5275 Comp : Entity_Id;
5277 begin
5278 Comp := First_Component (T);
5279 while Present (Comp) loop
5280 if Has_Simple_Protected_Object (Etype (Comp)) then
5281 return True;
5282 end if;
5284 Next_Component (Comp);
5285 end loop;
5287 return False;
5288 end;
5290 else
5291 return False;
5292 end if;
5293 end Has_Simple_Protected_Object;
5295 ------------------------------------
5296 -- Insert_Actions_In_Scope_Around --
5297 ------------------------------------
5299 procedure Insert_Actions_In_Scope_Around
5300 (N : Node_Id;
5301 Clean : Boolean;
5302 Manage_SS : Boolean)
5304 Act_Before : constant List_Id :=
5305 Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (Before);
5306 Act_After : constant List_Id :=
5307 Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (After);
5308 Act_Cleanup : constant List_Id :=
5309 Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (Cleanup);
5310 -- Note: We used to use renamings of Scope_Stack.Table (Scope_Stack.
5311 -- Last), but this was incorrect as Process_Transients_In_Scope may
5312 -- introduce new scopes and cause a reallocation of Scope_Stack.Table.
5314 procedure Process_Transients_In_Scope
5315 (First_Object : Node_Id;
5316 Last_Object : Node_Id;
5317 Related_Node : Node_Id);
5318 -- Find all transient objects in the list First_Object .. Last_Object
5319 -- and generate finalization actions for them. Related_Node denotes the
5320 -- node which created all transient objects.
5322 ---------------------------------
5323 -- Process_Transients_In_Scope --
5324 ---------------------------------
5326 procedure Process_Transients_In_Scope
5327 (First_Object : Node_Id;
5328 Last_Object : Node_Id;
5329 Related_Node : Node_Id)
5331 Exceptions_OK : constant Boolean := Exceptions_In_Finalization_OK;
5333 Must_Hook : Boolean := False;
5334 -- Flag denoting whether the context requires transient object
5335 -- export to the outer finalizer.
5337 function Is_Subprogram_Call (N : Node_Id) return Traverse_Result;
5338 -- Determine whether an arbitrary node denotes a subprogram call
5340 procedure Detect_Subprogram_Call is
5341 new Traverse_Proc (Is_Subprogram_Call);
5343 procedure Process_Transient_In_Scope
5344 (Obj_Decl : Node_Id;
5345 Blk_Data : Finalization_Exception_Data;
5346 Blk_Stmts : List_Id);
5347 -- Generate finalization actions for a single transient object
5348 -- denoted by object declaration Obj_Decl. Blk_Data is the
5349 -- exception data of the enclosing block. Blk_Stmts denotes the
5350 -- statements of the enclosing block.
5352 ------------------------
5353 -- Is_Subprogram_Call --
5354 ------------------------
5356 function Is_Subprogram_Call (N : Node_Id) return Traverse_Result is
5357 begin
5358 -- A regular procedure or function call
5360 if Nkind (N) in N_Subprogram_Call then
5361 Must_Hook := True;
5362 return Abandon;
5364 -- Special cases
5366 -- Heavy expansion may relocate function calls outside the related
5367 -- node. Inspect the original node to detect the initial placement
5368 -- of the call.
5370 elsif Is_Rewrite_Substitution (N) then
5371 Detect_Subprogram_Call (Original_Node (N));
5373 if Must_Hook then
5374 return Abandon;
5375 else
5376 return OK;
5377 end if;
5379 -- Generalized indexing always involves a function call
5381 elsif Nkind (N) = N_Indexed_Component
5382 and then Present (Generalized_Indexing (N))
5383 then
5384 Must_Hook := True;
5385 return Abandon;
5387 -- Keep searching
5389 else
5390 return OK;
5391 end if;
5392 end Is_Subprogram_Call;
5394 --------------------------------
5395 -- Process_Transient_In_Scope --
5396 --------------------------------
5398 procedure Process_Transient_In_Scope
5399 (Obj_Decl : Node_Id;
5400 Blk_Data : Finalization_Exception_Data;
5401 Blk_Stmts : List_Id)
5403 Loc : constant Source_Ptr := Sloc (Obj_Decl);
5404 Obj_Id : constant Entity_Id := Defining_Entity (Obj_Decl);
5405 Fin_Call : Node_Id;
5406 Fin_Stmts : List_Id;
5407 Hook_Assign : Node_Id;
5408 Hook_Clear : Node_Id;
5409 Hook_Decl : Node_Id;
5410 Hook_Insert : Node_Id;
5411 Ptr_Decl : Node_Id;
5413 begin
5414 -- Mark the transient object as successfully processed to avoid
5415 -- double finalization.
5417 Set_Is_Finalized_Transient (Obj_Id);
5419 -- Construct all the pieces necessary to hook and finalize the
5420 -- transient object.
5422 Build_Transient_Object_Statements
5423 (Obj_Decl => Obj_Decl,
5424 Fin_Call => Fin_Call,
5425 Hook_Assign => Hook_Assign,
5426 Hook_Clear => Hook_Clear,
5427 Hook_Decl => Hook_Decl,
5428 Ptr_Decl => Ptr_Decl);
5430 -- The context contains at least one subprogram call which may
5431 -- raise an exception. This scenario employs "hooking" to pass
5432 -- transient objects to the enclosing finalizer in case of an
5433 -- exception.
5435 if Must_Hook then
5437 -- Add the access type which provides a reference to the
5438 -- transient object. Generate:
5440 -- type Ptr_Typ is access all Desig_Typ;
5442 Insert_Action (Obj_Decl, Ptr_Decl);
5444 -- Add the temporary which acts as a hook to the transient
5445 -- object. Generate:
5447 -- Hook : Ptr_Typ := null;
5449 Insert_Action (Obj_Decl, Hook_Decl);
5451 -- When the transient object is initialized by an aggregate,
5452 -- the hook must capture the object after the last aggregate
5453 -- assignment takes place. Only then is the object considered
5454 -- fully initialized. Generate:
5456 -- Hook := Ptr_Typ (Obj_Id);
5457 -- <or>
5458 -- Hook := Obj_Id'Unrestricted_Access;
5460 if Ekind_In (Obj_Id, E_Constant, E_Variable)
5461 and then Present (Last_Aggregate_Assignment (Obj_Id))
5462 then
5463 Hook_Insert := Last_Aggregate_Assignment (Obj_Id);
5465 -- Otherwise the hook seizes the related object immediately
5467 else
5468 Hook_Insert := Obj_Decl;
5469 end if;
5471 Insert_After_And_Analyze (Hook_Insert, Hook_Assign);
5472 end if;
5474 -- When exception propagation is enabled wrap the hook clear
5475 -- statement and the finalization call into a block to catch
5476 -- potential exceptions raised during finalization. Generate:
5478 -- begin
5479 -- [Hook := null;]
5480 -- [Deep_]Finalize (Obj_Ref);
5482 -- exception
5483 -- when others =>
5484 -- if not Raised then
5485 -- Raised := True;
5486 -- Save_Occurrence
5487 -- (Enn, Get_Current_Excep.all.all);
5488 -- end if;
5489 -- end;
5491 if Exceptions_OK then
5492 Fin_Stmts := New_List;
5494 if Must_Hook then
5495 Append_To (Fin_Stmts, Hook_Clear);
5496 end if;
5498 Append_To (Fin_Stmts, Fin_Call);
5500 Prepend_To (Blk_Stmts,
5501 Make_Block_Statement (Loc,
5502 Handled_Statement_Sequence =>
5503 Make_Handled_Sequence_Of_Statements (Loc,
5504 Statements => Fin_Stmts,
5505 Exception_Handlers => New_List (
5506 Build_Exception_Handler (Blk_Data)))));
5508 -- Otherwise generate:
5510 -- [Hook := null;]
5511 -- [Deep_]Finalize (Obj_Ref);
5513 -- Note that the statements are inserted in reverse order to
5514 -- achieve the desired final order outlined above.
5516 else
5517 Prepend_To (Blk_Stmts, Fin_Call);
5519 if Must_Hook then
5520 Prepend_To (Blk_Stmts, Hook_Clear);
5521 end if;
5522 end if;
5523 end Process_Transient_In_Scope;
5525 -- Local variables
5527 Built : Boolean := False;
5528 Blk_Data : Finalization_Exception_Data;
5529 Blk_Decl : Node_Id := Empty;
5530 Blk_Decls : List_Id := No_List;
5531 Blk_Ins : Node_Id;
5532 Blk_Stmts : List_Id;
5533 Loc : Source_Ptr;
5534 Obj_Decl : Node_Id;
5536 -- Start of processing for Process_Transients_In_Scope
5538 begin
5539 -- The expansion performed by this routine is as follows:
5541 -- type Ptr_Typ_1 is access all Ctrl_Trans_Obj_1_Typ;
5542 -- Hook_1 : Ptr_Typ_1 := null;
5543 -- Ctrl_Trans_Obj_1 : ...;
5544 -- Hook_1 := Ctrl_Trans_Obj_1'Unrestricted_Access;
5545 -- . . .
5546 -- type Ptr_Typ_N is access all Ctrl_Trans_Obj_N_Typ;
5547 -- Hook_N : Ptr_Typ_N := null;
5548 -- Ctrl_Trans_Obj_N : ...;
5549 -- Hook_N := Ctrl_Trans_Obj_N'Unrestricted_Access;
5551 -- declare
5552 -- Abrt : constant Boolean := ...;
5553 -- Ex : Exception_Occurrence;
5554 -- Raised : Boolean := False;
5556 -- begin
5557 -- Abort_Defer;
5559 -- begin
5560 -- Hook_N := null;
5561 -- [Deep_]Finalize (Ctrl_Trans_Obj_N);
5563 -- exception
5564 -- when others =>
5565 -- if not Raised then
5566 -- Raised := True;
5567 -- Save_Occurrence (Ex, Get_Current_Excep.all.all);
5568 -- end;
5569 -- . . .
5570 -- begin
5571 -- Hook_1 := null;
5572 -- [Deep_]Finalize (Ctrl_Trans_Obj_1);
5574 -- exception
5575 -- when others =>
5576 -- if not Raised then
5577 -- Raised := True;
5578 -- Save_Occurrence (Ex, Get_Current_Excep.all.all);
5579 -- end;
5581 -- Abort_Undefer;
5583 -- if Raised and not Abrt then
5584 -- Raise_From_Controlled_Operation (Ex);
5585 -- end if;
5586 -- end;
5588 -- Recognize a scenario where the transient context is an object
5589 -- declaration initialized by a build-in-place function call:
5591 -- Obj : ... := BIP_Function_Call (Ctrl_Func_Call);
5593 -- The rough expansion of the above is:
5595 -- Temp : ... := Ctrl_Func_Call;
5596 -- Obj : ...;
5597 -- Res : ... := BIP_Func_Call (..., Obj, ...);
5599 -- The finalization of any transient object must happen after the
5600 -- build-in-place function call is executed.
5602 if Nkind (N) = N_Object_Declaration
5603 and then Present (BIP_Initialization_Call (Defining_Identifier (N)))
5604 then
5605 Must_Hook := True;
5606 Blk_Ins := BIP_Initialization_Call (Defining_Identifier (N));
5608 -- Search the context for at least one subprogram call. If found, the
5609 -- machinery exports all transient objects to the enclosing finalizer
5610 -- due to the possibility of abnormal call termination.
5612 else
5613 Detect_Subprogram_Call (N);
5614 Blk_Ins := Last_Object;
5615 end if;
5617 if Clean then
5618 Insert_List_After_And_Analyze (Blk_Ins, Act_Cleanup);
5619 end if;
5621 -- Examine all objects in the list First_Object .. Last_Object
5623 Obj_Decl := First_Object;
5624 while Present (Obj_Decl) loop
5625 if Nkind (Obj_Decl) = N_Object_Declaration
5626 and then Analyzed (Obj_Decl)
5627 and then Is_Finalizable_Transient (Obj_Decl, N)
5629 -- Do not process the node to be wrapped since it will be
5630 -- handled by the enclosing finalizer.
5632 and then Obj_Decl /= Related_Node
5633 then
5634 Loc := Sloc (Obj_Decl);
5636 -- Before generating the cleanup code for the first transient
5637 -- object, create a wrapper block which houses all hook clear
5638 -- statements and finalization calls. This wrapper is needed by
5639 -- the back end.
5641 if not Built then
5642 Built := True;
5643 Blk_Stmts := New_List;
5645 -- Generate:
5646 -- Abrt : constant Boolean := ...;
5647 -- Ex : Exception_Occurrence;
5648 -- Raised : Boolean := False;
5650 if Exceptions_OK then
5651 Blk_Decls := New_List;
5652 Build_Object_Declarations (Blk_Data, Blk_Decls, Loc);
5653 end if;
5655 Blk_Decl :=
5656 Make_Block_Statement (Loc,
5657 Declarations => Blk_Decls,
5658 Handled_Statement_Sequence =>
5659 Make_Handled_Sequence_Of_Statements (Loc,
5660 Statements => Blk_Stmts));
5661 end if;
5663 -- Construct all necessary circuitry to hook and finalize a
5664 -- single transient object.
5666 Process_Transient_In_Scope
5667 (Obj_Decl => Obj_Decl,
5668 Blk_Data => Blk_Data,
5669 Blk_Stmts => Blk_Stmts);
5670 end if;
5672 -- Terminate the scan after the last object has been processed to
5673 -- avoid touching unrelated code.
5675 if Obj_Decl = Last_Object then
5676 exit;
5677 end if;
5679 Next (Obj_Decl);
5680 end loop;
5682 -- Complete the decoration of the enclosing finalization block and
5683 -- insert it into the tree.
5685 if Present (Blk_Decl) then
5687 -- Note that this Abort_Undefer does not require a extra block or
5688 -- an AT_END handler because each finalization exception is caught
5689 -- in its own corresponding finalization block. As a result, the
5690 -- call to Abort_Defer always takes place.
5692 if Abort_Allowed then
5693 Prepend_To (Blk_Stmts,
5694 Build_Runtime_Call (Loc, RE_Abort_Defer));
5696 Append_To (Blk_Stmts,
5697 Build_Runtime_Call (Loc, RE_Abort_Undefer));
5698 end if;
5700 -- Generate:
5701 -- if Raised and then not Abrt then
5702 -- Raise_From_Controlled_Operation (Ex);
5703 -- end if;
5705 if Exceptions_OK then
5706 Append_To (Blk_Stmts, Build_Raise_Statement (Blk_Data));
5707 end if;
5709 Insert_After_And_Analyze (Blk_Ins, Blk_Decl);
5710 end if;
5711 end Process_Transients_In_Scope;
5713 -- Local variables
5715 Loc : constant Source_Ptr := Sloc (N);
5716 Node_To_Wrap : constant Node_Id := Node_To_Be_Wrapped;
5717 First_Obj : Node_Id;
5718 Last_Obj : Node_Id;
5719 Mark_Id : Entity_Id;
5720 Target : Node_Id;
5722 -- Start of processing for Insert_Actions_In_Scope_Around
5724 begin
5725 -- Nothing to do if the scope does not manage the secondary stack or
5726 -- does not contain meaninful actions for insertion.
5728 if not Manage_SS
5729 and then No (Act_Before)
5730 and then No (Act_After)
5731 and then No (Act_Cleanup)
5732 then
5733 return;
5734 end if;
5736 -- If the node to be wrapped is the trigger of an asynchronous select,
5737 -- it is not part of a statement list. The actions must be inserted
5738 -- before the select itself, which is part of some list of statements.
5739 -- Note that the triggering alternative includes the triggering
5740 -- statement and an optional statement list. If the node to be
5741 -- wrapped is part of that list, the normal insertion applies.
5743 if Nkind (Parent (Node_To_Wrap)) = N_Triggering_Alternative
5744 and then not Is_List_Member (Node_To_Wrap)
5745 then
5746 Target := Parent (Parent (Node_To_Wrap));
5747 else
5748 Target := N;
5749 end if;
5751 First_Obj := Target;
5752 Last_Obj := Target;
5754 -- Add all actions associated with a transient scope into the main tree.
5755 -- There are several scenarios here:
5757 -- +--- Before ----+ +----- After ---+
5758 -- 1) First_Obj ....... Target ........ Last_Obj
5760 -- 2) First_Obj ....... Target
5762 -- 3) Target ........ Last_Obj
5764 -- Flag declarations are inserted before the first object
5766 if Present (Act_Before) then
5767 First_Obj := First (Act_Before);
5768 Insert_List_Before (Target, Act_Before);
5769 end if;
5771 -- Finalization calls are inserted after the last object
5773 if Present (Act_After) then
5774 Last_Obj := Last (Act_After);
5775 Insert_List_After (Target, Act_After);
5776 end if;
5778 -- Mark and release the secondary stack when the context warrants it
5780 if Manage_SS then
5781 Mark_Id := Make_Temporary (Loc, 'M');
5783 -- Generate:
5784 -- Mnn : constant Mark_Id := SS_Mark;
5786 Insert_Before_And_Analyze
5787 (First_Obj, Build_SS_Mark_Call (Loc, Mark_Id));
5789 -- Generate:
5790 -- SS_Release (Mnn);
5792 Insert_After_And_Analyze
5793 (Last_Obj, Build_SS_Release_Call (Loc, Mark_Id));
5794 end if;
5796 -- Check for transient objects associated with Target and generate the
5797 -- appropriate finalization actions for them.
5799 Process_Transients_In_Scope
5800 (First_Object => First_Obj,
5801 Last_Object => Last_Obj,
5802 Related_Node => Target);
5804 -- Reset the action lists
5806 Scope_Stack.Table
5807 (Scope_Stack.Last).Actions_To_Be_Wrapped (Before) := No_List;
5808 Scope_Stack.Table
5809 (Scope_Stack.Last).Actions_To_Be_Wrapped (After) := No_List;
5811 if Clean then
5812 Scope_Stack.Table
5813 (Scope_Stack.Last).Actions_To_Be_Wrapped (Cleanup) := No_List;
5814 end if;
5815 end Insert_Actions_In_Scope_Around;
5817 ------------------------------
5818 -- Is_Simple_Protected_Type --
5819 ------------------------------
5821 function Is_Simple_Protected_Type (T : Entity_Id) return Boolean is
5822 begin
5823 return
5824 Is_Protected_Type (T)
5825 and then not Uses_Lock_Free (T)
5826 and then not Has_Entries (T)
5827 and then Is_RTE (Find_Protection_Type (T), RE_Protection);
5828 end Is_Simple_Protected_Type;
5830 -----------------------
5831 -- Make_Adjust_Call --
5832 -----------------------
5834 function Make_Adjust_Call
5835 (Obj_Ref : Node_Id;
5836 Typ : Entity_Id;
5837 Skip_Self : Boolean := False) return Node_Id
5839 Loc : constant Source_Ptr := Sloc (Obj_Ref);
5840 Adj_Id : Entity_Id := Empty;
5841 Ref : Node_Id;
5842 Utyp : Entity_Id;
5844 begin
5845 Ref := Obj_Ref;
5847 -- Recover the proper type which contains Deep_Adjust
5849 if Is_Class_Wide_Type (Typ) then
5850 Utyp := Root_Type (Typ);
5851 else
5852 Utyp := Typ;
5853 end if;
5855 Utyp := Underlying_Type (Base_Type (Utyp));
5856 Set_Assignment_OK (Ref);
5858 -- Deal with untagged derivation of private views
5860 if Present (Utyp) and then Is_Untagged_Derivation (Typ) then
5861 Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
5862 Ref := Unchecked_Convert_To (Utyp, Ref);
5863 Set_Assignment_OK (Ref);
5864 end if;
5866 -- When dealing with the completion of a private type, use the base
5867 -- type instead.
5869 if Present (Utyp) and then Utyp /= Base_Type (Utyp) then
5870 pragma Assert (Is_Private_Type (Typ));
5872 Utyp := Base_Type (Utyp);
5873 Ref := Unchecked_Convert_To (Utyp, Ref);
5874 end if;
5876 -- The underlying type may not be present due to a missing full view. In
5877 -- this case freezing did not take place and there is no [Deep_]Adjust
5878 -- primitive to call.
5880 if No (Utyp) then
5881 return Empty;
5883 elsif Skip_Self then
5884 if Has_Controlled_Component (Utyp) then
5885 if Is_Tagged_Type (Utyp) then
5886 Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust);
5887 else
5888 Adj_Id := TSS (Utyp, TSS_Deep_Adjust);
5889 end if;
5890 end if;
5892 -- Class-wide types, interfaces and types with controlled components
5894 elsif Is_Class_Wide_Type (Typ)
5895 or else Is_Interface (Typ)
5896 or else Has_Controlled_Component (Utyp)
5897 then
5898 if Is_Tagged_Type (Utyp) then
5899 Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust);
5900 else
5901 Adj_Id := TSS (Utyp, TSS_Deep_Adjust);
5902 end if;
5904 -- Derivations from [Limited_]Controlled
5906 elsif Is_Controlled (Utyp) then
5907 if Has_Controlled_Component (Utyp) then
5908 Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust);
5909 else
5910 Adj_Id := Find_Optional_Prim_Op (Utyp, Name_Of (Adjust_Case));
5911 end if;
5913 -- Tagged types
5915 elsif Is_Tagged_Type (Utyp) then
5916 Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust);
5918 else
5919 raise Program_Error;
5920 end if;
5922 if Present (Adj_Id) then
5924 -- If the object is unanalyzed, set its expected type for use in
5925 -- Convert_View in case an additional conversion is needed.
5927 if No (Etype (Ref))
5928 and then Nkind (Ref) /= N_Unchecked_Type_Conversion
5929 then
5930 Set_Etype (Ref, Typ);
5931 end if;
5933 -- The object reference may need another conversion depending on the
5934 -- type of the formal and that of the actual.
5936 if not Is_Class_Wide_Type (Typ) then
5937 Ref := Convert_View (Adj_Id, Ref);
5938 end if;
5940 return
5941 Make_Call (Loc,
5942 Proc_Id => Adj_Id,
5943 Param => Ref,
5944 Skip_Self => Skip_Self);
5945 else
5946 return Empty;
5947 end if;
5948 end Make_Adjust_Call;
5950 ----------------------
5951 -- Make_Detach_Call --
5952 ----------------------
5954 function Make_Detach_Call (Obj_Ref : Node_Id) return Node_Id is
5955 Loc : constant Source_Ptr := Sloc (Obj_Ref);
5957 begin
5958 return
5959 Make_Procedure_Call_Statement (Loc,
5960 Name =>
5961 New_Occurrence_Of (RTE (RE_Detach), Loc),
5962 Parameter_Associations => New_List (
5963 Unchecked_Convert_To (RTE (RE_Root_Controlled_Ptr), Obj_Ref)));
5964 end Make_Detach_Call;
5966 ---------------
5967 -- Make_Call --
5968 ---------------
5970 function Make_Call
5971 (Loc : Source_Ptr;
5972 Proc_Id : Entity_Id;
5973 Param : Node_Id;
5974 Skip_Self : Boolean := False) return Node_Id
5976 Params : constant List_Id := New_List (Param);
5978 begin
5979 -- Do not apply the controlled action to the object itself by signaling
5980 -- the related routine to avoid self.
5982 if Skip_Self then
5983 Append_To (Params, New_Occurrence_Of (Standard_False, Loc));
5984 end if;
5986 return
5987 Make_Procedure_Call_Statement (Loc,
5988 Name => New_Occurrence_Of (Proc_Id, Loc),
5989 Parameter_Associations => Params);
5990 end Make_Call;
5992 --------------------------
5993 -- Make_Deep_Array_Body --
5994 --------------------------
5996 function Make_Deep_Array_Body
5997 (Prim : Final_Primitives;
5998 Typ : Entity_Id) return List_Id
6000 Exceptions_OK : constant Boolean := Exceptions_In_Finalization_OK;
6002 function Build_Adjust_Or_Finalize_Statements
6003 (Typ : Entity_Id) return List_Id;
6004 -- Create the statements necessary to adjust or finalize an array of
6005 -- controlled elements. Generate:
6007 -- declare
6008 -- Abort : constant Boolean := Triggered_By_Abort;
6009 -- <or>
6010 -- Abort : constant Boolean := False; -- no abort
6012 -- E : Exception_Occurrence;
6013 -- Raised : Boolean := False;
6015 -- begin
6016 -- for J1 in [reverse] Typ'First (1) .. Typ'Last (1) loop
6017 -- ^-- in the finalization case
6018 -- ...
6019 -- for Jn in [reverse] Typ'First (n) .. Typ'Last (n) loop
6020 -- begin
6021 -- [Deep_]Adjust / Finalize (V (J1, ..., Jn));
6023 -- exception
6024 -- when others =>
6025 -- if not Raised then
6026 -- Raised := True;
6027 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6028 -- end if;
6029 -- end;
6030 -- end loop;
6031 -- ...
6032 -- end loop;
6034 -- if Raised and then not Abort then
6035 -- Raise_From_Controlled_Operation (E);
6036 -- end if;
6037 -- end;
6039 function Build_Initialize_Statements (Typ : Entity_Id) return List_Id;
6040 -- Create the statements necessary to initialize an array of controlled
6041 -- elements. Include a mechanism to carry out partial finalization if an
6042 -- exception occurs. Generate:
6044 -- declare
6045 -- Counter : Integer := 0;
6047 -- begin
6048 -- for J1 in V'Range (1) loop
6049 -- ...
6050 -- for JN in V'Range (N) loop
6051 -- begin
6052 -- [Deep_]Initialize (V (J1, ..., JN));
6054 -- Counter := Counter + 1;
6056 -- exception
6057 -- when others =>
6058 -- declare
6059 -- Abort : constant Boolean := Triggered_By_Abort;
6060 -- <or>
6061 -- Abort : constant Boolean := False; -- no abort
6062 -- E : Exception_Occurrence;
6063 -- Raised : Boolean := False;
6065 -- begin
6066 -- Counter :=
6067 -- V'Length (1) *
6068 -- V'Length (2) *
6069 -- ...
6070 -- V'Length (N) - Counter;
6072 -- for F1 in reverse V'Range (1) loop
6073 -- ...
6074 -- for FN in reverse V'Range (N) loop
6075 -- if Counter > 0 then
6076 -- Counter := Counter - 1;
6077 -- else
6078 -- begin
6079 -- [Deep_]Finalize (V (F1, ..., FN));
6081 -- exception
6082 -- when others =>
6083 -- if not Raised then
6084 -- Raised := True;
6085 -- Save_Occurrence (E,
6086 -- Get_Current_Excep.all.all);
6087 -- end if;
6088 -- end;
6089 -- end if;
6090 -- end loop;
6091 -- ...
6092 -- end loop;
6093 -- end;
6095 -- if Raised and then not Abort then
6096 -- Raise_From_Controlled_Operation (E);
6097 -- end if;
6099 -- raise;
6100 -- end;
6101 -- end loop;
6102 -- end loop;
6103 -- end;
6105 function New_References_To
6106 (L : List_Id;
6107 Loc : Source_Ptr) return List_Id;
6108 -- Given a list of defining identifiers, return a list of references to
6109 -- the original identifiers, in the same order as they appear.
6111 -----------------------------------------
6112 -- Build_Adjust_Or_Finalize_Statements --
6113 -----------------------------------------
6115 function Build_Adjust_Or_Finalize_Statements
6116 (Typ : Entity_Id) return List_Id
6118 Comp_Typ : constant Entity_Id := Component_Type (Typ);
6119 Index_List : constant List_Id := New_List;
6120 Loc : constant Source_Ptr := Sloc (Typ);
6121 Num_Dims : constant Int := Number_Dimensions (Typ);
6123 procedure Build_Indexes;
6124 -- Generate the indexes used in the dimension loops
6126 -------------------
6127 -- Build_Indexes --
6128 -------------------
6130 procedure Build_Indexes is
6131 begin
6132 -- Generate the following identifiers:
6133 -- Jnn - for initialization
6135 for Dim in 1 .. Num_Dims loop
6136 Append_To (Index_List,
6137 Make_Defining_Identifier (Loc, New_External_Name ('J', Dim)));
6138 end loop;
6139 end Build_Indexes;
6141 -- Local variables
6143 Final_Decls : List_Id := No_List;
6144 Final_Data : Finalization_Exception_Data;
6145 Block : Node_Id;
6146 Call : Node_Id;
6147 Comp_Ref : Node_Id;
6148 Core_Loop : Node_Id;
6149 Dim : Int;
6150 J : Entity_Id;
6151 Loop_Id : Entity_Id;
6152 Stmts : List_Id;
6154 -- Start of processing for Build_Adjust_Or_Finalize_Statements
6156 begin
6157 Final_Decls := New_List;
6159 Build_Indexes;
6160 Build_Object_Declarations (Final_Data, Final_Decls, Loc);
6162 Comp_Ref :=
6163 Make_Indexed_Component (Loc,
6164 Prefix => Make_Identifier (Loc, Name_V),
6165 Expressions => New_References_To (Index_List, Loc));
6166 Set_Etype (Comp_Ref, Comp_Typ);
6168 -- Generate:
6169 -- [Deep_]Adjust (V (J1, ..., JN))
6171 if Prim = Adjust_Case then
6172 Call := Make_Adjust_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ);
6174 -- Generate:
6175 -- [Deep_]Finalize (V (J1, ..., JN))
6177 else pragma Assert (Prim = Finalize_Case);
6178 Call := Make_Final_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ);
6179 end if;
6181 if Present (Call) then
6183 -- Generate the block which houses the adjust or finalize call:
6185 -- begin
6186 -- <adjust or finalize call>
6188 -- exception
6189 -- when others =>
6190 -- if not Raised then
6191 -- Raised := True;
6192 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6193 -- end if;
6194 -- end;
6196 if Exceptions_OK then
6197 Core_Loop :=
6198 Make_Block_Statement (Loc,
6199 Handled_Statement_Sequence =>
6200 Make_Handled_Sequence_Of_Statements (Loc,
6201 Statements => New_List (Call),
6202 Exception_Handlers => New_List (
6203 Build_Exception_Handler (Final_Data))));
6204 else
6205 Core_Loop := Call;
6206 end if;
6208 -- Generate the dimension loops starting from the innermost one
6210 -- for Jnn in [reverse] V'Range (Dim) loop
6211 -- <core loop>
6212 -- end loop;
6214 J := Last (Index_List);
6215 Dim := Num_Dims;
6216 while Present (J) and then Dim > 0 loop
6217 Loop_Id := J;
6218 Prev (J);
6219 Remove (Loop_Id);
6221 Core_Loop :=
6222 Make_Loop_Statement (Loc,
6223 Iteration_Scheme =>
6224 Make_Iteration_Scheme (Loc,
6225 Loop_Parameter_Specification =>
6226 Make_Loop_Parameter_Specification (Loc,
6227 Defining_Identifier => Loop_Id,
6228 Discrete_Subtype_Definition =>
6229 Make_Attribute_Reference (Loc,
6230 Prefix => Make_Identifier (Loc, Name_V),
6231 Attribute_Name => Name_Range,
6232 Expressions => New_List (
6233 Make_Integer_Literal (Loc, Dim))),
6235 Reverse_Present =>
6236 Prim = Finalize_Case)),
6238 Statements => New_List (Core_Loop),
6239 End_Label => Empty);
6241 Dim := Dim - 1;
6242 end loop;
6244 -- Generate the block which contains the core loop, declarations
6245 -- of the abort flag, the exception occurrence, the raised flag
6246 -- and the conditional raise:
6248 -- declare
6249 -- Abort : constant Boolean := Triggered_By_Abort;
6250 -- <or>
6251 -- Abort : constant Boolean := False; -- no abort
6253 -- E : Exception_Occurrence;
6254 -- Raised : Boolean := False;
6256 -- begin
6257 -- <core loop>
6259 -- if Raised and then not Abort then
6260 -- Raise_From_Controlled_Operation (E);
6261 -- end if;
6262 -- end;
6264 Stmts := New_List (Core_Loop);
6266 if Exceptions_OK then
6267 Append_To (Stmts, Build_Raise_Statement (Final_Data));
6268 end if;
6270 Block :=
6271 Make_Block_Statement (Loc,
6272 Declarations => Final_Decls,
6273 Handled_Statement_Sequence =>
6274 Make_Handled_Sequence_Of_Statements (Loc,
6275 Statements => Stmts));
6277 -- Otherwise previous errors or a missing full view may prevent the
6278 -- proper freezing of the component type. If this is the case, there
6279 -- is no [Deep_]Adjust or [Deep_]Finalize primitive to call.
6281 else
6282 Block := Make_Null_Statement (Loc);
6283 end if;
6285 return New_List (Block);
6286 end Build_Adjust_Or_Finalize_Statements;
6288 ---------------------------------
6289 -- Build_Initialize_Statements --
6290 ---------------------------------
6292 function Build_Initialize_Statements (Typ : Entity_Id) return List_Id is
6293 Comp_Typ : constant Entity_Id := Component_Type (Typ);
6294 Final_List : constant List_Id := New_List;
6295 Index_List : constant List_Id := New_List;
6296 Loc : constant Source_Ptr := Sloc (Typ);
6297 Num_Dims : constant Int := Number_Dimensions (Typ);
6299 function Build_Assignment (Counter_Id : Entity_Id) return Node_Id;
6300 -- Generate the following assignment:
6301 -- Counter := V'Length (1) *
6302 -- ...
6303 -- V'Length (N) - Counter;
6305 -- Counter_Id denotes the entity of the counter.
6307 function Build_Finalization_Call return Node_Id;
6308 -- Generate a deep finalization call for an array element
6310 procedure Build_Indexes;
6311 -- Generate the initialization and finalization indexes used in the
6312 -- dimension loops.
6314 function Build_Initialization_Call return Node_Id;
6315 -- Generate a deep initialization call for an array element
6317 ----------------------
6318 -- Build_Assignment --
6319 ----------------------
6321 function Build_Assignment (Counter_Id : Entity_Id) return Node_Id is
6322 Dim : Int;
6323 Expr : Node_Id;
6325 begin
6326 -- Start from the first dimension and generate:
6327 -- V'Length (1)
6329 Dim := 1;
6330 Expr :=
6331 Make_Attribute_Reference (Loc,
6332 Prefix => Make_Identifier (Loc, Name_V),
6333 Attribute_Name => Name_Length,
6334 Expressions => New_List (Make_Integer_Literal (Loc, Dim)));
6336 -- Process the rest of the dimensions, generate:
6337 -- Expr * V'Length (N)
6339 Dim := Dim + 1;
6340 while Dim <= Num_Dims loop
6341 Expr :=
6342 Make_Op_Multiply (Loc,
6343 Left_Opnd => Expr,
6344 Right_Opnd =>
6345 Make_Attribute_Reference (Loc,
6346 Prefix => Make_Identifier (Loc, Name_V),
6347 Attribute_Name => Name_Length,
6348 Expressions => New_List (
6349 Make_Integer_Literal (Loc, Dim))));
6351 Dim := Dim + 1;
6352 end loop;
6354 -- Generate:
6355 -- Counter := Expr - Counter;
6357 return
6358 Make_Assignment_Statement (Loc,
6359 Name => New_Occurrence_Of (Counter_Id, Loc),
6360 Expression =>
6361 Make_Op_Subtract (Loc,
6362 Left_Opnd => Expr,
6363 Right_Opnd => New_Occurrence_Of (Counter_Id, Loc)));
6364 end Build_Assignment;
6366 -----------------------------
6367 -- Build_Finalization_Call --
6368 -----------------------------
6370 function Build_Finalization_Call return Node_Id is
6371 Comp_Ref : constant Node_Id :=
6372 Make_Indexed_Component (Loc,
6373 Prefix => Make_Identifier (Loc, Name_V),
6374 Expressions => New_References_To (Final_List, Loc));
6376 begin
6377 Set_Etype (Comp_Ref, Comp_Typ);
6379 -- Generate:
6380 -- [Deep_]Finalize (V);
6382 return Make_Final_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ);
6383 end Build_Finalization_Call;
6385 -------------------
6386 -- Build_Indexes --
6387 -------------------
6389 procedure Build_Indexes is
6390 begin
6391 -- Generate the following identifiers:
6392 -- Jnn - for initialization
6393 -- Fnn - for finalization
6395 for Dim in 1 .. Num_Dims loop
6396 Append_To (Index_List,
6397 Make_Defining_Identifier (Loc, New_External_Name ('J', Dim)));
6399 Append_To (Final_List,
6400 Make_Defining_Identifier (Loc, New_External_Name ('F', Dim)));
6401 end loop;
6402 end Build_Indexes;
6404 -------------------------------
6405 -- Build_Initialization_Call --
6406 -------------------------------
6408 function Build_Initialization_Call return Node_Id is
6409 Comp_Ref : constant Node_Id :=
6410 Make_Indexed_Component (Loc,
6411 Prefix => Make_Identifier (Loc, Name_V),
6412 Expressions => New_References_To (Index_List, Loc));
6414 begin
6415 Set_Etype (Comp_Ref, Comp_Typ);
6417 -- Generate:
6418 -- [Deep_]Initialize (V (J1, ..., JN));
6420 return Make_Init_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ);
6421 end Build_Initialization_Call;
6423 -- Local variables
6425 Counter_Id : Entity_Id;
6426 Dim : Int;
6427 F : Node_Id;
6428 Fin_Stmt : Node_Id;
6429 Final_Block : Node_Id;
6430 Final_Data : Finalization_Exception_Data;
6431 Final_Decls : List_Id := No_List;
6432 Final_Loop : Node_Id;
6433 Init_Block : Node_Id;
6434 Init_Call : Node_Id;
6435 Init_Loop : Node_Id;
6436 J : Node_Id;
6437 Loop_Id : Node_Id;
6438 Stmts : List_Id;
6440 -- Start of processing for Build_Initialize_Statements
6442 begin
6443 Counter_Id := Make_Temporary (Loc, 'C');
6444 Final_Decls := New_List;
6446 Build_Indexes;
6447 Build_Object_Declarations (Final_Data, Final_Decls, Loc);
6449 -- Generate the block which houses the finalization call, the index
6450 -- guard and the handler which triggers Program_Error later on.
6452 -- if Counter > 0 then
6453 -- Counter := Counter - 1;
6454 -- else
6455 -- begin
6456 -- [Deep_]Finalize (V (F1, ..., FN));
6457 -- exception
6458 -- when others =>
6459 -- if not Raised then
6460 -- Raised := True;
6461 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6462 -- end if;
6463 -- end;
6464 -- end if;
6466 Fin_Stmt := Build_Finalization_Call;
6468 if Present (Fin_Stmt) then
6469 if Exceptions_OK then
6470 Fin_Stmt :=
6471 Make_Block_Statement (Loc,
6472 Handled_Statement_Sequence =>
6473 Make_Handled_Sequence_Of_Statements (Loc,
6474 Statements => New_List (Fin_Stmt),
6475 Exception_Handlers => New_List (
6476 Build_Exception_Handler (Final_Data))));
6477 end if;
6479 -- This is the core of the loop, the dimension iterators are added
6480 -- one by one in reverse.
6482 Final_Loop :=
6483 Make_If_Statement (Loc,
6484 Condition =>
6485 Make_Op_Gt (Loc,
6486 Left_Opnd => New_Occurrence_Of (Counter_Id, Loc),
6487 Right_Opnd => Make_Integer_Literal (Loc, 0)),
6489 Then_Statements => New_List (
6490 Make_Assignment_Statement (Loc,
6491 Name => New_Occurrence_Of (Counter_Id, Loc),
6492 Expression =>
6493 Make_Op_Subtract (Loc,
6494 Left_Opnd => New_Occurrence_Of (Counter_Id, Loc),
6495 Right_Opnd => Make_Integer_Literal (Loc, 1)))),
6497 Else_Statements => New_List (Fin_Stmt));
6499 -- Generate all finalization loops starting from the innermost
6500 -- dimension.
6502 -- for Fnn in reverse V'Range (Dim) loop
6503 -- <final loop>
6504 -- end loop;
6506 F := Last (Final_List);
6507 Dim := Num_Dims;
6508 while Present (F) and then Dim > 0 loop
6509 Loop_Id := F;
6510 Prev (F);
6511 Remove (Loop_Id);
6513 Final_Loop :=
6514 Make_Loop_Statement (Loc,
6515 Iteration_Scheme =>
6516 Make_Iteration_Scheme (Loc,
6517 Loop_Parameter_Specification =>
6518 Make_Loop_Parameter_Specification (Loc,
6519 Defining_Identifier => Loop_Id,
6520 Discrete_Subtype_Definition =>
6521 Make_Attribute_Reference (Loc,
6522 Prefix => Make_Identifier (Loc, Name_V),
6523 Attribute_Name => Name_Range,
6524 Expressions => New_List (
6525 Make_Integer_Literal (Loc, Dim))),
6527 Reverse_Present => True)),
6529 Statements => New_List (Final_Loop),
6530 End_Label => Empty);
6532 Dim := Dim - 1;
6533 end loop;
6535 -- Generate the block which contains the finalization loops, the
6536 -- declarations of the abort flag, the exception occurrence, the
6537 -- raised flag and the conditional raise.
6539 -- declare
6540 -- Abort : constant Boolean := Triggered_By_Abort;
6541 -- <or>
6542 -- Abort : constant Boolean := False; -- no abort
6544 -- E : Exception_Occurrence;
6545 -- Raised : Boolean := False;
6547 -- begin
6548 -- Counter :=
6549 -- V'Length (1) *
6550 -- ...
6551 -- V'Length (N) - Counter;
6553 -- <final loop>
6555 -- if Raised and then not Abort then
6556 -- Raise_From_Controlled_Operation (E);
6557 -- end if;
6559 -- raise;
6560 -- end;
6562 Stmts := New_List (Build_Assignment (Counter_Id), Final_Loop);
6564 if Exceptions_OK then
6565 Append_To (Stmts, Build_Raise_Statement (Final_Data));
6566 Append_To (Stmts, Make_Raise_Statement (Loc));
6567 end if;
6569 Final_Block :=
6570 Make_Block_Statement (Loc,
6571 Declarations => Final_Decls,
6572 Handled_Statement_Sequence =>
6573 Make_Handled_Sequence_Of_Statements (Loc,
6574 Statements => Stmts));
6576 -- Otherwise previous errors or a missing full view may prevent the
6577 -- proper freezing of the component type. If this is the case, there
6578 -- is no [Deep_]Finalize primitive to call.
6580 else
6581 Final_Block := Make_Null_Statement (Loc);
6582 end if;
6584 -- Generate the block which contains the initialization call and
6585 -- the partial finalization code.
6587 -- begin
6588 -- [Deep_]Initialize (V (J1, ..., JN));
6590 -- Counter := Counter + 1;
6592 -- exception
6593 -- when others =>
6594 -- <finalization code>
6595 -- end;
6597 Init_Call := Build_Initialization_Call;
6599 -- Only create finalization block if there is a non-trivial
6600 -- call to initialization.
6602 if Present (Init_Call)
6603 and then Nkind (Init_Call) /= N_Null_Statement
6604 then
6605 Init_Loop :=
6606 Make_Block_Statement (Loc,
6607 Handled_Statement_Sequence =>
6608 Make_Handled_Sequence_Of_Statements (Loc,
6609 Statements => New_List (Init_Call),
6610 Exception_Handlers => New_List (
6611 Make_Exception_Handler (Loc,
6612 Exception_Choices => New_List (
6613 Make_Others_Choice (Loc)),
6614 Statements => New_List (Final_Block)))));
6616 Append_To (Statements (Handled_Statement_Sequence (Init_Loop)),
6617 Make_Assignment_Statement (Loc,
6618 Name => New_Occurrence_Of (Counter_Id, Loc),
6619 Expression =>
6620 Make_Op_Add (Loc,
6621 Left_Opnd => New_Occurrence_Of (Counter_Id, Loc),
6622 Right_Opnd => Make_Integer_Literal (Loc, 1))));
6624 -- Generate all initialization loops starting from the innermost
6625 -- dimension.
6627 -- for Jnn in V'Range (Dim) loop
6628 -- <init loop>
6629 -- end loop;
6631 J := Last (Index_List);
6632 Dim := Num_Dims;
6633 while Present (J) and then Dim > 0 loop
6634 Loop_Id := J;
6635 Prev (J);
6636 Remove (Loop_Id);
6638 Init_Loop :=
6639 Make_Loop_Statement (Loc,
6640 Iteration_Scheme =>
6641 Make_Iteration_Scheme (Loc,
6642 Loop_Parameter_Specification =>
6643 Make_Loop_Parameter_Specification (Loc,
6644 Defining_Identifier => Loop_Id,
6645 Discrete_Subtype_Definition =>
6646 Make_Attribute_Reference (Loc,
6647 Prefix => Make_Identifier (Loc, Name_V),
6648 Attribute_Name => Name_Range,
6649 Expressions => New_List (
6650 Make_Integer_Literal (Loc, Dim))))),
6652 Statements => New_List (Init_Loop),
6653 End_Label => Empty);
6655 Dim := Dim - 1;
6656 end loop;
6658 -- Generate the block which contains the counter variable and the
6659 -- initialization loops.
6661 -- declare
6662 -- Counter : Integer := 0;
6663 -- begin
6664 -- <init loop>
6665 -- end;
6667 Init_Block :=
6668 Make_Block_Statement (Loc,
6669 Declarations => New_List (
6670 Make_Object_Declaration (Loc,
6671 Defining_Identifier => Counter_Id,
6672 Object_Definition =>
6673 New_Occurrence_Of (Standard_Integer, Loc),
6674 Expression => Make_Integer_Literal (Loc, 0))),
6676 Handled_Statement_Sequence =>
6677 Make_Handled_Sequence_Of_Statements (Loc,
6678 Statements => New_List (Init_Loop)));
6680 -- Otherwise previous errors or a missing full view may prevent the
6681 -- proper freezing of the component type. If this is the case, there
6682 -- is no [Deep_]Initialize primitive to call.
6684 else
6685 Init_Block := Make_Null_Statement (Loc);
6686 end if;
6688 return New_List (Init_Block);
6689 end Build_Initialize_Statements;
6691 -----------------------
6692 -- New_References_To --
6693 -----------------------
6695 function New_References_To
6696 (L : List_Id;
6697 Loc : Source_Ptr) return List_Id
6699 Refs : constant List_Id := New_List;
6700 Id : Node_Id;
6702 begin
6703 Id := First (L);
6704 while Present (Id) loop
6705 Append_To (Refs, New_Occurrence_Of (Id, Loc));
6706 Next (Id);
6707 end loop;
6709 return Refs;
6710 end New_References_To;
6712 -- Start of processing for Make_Deep_Array_Body
6714 begin
6715 case Prim is
6716 when Address_Case =>
6717 return Make_Finalize_Address_Stmts (Typ);
6719 when Adjust_Case
6720 | Finalize_Case
6722 return Build_Adjust_Or_Finalize_Statements (Typ);
6724 when Initialize_Case =>
6725 return Build_Initialize_Statements (Typ);
6726 end case;
6727 end Make_Deep_Array_Body;
6729 --------------------
6730 -- Make_Deep_Proc --
6731 --------------------
6733 function Make_Deep_Proc
6734 (Prim : Final_Primitives;
6735 Typ : Entity_Id;
6736 Stmts : List_Id) return Entity_Id
6738 Loc : constant Source_Ptr := Sloc (Typ);
6739 Formals : List_Id;
6740 Proc_Id : Entity_Id;
6742 begin
6743 -- Create the object formal, generate:
6744 -- V : System.Address
6746 if Prim = Address_Case then
6747 Formals := New_List (
6748 Make_Parameter_Specification (Loc,
6749 Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
6750 Parameter_Type =>
6751 New_Occurrence_Of (RTE (RE_Address), Loc)));
6753 -- Default case
6755 else
6756 -- V : in out Typ
6758 Formals := New_List (
6759 Make_Parameter_Specification (Loc,
6760 Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
6761 In_Present => True,
6762 Out_Present => True,
6763 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
6765 -- F : Boolean := True
6767 if Prim = Adjust_Case
6768 or else Prim = Finalize_Case
6769 then
6770 Append_To (Formals,
6771 Make_Parameter_Specification (Loc,
6772 Defining_Identifier => Make_Defining_Identifier (Loc, Name_F),
6773 Parameter_Type =>
6774 New_Occurrence_Of (Standard_Boolean, Loc),
6775 Expression =>
6776 New_Occurrence_Of (Standard_True, Loc)));
6777 end if;
6778 end if;
6780 Proc_Id :=
6781 Make_Defining_Identifier (Loc,
6782 Chars => Make_TSS_Name (Typ, Deep_Name_Of (Prim)));
6784 -- Generate:
6785 -- procedure Deep_Initialize / Adjust / Finalize (V : in out <typ>) is
6786 -- begin
6787 -- <stmts>
6788 -- exception -- Finalize and Adjust cases only
6789 -- raise Program_Error;
6790 -- end Deep_Initialize / Adjust / Finalize;
6792 -- or
6794 -- procedure Finalize_Address (V : System.Address) is
6795 -- begin
6796 -- <stmts>
6797 -- end Finalize_Address;
6799 Discard_Node (
6800 Make_Subprogram_Body (Loc,
6801 Specification =>
6802 Make_Procedure_Specification (Loc,
6803 Defining_Unit_Name => Proc_Id,
6804 Parameter_Specifications => Formals),
6806 Declarations => Empty_List,
6808 Handled_Statement_Sequence =>
6809 Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts)));
6811 -- If there are no calls to component initialization, indicate that
6812 -- the procedure is trivial, so prevent calls to it.
6814 if Is_Empty_List (Stmts)
6815 or else Nkind (First (Stmts)) = N_Null_Statement
6816 then
6817 Set_Is_Trivial_Subprogram (Proc_Id);
6818 end if;
6820 return Proc_Id;
6821 end Make_Deep_Proc;
6823 ---------------------------
6824 -- Make_Deep_Record_Body --
6825 ---------------------------
6827 function Make_Deep_Record_Body
6828 (Prim : Final_Primitives;
6829 Typ : Entity_Id;
6830 Is_Local : Boolean := False) return List_Id
6832 Exceptions_OK : constant Boolean := Exceptions_In_Finalization_OK;
6834 function Build_Adjust_Statements (Typ : Entity_Id) return List_Id;
6835 -- Build the statements necessary to adjust a record type. The type may
6836 -- have discriminants and contain variant parts. Generate:
6838 -- begin
6839 -- begin
6840 -- [Deep_]Adjust (V.Comp_1);
6841 -- exception
6842 -- when Id : others =>
6843 -- if not Raised then
6844 -- Raised := True;
6845 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6846 -- end if;
6847 -- end;
6848 -- . . .
6849 -- begin
6850 -- [Deep_]Adjust (V.Comp_N);
6851 -- exception
6852 -- when Id : others =>
6853 -- if not Raised then
6854 -- Raised := True;
6855 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6856 -- end if;
6857 -- end;
6859 -- begin
6860 -- Deep_Adjust (V._parent, False); -- If applicable
6861 -- exception
6862 -- when Id : others =>
6863 -- if not Raised then
6864 -- Raised := True;
6865 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6866 -- end if;
6867 -- end;
6869 -- if F then
6870 -- begin
6871 -- Adjust (V); -- If applicable
6872 -- exception
6873 -- when others =>
6874 -- if not Raised then
6875 -- Raised := True;
6876 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6877 -- end if;
6878 -- end;
6879 -- end if;
6881 -- if Raised and then not Abort then
6882 -- Raise_From_Controlled_Operation (E);
6883 -- end if;
6884 -- end;
6886 function Build_Finalize_Statements (Typ : Entity_Id) return List_Id;
6887 -- Build the statements necessary to finalize a record type. The type
6888 -- may have discriminants and contain variant parts. Generate:
6890 -- declare
6891 -- Abort : constant Boolean := Triggered_By_Abort;
6892 -- <or>
6893 -- Abort : constant Boolean := False; -- no abort
6894 -- E : Exception_Occurrence;
6895 -- Raised : Boolean := False;
6897 -- begin
6898 -- if F then
6899 -- begin
6900 -- Finalize (V); -- If applicable
6901 -- exception
6902 -- when others =>
6903 -- if not Raised then
6904 -- Raised := True;
6905 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6906 -- end if;
6907 -- end;
6908 -- end if;
6910 -- case Variant_1 is
6911 -- when Value_1 =>
6912 -- case State_Counter_N => -- If Is_Local is enabled
6913 -- when N => .
6914 -- goto LN; .
6915 -- ... .
6916 -- when 1 => .
6917 -- goto L1; .
6918 -- when others => .
6919 -- goto L0; .
6920 -- end case; .
6922 -- <<LN>> -- If Is_Local is enabled
6923 -- begin
6924 -- [Deep_]Finalize (V.Comp_N);
6925 -- exception
6926 -- when others =>
6927 -- if not Raised then
6928 -- Raised := True;
6929 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6930 -- end if;
6931 -- end;
6932 -- . . .
6933 -- <<L1>>
6934 -- begin
6935 -- [Deep_]Finalize (V.Comp_1);
6936 -- exception
6937 -- when others =>
6938 -- if not Raised then
6939 -- Raised := True;
6940 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6941 -- end if;
6942 -- end;
6943 -- <<L0>>
6944 -- end case;
6946 -- case State_Counter_1 => -- If Is_Local is enabled
6947 -- when M => .
6948 -- goto LM; .
6949 -- ...
6951 -- begin
6952 -- Deep_Finalize (V._parent, False); -- If applicable
6953 -- exception
6954 -- when Id : others =>
6955 -- if not Raised then
6956 -- Raised := True;
6957 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6958 -- end if;
6959 -- end;
6961 -- if Raised and then not Abort then
6962 -- Raise_From_Controlled_Operation (E);
6963 -- end if;
6964 -- end;
6966 function Parent_Field_Type (Typ : Entity_Id) return Entity_Id;
6967 -- Given a derived tagged type Typ, traverse all components, find field
6968 -- _parent and return its type.
6970 procedure Preprocess_Components
6971 (Comps : Node_Id;
6972 Num_Comps : out Nat;
6973 Has_POC : out Boolean);
6974 -- Examine all components in component list Comps, count all controlled
6975 -- components and determine whether at least one of them is per-object
6976 -- constrained. Component _parent is always skipped.
6978 -----------------------------
6979 -- Build_Adjust_Statements --
6980 -----------------------------
6982 function Build_Adjust_Statements (Typ : Entity_Id) return List_Id is
6983 Loc : constant Source_Ptr := Sloc (Typ);
6984 Typ_Def : constant Node_Id := Type_Definition (Parent (Typ));
6986 Finalizer_Data : Finalization_Exception_Data;
6988 function Process_Component_List_For_Adjust
6989 (Comps : Node_Id) return List_Id;
6990 -- Build all necessary adjust statements for a single component list
6992 ---------------------------------------
6993 -- Process_Component_List_For_Adjust --
6994 ---------------------------------------
6996 function Process_Component_List_For_Adjust
6997 (Comps : Node_Id) return List_Id
6999 Stmts : constant List_Id := New_List;
7001 procedure Process_Component_For_Adjust (Decl : Node_Id);
7002 -- Process the declaration of a single controlled component
7004 ----------------------------------
7005 -- Process_Component_For_Adjust --
7006 ----------------------------------
7008 procedure Process_Component_For_Adjust (Decl : Node_Id) is
7009 Id : constant Entity_Id := Defining_Identifier (Decl);
7010 Typ : constant Entity_Id := Etype (Id);
7012 Adj_Call : Node_Id;
7014 begin
7015 -- begin
7016 -- [Deep_]Adjust (V.Id);
7018 -- exception
7019 -- when others =>
7020 -- if not Raised then
7021 -- Raised := True;
7022 -- Save_Occurrence (E, Get_Current_Excep.all.all);
7023 -- end if;
7024 -- end;
7026 Adj_Call :=
7027 Make_Adjust_Call (
7028 Obj_Ref =>
7029 Make_Selected_Component (Loc,
7030 Prefix => Make_Identifier (Loc, Name_V),
7031 Selector_Name => Make_Identifier (Loc, Chars (Id))),
7032 Typ => Typ);
7034 -- Guard against a missing [Deep_]Adjust when the component
7035 -- type was not properly frozen.
7037 if Present (Adj_Call) then
7038 if Exceptions_OK then
7039 Adj_Call :=
7040 Make_Block_Statement (Loc,
7041 Handled_Statement_Sequence =>
7042 Make_Handled_Sequence_Of_Statements (Loc,
7043 Statements => New_List (Adj_Call),
7044 Exception_Handlers => New_List (
7045 Build_Exception_Handler (Finalizer_Data))));
7046 end if;
7048 Append_To (Stmts, Adj_Call);
7049 end if;
7050 end Process_Component_For_Adjust;
7052 -- Local variables
7054 Decl : Node_Id;
7055 Decl_Id : Entity_Id;
7056 Decl_Typ : Entity_Id;
7057 Has_POC : Boolean;
7058 Num_Comps : Nat;
7059 Var_Case : Node_Id;
7061 -- Start of processing for Process_Component_List_For_Adjust
7063 begin
7064 -- Perform an initial check, determine the number of controlled
7065 -- components in the current list and whether at least one of them
7066 -- is per-object constrained.
7068 Preprocess_Components (Comps, Num_Comps, Has_POC);
7070 -- The processing in this routine is done in the following order:
7071 -- 1) Regular components
7072 -- 2) Per-object constrained components
7073 -- 3) Variant parts
7075 if Num_Comps > 0 then
7077 -- Process all regular components in order of declarations
7079 Decl := First_Non_Pragma (Component_Items (Comps));
7080 while Present (Decl) loop
7081 Decl_Id := Defining_Identifier (Decl);
7082 Decl_Typ := Etype (Decl_Id);
7084 -- Skip _parent as well as per-object constrained components
7086 if Chars (Decl_Id) /= Name_uParent
7087 and then Needs_Finalization (Decl_Typ)
7088 then
7089 if Has_Access_Constraint (Decl_Id)
7090 and then No (Expression (Decl))
7091 then
7092 null;
7093 else
7094 Process_Component_For_Adjust (Decl);
7095 end if;
7096 end if;
7098 Next_Non_Pragma (Decl);
7099 end loop;
7101 -- Process all per-object constrained components in order of
7102 -- declarations.
7104 if Has_POC then
7105 Decl := First_Non_Pragma (Component_Items (Comps));
7106 while Present (Decl) loop
7107 Decl_Id := Defining_Identifier (Decl);
7108 Decl_Typ := Etype (Decl_Id);
7110 -- Skip _parent
7112 if Chars (Decl_Id) /= Name_uParent
7113 and then Needs_Finalization (Decl_Typ)
7114 and then Has_Access_Constraint (Decl_Id)
7115 and then No (Expression (Decl))
7116 then
7117 Process_Component_For_Adjust (Decl);
7118 end if;
7120 Next_Non_Pragma (Decl);
7121 end loop;
7122 end if;
7123 end if;
7125 -- Process all variants, if any
7127 Var_Case := Empty;
7128 if Present (Variant_Part (Comps)) then
7129 declare
7130 Var_Alts : constant List_Id := New_List;
7131 Var : Node_Id;
7133 begin
7134 Var := First_Non_Pragma (Variants (Variant_Part (Comps)));
7135 while Present (Var) loop
7137 -- Generate:
7138 -- when <discrete choices> =>
7139 -- <adjust statements>
7141 Append_To (Var_Alts,
7142 Make_Case_Statement_Alternative (Loc,
7143 Discrete_Choices =>
7144 New_Copy_List (Discrete_Choices (Var)),
7145 Statements =>
7146 Process_Component_List_For_Adjust (
7147 Component_List (Var))));
7149 Next_Non_Pragma (Var);
7150 end loop;
7152 -- Generate:
7153 -- case V.<discriminant> is
7154 -- when <discrete choices 1> =>
7155 -- <adjust statements 1>
7156 -- ...
7157 -- when <discrete choices N> =>
7158 -- <adjust statements N>
7159 -- end case;
7161 Var_Case :=
7162 Make_Case_Statement (Loc,
7163 Expression =>
7164 Make_Selected_Component (Loc,
7165 Prefix => Make_Identifier (Loc, Name_V),
7166 Selector_Name =>
7167 Make_Identifier (Loc,
7168 Chars => Chars (Name (Variant_Part (Comps))))),
7169 Alternatives => Var_Alts);
7170 end;
7171 end if;
7173 -- Add the variant case statement to the list of statements
7175 if Present (Var_Case) then
7176 Append_To (Stmts, Var_Case);
7177 end if;
7179 -- If the component list did not have any controlled components
7180 -- nor variants, return null.
7182 if Is_Empty_List (Stmts) then
7183 Append_To (Stmts, Make_Null_Statement (Loc));
7184 end if;
7186 return Stmts;
7187 end Process_Component_List_For_Adjust;
7189 -- Local variables
7191 Bod_Stmts : List_Id := No_List;
7192 Finalizer_Decls : List_Id := No_List;
7193 Rec_Def : Node_Id;
7195 -- Start of processing for Build_Adjust_Statements
7197 begin
7198 Finalizer_Decls := New_List;
7199 Build_Object_Declarations (Finalizer_Data, Finalizer_Decls, Loc);
7201 if Nkind (Typ_Def) = N_Derived_Type_Definition then
7202 Rec_Def := Record_Extension_Part (Typ_Def);
7203 else
7204 Rec_Def := Typ_Def;
7205 end if;
7207 -- Create an adjust sequence for all record components
7209 if Present (Component_List (Rec_Def)) then
7210 Bod_Stmts :=
7211 Process_Component_List_For_Adjust (Component_List (Rec_Def));
7212 end if;
7214 -- A derived record type must adjust all inherited components. This
7215 -- action poses the following problem:
7217 -- procedure Deep_Adjust (Obj : in out Parent_Typ) is
7218 -- begin
7219 -- Adjust (Obj);
7220 -- ...
7222 -- procedure Deep_Adjust (Obj : in out Derived_Typ) is
7223 -- begin
7224 -- Deep_Adjust (Obj._parent);
7225 -- ...
7226 -- Adjust (Obj);
7227 -- ...
7229 -- Adjusting the derived type will invoke Adjust of the parent and
7230 -- then that of the derived type. This is undesirable because both
7231 -- routines may modify shared components. Only the Adjust of the
7232 -- derived type should be invoked.
7234 -- To prevent this double adjustment of shared components,
7235 -- Deep_Adjust uses a flag to control the invocation of Adjust:
7237 -- procedure Deep_Adjust
7238 -- (Obj : in out Some_Type;
7239 -- Flag : Boolean := True)
7240 -- is
7241 -- begin
7242 -- if Flag then
7243 -- Adjust (Obj);
7244 -- end if;
7245 -- ...
7247 -- When Deep_Adjust is invokes for field _parent, a value of False is
7248 -- provided for the flag:
7250 -- Deep_Adjust (Obj._parent, False);
7252 if Is_Tagged_Type (Typ) and then Is_Derived_Type (Typ) then
7253 declare
7254 Par_Typ : constant Entity_Id := Parent_Field_Type (Typ);
7255 Adj_Stmt : Node_Id;
7256 Call : Node_Id;
7258 begin
7259 if Needs_Finalization (Par_Typ) then
7260 Call :=
7261 Make_Adjust_Call
7262 (Obj_Ref =>
7263 Make_Selected_Component (Loc,
7264 Prefix => Make_Identifier (Loc, Name_V),
7265 Selector_Name =>
7266 Make_Identifier (Loc, Name_uParent)),
7267 Typ => Par_Typ,
7268 Skip_Self => True);
7270 -- Generate:
7271 -- begin
7272 -- Deep_Adjust (V._parent, False);
7274 -- exception
7275 -- when Id : others =>
7276 -- if not Raised then
7277 -- Raised := True;
7278 -- Save_Occurrence (E,
7279 -- Get_Current_Excep.all.all);
7280 -- end if;
7281 -- end;
7283 if Present (Call) then
7284 Adj_Stmt := Call;
7286 if Exceptions_OK then
7287 Adj_Stmt :=
7288 Make_Block_Statement (Loc,
7289 Handled_Statement_Sequence =>
7290 Make_Handled_Sequence_Of_Statements (Loc,
7291 Statements => New_List (Adj_Stmt),
7292 Exception_Handlers => New_List (
7293 Build_Exception_Handler (Finalizer_Data))));
7294 end if;
7296 Prepend_To (Bod_Stmts, Adj_Stmt);
7297 end if;
7298 end if;
7299 end;
7300 end if;
7302 -- Adjust the object. This action must be performed last after all
7303 -- components have been adjusted.
7305 if Is_Controlled (Typ) then
7306 declare
7307 Adj_Stmt : Node_Id;
7308 Proc : Entity_Id;
7310 begin
7311 Proc := Find_Optional_Prim_Op (Typ, Name_Adjust);
7313 -- Generate:
7314 -- if F then
7315 -- begin
7316 -- Adjust (V);
7318 -- exception
7319 -- when others =>
7320 -- if not Raised then
7321 -- Raised := True;
7322 -- Save_Occurrence (E,
7323 -- Get_Current_Excep.all.all);
7324 -- end if;
7325 -- end;
7326 -- end if;
7328 if Present (Proc) then
7329 Adj_Stmt :=
7330 Make_Procedure_Call_Statement (Loc,
7331 Name => New_Occurrence_Of (Proc, Loc),
7332 Parameter_Associations => New_List (
7333 Make_Identifier (Loc, Name_V)));
7335 if Exceptions_OK then
7336 Adj_Stmt :=
7337 Make_Block_Statement (Loc,
7338 Handled_Statement_Sequence =>
7339 Make_Handled_Sequence_Of_Statements (Loc,
7340 Statements => New_List (Adj_Stmt),
7341 Exception_Handlers => New_List (
7342 Build_Exception_Handler
7343 (Finalizer_Data))));
7344 end if;
7346 Append_To (Bod_Stmts,
7347 Make_If_Statement (Loc,
7348 Condition => Make_Identifier (Loc, Name_F),
7349 Then_Statements => New_List (Adj_Stmt)));
7350 end if;
7351 end;
7352 end if;
7354 -- At this point either all adjustment statements have been generated
7355 -- or the type is not controlled.
7357 if Is_Empty_List (Bod_Stmts) then
7358 Append_To (Bod_Stmts, Make_Null_Statement (Loc));
7360 return Bod_Stmts;
7362 -- Generate:
7363 -- declare
7364 -- Abort : constant Boolean := Triggered_By_Abort;
7365 -- <or>
7366 -- Abort : constant Boolean := False; -- no abort
7368 -- E : Exception_Occurrence;
7369 -- Raised : Boolean := False;
7371 -- begin
7372 -- <adjust statements>
7374 -- if Raised and then not Abort then
7375 -- Raise_From_Controlled_Operation (E);
7376 -- end if;
7377 -- end;
7379 else
7380 if Exceptions_OK then
7381 Append_To (Bod_Stmts, Build_Raise_Statement (Finalizer_Data));
7382 end if;
7384 return
7385 New_List (
7386 Make_Block_Statement (Loc,
7387 Declarations =>
7388 Finalizer_Decls,
7389 Handled_Statement_Sequence =>
7390 Make_Handled_Sequence_Of_Statements (Loc, Bod_Stmts)));
7391 end if;
7392 end Build_Adjust_Statements;
7394 -------------------------------
7395 -- Build_Finalize_Statements --
7396 -------------------------------
7398 function Build_Finalize_Statements (Typ : Entity_Id) return List_Id is
7399 Loc : constant Source_Ptr := Sloc (Typ);
7400 Typ_Def : constant Node_Id := Type_Definition (Parent (Typ));
7402 Counter : Int := 0;
7403 Finalizer_Data : Finalization_Exception_Data;
7405 function Process_Component_List_For_Finalize
7406 (Comps : Node_Id) return List_Id;
7407 -- Build all necessary finalization statements for a single component
7408 -- list. The statements may include a jump circuitry if flag Is_Local
7409 -- is enabled.
7411 -----------------------------------------
7412 -- Process_Component_List_For_Finalize --
7413 -----------------------------------------
7415 function Process_Component_List_For_Finalize
7416 (Comps : Node_Id) return List_Id
7418 procedure Process_Component_For_Finalize
7419 (Decl : Node_Id;
7420 Alts : List_Id;
7421 Decls : List_Id;
7422 Stmts : List_Id;
7423 Num_Comps : in out Nat);
7424 -- Process the declaration of a single controlled component. If
7425 -- flag Is_Local is enabled, create the corresponding label and
7426 -- jump circuitry. Alts is the list of case alternatives, Decls
7427 -- is the top level declaration list where labels are declared
7428 -- and Stmts is the list of finalization actions. Num_Comps
7429 -- denotes the current number of components needing finalization.
7431 ------------------------------------
7432 -- Process_Component_For_Finalize --
7433 ------------------------------------
7435 procedure Process_Component_For_Finalize
7436 (Decl : Node_Id;
7437 Alts : List_Id;
7438 Decls : List_Id;
7439 Stmts : List_Id;
7440 Num_Comps : in out Nat)
7442 Id : constant Entity_Id := Defining_Identifier (Decl);
7443 Typ : constant Entity_Id := Etype (Id);
7444 Fin_Call : Node_Id;
7446 begin
7447 if Is_Local then
7448 declare
7449 Label : Node_Id;
7450 Label_Id : Entity_Id;
7452 begin
7453 -- Generate:
7454 -- LN : label;
7456 Label_Id :=
7457 Make_Identifier (Loc,
7458 Chars => New_External_Name ('L', Num_Comps));
7459 Set_Entity (Label_Id,
7460 Make_Defining_Identifier (Loc, Chars (Label_Id)));
7461 Label := Make_Label (Loc, Label_Id);
7463 Append_To (Decls,
7464 Make_Implicit_Label_Declaration (Loc,
7465 Defining_Identifier => Entity (Label_Id),
7466 Label_Construct => Label));
7468 -- Generate:
7469 -- when N =>
7470 -- goto LN;
7472 Append_To (Alts,
7473 Make_Case_Statement_Alternative (Loc,
7474 Discrete_Choices => New_List (
7475 Make_Integer_Literal (Loc, Num_Comps)),
7477 Statements => New_List (
7478 Make_Goto_Statement (Loc,
7479 Name =>
7480 New_Occurrence_Of (Entity (Label_Id), Loc)))));
7482 -- Generate:
7483 -- <<LN>>
7485 Append_To (Stmts, Label);
7487 -- Decrease the number of components to be processed.
7488 -- This action yields a new Label_Id in future calls.
7490 Num_Comps := Num_Comps - 1;
7491 end;
7492 end if;
7494 -- Generate:
7495 -- [Deep_]Finalize (V.Id); -- No_Exception_Propagation
7497 -- begin -- Exception handlers allowed
7498 -- [Deep_]Finalize (V.Id);
7499 -- exception
7500 -- when others =>
7501 -- if not Raised then
7502 -- Raised := True;
7503 -- Save_Occurrence (E,
7504 -- Get_Current_Excep.all.all);
7505 -- end if;
7506 -- end;
7508 Fin_Call :=
7509 Make_Final_Call
7510 (Obj_Ref =>
7511 Make_Selected_Component (Loc,
7512 Prefix => Make_Identifier (Loc, Name_V),
7513 Selector_Name => Make_Identifier (Loc, Chars (Id))),
7514 Typ => Typ);
7516 -- Guard against a missing [Deep_]Finalize when the component
7517 -- type was not properly frozen.
7519 if Present (Fin_Call) then
7520 if Exceptions_OK then
7521 Fin_Call :=
7522 Make_Block_Statement (Loc,
7523 Handled_Statement_Sequence =>
7524 Make_Handled_Sequence_Of_Statements (Loc,
7525 Statements => New_List (Fin_Call),
7526 Exception_Handlers => New_List (
7527 Build_Exception_Handler (Finalizer_Data))));
7528 end if;
7530 Append_To (Stmts, Fin_Call);
7531 end if;
7532 end Process_Component_For_Finalize;
7534 -- Local variables
7536 Alts : List_Id;
7537 Counter_Id : Entity_Id := Empty;
7538 Decl : Node_Id;
7539 Decl_Id : Entity_Id;
7540 Decl_Typ : Entity_Id;
7541 Decls : List_Id;
7542 Has_POC : Boolean;
7543 Jump_Block : Node_Id;
7544 Label : Node_Id;
7545 Label_Id : Entity_Id;
7546 Num_Comps : Nat;
7547 Stmts : List_Id;
7548 Var_Case : Node_Id;
7550 -- Start of processing for Process_Component_List_For_Finalize
7552 begin
7553 -- Perform an initial check, look for controlled and per-object
7554 -- constrained components.
7556 Preprocess_Components (Comps, Num_Comps, Has_POC);
7558 -- Create a state counter to service the current component list.
7559 -- This step is performed before the variants are inspected in
7560 -- order to generate the same state counter names as those from
7561 -- Build_Initialize_Statements.
7563 if Num_Comps > 0 and then Is_Local then
7564 Counter := Counter + 1;
7566 Counter_Id :=
7567 Make_Defining_Identifier (Loc,
7568 Chars => New_External_Name ('C', Counter));
7569 end if;
7571 -- Process the component in the following order:
7572 -- 1) Variants
7573 -- 2) Per-object constrained components
7574 -- 3) Regular components
7576 -- Start with the variant parts
7578 Var_Case := Empty;
7579 if Present (Variant_Part (Comps)) then
7580 declare
7581 Var_Alts : constant List_Id := New_List;
7582 Var : Node_Id;
7584 begin
7585 Var := First_Non_Pragma (Variants (Variant_Part (Comps)));
7586 while Present (Var) loop
7588 -- Generate:
7589 -- when <discrete choices> =>
7590 -- <finalize statements>
7592 Append_To (Var_Alts,
7593 Make_Case_Statement_Alternative (Loc,
7594 Discrete_Choices =>
7595 New_Copy_List (Discrete_Choices (Var)),
7596 Statements =>
7597 Process_Component_List_For_Finalize (
7598 Component_List (Var))));
7600 Next_Non_Pragma (Var);
7601 end loop;
7603 -- Generate:
7604 -- case V.<discriminant> is
7605 -- when <discrete choices 1> =>
7606 -- <finalize statements 1>
7607 -- ...
7608 -- when <discrete choices N> =>
7609 -- <finalize statements N>
7610 -- end case;
7612 Var_Case :=
7613 Make_Case_Statement (Loc,
7614 Expression =>
7615 Make_Selected_Component (Loc,
7616 Prefix => Make_Identifier (Loc, Name_V),
7617 Selector_Name =>
7618 Make_Identifier (Loc,
7619 Chars => Chars (Name (Variant_Part (Comps))))),
7620 Alternatives => Var_Alts);
7621 end;
7622 end if;
7624 -- The current component list does not have a single controlled
7625 -- component, however it may contain variants. Return the case
7626 -- statement for the variants or nothing.
7628 if Num_Comps = 0 then
7629 if Present (Var_Case) then
7630 return New_List (Var_Case);
7631 else
7632 return New_List (Make_Null_Statement (Loc));
7633 end if;
7634 end if;
7636 -- Prepare all lists
7638 Alts := New_List;
7639 Decls := New_List;
7640 Stmts := New_List;
7642 -- Process all per-object constrained components in reverse order
7644 if Has_POC then
7645 Decl := Last_Non_Pragma (Component_Items (Comps));
7646 while Present (Decl) loop
7647 Decl_Id := Defining_Identifier (Decl);
7648 Decl_Typ := Etype (Decl_Id);
7650 -- Skip _parent
7652 if Chars (Decl_Id) /= Name_uParent
7653 and then Needs_Finalization (Decl_Typ)
7654 and then Has_Access_Constraint (Decl_Id)
7655 and then No (Expression (Decl))
7656 then
7657 Process_Component_For_Finalize
7658 (Decl, Alts, Decls, Stmts, Num_Comps);
7659 end if;
7661 Prev_Non_Pragma (Decl);
7662 end loop;
7663 end if;
7665 -- Process the rest of the components in reverse order
7667 Decl := Last_Non_Pragma (Component_Items (Comps));
7668 while Present (Decl) loop
7669 Decl_Id := Defining_Identifier (Decl);
7670 Decl_Typ := Etype (Decl_Id);
7672 -- Skip _parent
7674 if Chars (Decl_Id) /= Name_uParent
7675 and then Needs_Finalization (Decl_Typ)
7676 then
7677 -- Skip per-object constrained components since they were
7678 -- handled in the above step.
7680 if Has_Access_Constraint (Decl_Id)
7681 and then No (Expression (Decl))
7682 then
7683 null;
7684 else
7685 Process_Component_For_Finalize
7686 (Decl, Alts, Decls, Stmts, Num_Comps);
7687 end if;
7688 end if;
7690 Prev_Non_Pragma (Decl);
7691 end loop;
7693 -- Generate:
7694 -- declare
7695 -- LN : label; -- If Is_Local is enabled
7696 -- ... .
7697 -- L0 : label; .
7699 -- begin .
7700 -- case CounterX is .
7701 -- when N => .
7702 -- goto LN; .
7703 -- ... .
7704 -- when 1 => .
7705 -- goto L1; .
7706 -- when others => .
7707 -- goto L0; .
7708 -- end case; .
7710 -- <<LN>> -- If Is_Local is enabled
7711 -- begin
7712 -- [Deep_]Finalize (V.CompY);
7713 -- exception
7714 -- when Id : others =>
7715 -- if not Raised then
7716 -- Raised := True;
7717 -- Save_Occurrence (E,
7718 -- Get_Current_Excep.all.all);
7719 -- end if;
7720 -- end;
7721 -- ...
7722 -- <<L0>> -- If Is_Local is enabled
7723 -- end;
7725 if Is_Local then
7727 -- Add the declaration of default jump location L0, its
7728 -- corresponding alternative and its place in the statements.
7730 Label_Id := Make_Identifier (Loc, New_External_Name ('L', 0));
7731 Set_Entity (Label_Id,
7732 Make_Defining_Identifier (Loc, Chars (Label_Id)));
7733 Label := Make_Label (Loc, Label_Id);
7735 Append_To (Decls, -- declaration
7736 Make_Implicit_Label_Declaration (Loc,
7737 Defining_Identifier => Entity (Label_Id),
7738 Label_Construct => Label));
7740 Append_To (Alts, -- alternative
7741 Make_Case_Statement_Alternative (Loc,
7742 Discrete_Choices => New_List (
7743 Make_Others_Choice (Loc)),
7745 Statements => New_List (
7746 Make_Goto_Statement (Loc,
7747 Name => New_Occurrence_Of (Entity (Label_Id), Loc)))));
7749 Append_To (Stmts, Label); -- statement
7751 -- Create the jump block
7753 Prepend_To (Stmts,
7754 Make_Case_Statement (Loc,
7755 Expression => Make_Identifier (Loc, Chars (Counter_Id)),
7756 Alternatives => Alts));
7757 end if;
7759 Jump_Block :=
7760 Make_Block_Statement (Loc,
7761 Declarations => Decls,
7762 Handled_Statement_Sequence =>
7763 Make_Handled_Sequence_Of_Statements (Loc, Stmts));
7765 if Present (Var_Case) then
7766 return New_List (Var_Case, Jump_Block);
7767 else
7768 return New_List (Jump_Block);
7769 end if;
7770 end Process_Component_List_For_Finalize;
7772 -- Local variables
7774 Bod_Stmts : List_Id := No_List;
7775 Finalizer_Decls : List_Id := No_List;
7776 Rec_Def : Node_Id;
7778 -- Start of processing for Build_Finalize_Statements
7780 begin
7781 Finalizer_Decls := New_List;
7782 Build_Object_Declarations (Finalizer_Data, Finalizer_Decls, Loc);
7784 if Nkind (Typ_Def) = N_Derived_Type_Definition then
7785 Rec_Def := Record_Extension_Part (Typ_Def);
7786 else
7787 Rec_Def := Typ_Def;
7788 end if;
7790 -- Create a finalization sequence for all record components
7792 if Present (Component_List (Rec_Def)) then
7793 Bod_Stmts :=
7794 Process_Component_List_For_Finalize (Component_List (Rec_Def));
7795 end if;
7797 -- A derived record type must finalize all inherited components. This
7798 -- action poses the following problem:
7800 -- procedure Deep_Finalize (Obj : in out Parent_Typ) is
7801 -- begin
7802 -- Finalize (Obj);
7803 -- ...
7805 -- procedure Deep_Finalize (Obj : in out Derived_Typ) is
7806 -- begin
7807 -- Deep_Finalize (Obj._parent);
7808 -- ...
7809 -- Finalize (Obj);
7810 -- ...
7812 -- Finalizing the derived type will invoke Finalize of the parent and
7813 -- then that of the derived type. This is undesirable because both
7814 -- routines may modify shared components. Only the Finalize of the
7815 -- derived type should be invoked.
7817 -- To prevent this double adjustment of shared components,
7818 -- Deep_Finalize uses a flag to control the invocation of Finalize:
7820 -- procedure Deep_Finalize
7821 -- (Obj : in out Some_Type;
7822 -- Flag : Boolean := True)
7823 -- is
7824 -- begin
7825 -- if Flag then
7826 -- Finalize (Obj);
7827 -- end if;
7828 -- ...
7830 -- When Deep_Finalize is invoked for field _parent, a value of False
7831 -- is provided for the flag:
7833 -- Deep_Finalize (Obj._parent, False);
7835 if Is_Tagged_Type (Typ) and then Is_Derived_Type (Typ) then
7836 declare
7837 Par_Typ : constant Entity_Id := Parent_Field_Type (Typ);
7838 Call : Node_Id;
7839 Fin_Stmt : Node_Id;
7841 begin
7842 if Needs_Finalization (Par_Typ) then
7843 Call :=
7844 Make_Final_Call
7845 (Obj_Ref =>
7846 Make_Selected_Component (Loc,
7847 Prefix => Make_Identifier (Loc, Name_V),
7848 Selector_Name =>
7849 Make_Identifier (Loc, Name_uParent)),
7850 Typ => Par_Typ,
7851 Skip_Self => True);
7853 -- Generate:
7854 -- begin
7855 -- Deep_Finalize (V._parent, False);
7857 -- exception
7858 -- when Id : others =>
7859 -- if not Raised then
7860 -- Raised := True;
7861 -- Save_Occurrence (E,
7862 -- Get_Current_Excep.all.all);
7863 -- end if;
7864 -- end;
7866 if Present (Call) then
7867 Fin_Stmt := Call;
7869 if Exceptions_OK then
7870 Fin_Stmt :=
7871 Make_Block_Statement (Loc,
7872 Handled_Statement_Sequence =>
7873 Make_Handled_Sequence_Of_Statements (Loc,
7874 Statements => New_List (Fin_Stmt),
7875 Exception_Handlers => New_List (
7876 Build_Exception_Handler
7877 (Finalizer_Data))));
7878 end if;
7880 Append_To (Bod_Stmts, Fin_Stmt);
7881 end if;
7882 end if;
7883 end;
7884 end if;
7886 -- Finalize the object. This action must be performed first before
7887 -- all components have been finalized.
7889 if Is_Controlled (Typ) and then not Is_Local then
7890 declare
7891 Fin_Stmt : Node_Id;
7892 Proc : Entity_Id;
7894 begin
7895 Proc := Find_Optional_Prim_Op (Typ, Name_Finalize);
7897 -- Generate:
7898 -- if F then
7899 -- begin
7900 -- Finalize (V);
7902 -- exception
7903 -- when others =>
7904 -- if not Raised then
7905 -- Raised := True;
7906 -- Save_Occurrence (E,
7907 -- Get_Current_Excep.all.all);
7908 -- end if;
7909 -- end;
7910 -- end if;
7912 if Present (Proc) then
7913 Fin_Stmt :=
7914 Make_Procedure_Call_Statement (Loc,
7915 Name => New_Occurrence_Of (Proc, Loc),
7916 Parameter_Associations => New_List (
7917 Make_Identifier (Loc, Name_V)));
7919 if Exceptions_OK then
7920 Fin_Stmt :=
7921 Make_Block_Statement (Loc,
7922 Handled_Statement_Sequence =>
7923 Make_Handled_Sequence_Of_Statements (Loc,
7924 Statements => New_List (Fin_Stmt),
7925 Exception_Handlers => New_List (
7926 Build_Exception_Handler
7927 (Finalizer_Data))));
7928 end if;
7930 Prepend_To (Bod_Stmts,
7931 Make_If_Statement (Loc,
7932 Condition => Make_Identifier (Loc, Name_F),
7933 Then_Statements => New_List (Fin_Stmt)));
7934 end if;
7935 end;
7936 end if;
7938 -- At this point either all finalization statements have been
7939 -- generated or the type is not controlled.
7941 if No (Bod_Stmts) then
7942 return New_List (Make_Null_Statement (Loc));
7944 -- Generate:
7945 -- declare
7946 -- Abort : constant Boolean := Triggered_By_Abort;
7947 -- <or>
7948 -- Abort : constant Boolean := False; -- no abort
7950 -- E : Exception_Occurrence;
7951 -- Raised : Boolean := False;
7953 -- begin
7954 -- <finalize statements>
7956 -- if Raised and then not Abort then
7957 -- Raise_From_Controlled_Operation (E);
7958 -- end if;
7959 -- end;
7961 else
7962 if Exceptions_OK then
7963 Append_To (Bod_Stmts, Build_Raise_Statement (Finalizer_Data));
7964 end if;
7966 return
7967 New_List (
7968 Make_Block_Statement (Loc,
7969 Declarations =>
7970 Finalizer_Decls,
7971 Handled_Statement_Sequence =>
7972 Make_Handled_Sequence_Of_Statements (Loc, Bod_Stmts)));
7973 end if;
7974 end Build_Finalize_Statements;
7976 -----------------------
7977 -- Parent_Field_Type --
7978 -----------------------
7980 function Parent_Field_Type (Typ : Entity_Id) return Entity_Id is
7981 Field : Entity_Id;
7983 begin
7984 Field := First_Entity (Typ);
7985 while Present (Field) loop
7986 if Chars (Field) = Name_uParent then
7987 return Etype (Field);
7988 end if;
7990 Next_Entity (Field);
7991 end loop;
7993 -- A derived tagged type should always have a parent field
7995 raise Program_Error;
7996 end Parent_Field_Type;
7998 ---------------------------
7999 -- Preprocess_Components --
8000 ---------------------------
8002 procedure Preprocess_Components
8003 (Comps : Node_Id;
8004 Num_Comps : out Nat;
8005 Has_POC : out Boolean)
8007 Decl : Node_Id;
8008 Id : Entity_Id;
8009 Typ : Entity_Id;
8011 begin
8012 Num_Comps := 0;
8013 Has_POC := False;
8015 Decl := First_Non_Pragma (Component_Items (Comps));
8016 while Present (Decl) loop
8017 Id := Defining_Identifier (Decl);
8018 Typ := Etype (Id);
8020 -- Skip field _parent
8022 if Chars (Id) /= Name_uParent
8023 and then Needs_Finalization (Typ)
8024 then
8025 Num_Comps := Num_Comps + 1;
8027 if Has_Access_Constraint (Id)
8028 and then No (Expression (Decl))
8029 then
8030 Has_POC := True;
8031 end if;
8032 end if;
8034 Next_Non_Pragma (Decl);
8035 end loop;
8036 end Preprocess_Components;
8038 -- Start of processing for Make_Deep_Record_Body
8040 begin
8041 case Prim is
8042 when Address_Case =>
8043 return Make_Finalize_Address_Stmts (Typ);
8045 when Adjust_Case =>
8046 return Build_Adjust_Statements (Typ);
8048 when Finalize_Case =>
8049 return Build_Finalize_Statements (Typ);
8051 when Initialize_Case =>
8052 declare
8053 Loc : constant Source_Ptr := Sloc (Typ);
8055 begin
8056 if Is_Controlled (Typ) then
8057 return New_List (
8058 Make_Procedure_Call_Statement (Loc,
8059 Name =>
8060 New_Occurrence_Of
8061 (Find_Prim_Op (Typ, Name_Of (Prim)), Loc),
8062 Parameter_Associations => New_List (
8063 Make_Identifier (Loc, Name_V))));
8064 else
8065 return Empty_List;
8066 end if;
8067 end;
8068 end case;
8069 end Make_Deep_Record_Body;
8071 ----------------------
8072 -- Make_Final_Call --
8073 ----------------------
8075 function Make_Final_Call
8076 (Obj_Ref : Node_Id;
8077 Typ : Entity_Id;
8078 Skip_Self : Boolean := False) return Node_Id
8080 Loc : constant Source_Ptr := Sloc (Obj_Ref);
8081 Atyp : Entity_Id;
8082 Fin_Id : Entity_Id := Empty;
8083 Ref : Node_Id;
8084 Utyp : Entity_Id;
8086 begin
8087 Ref := Obj_Ref;
8089 -- Recover the proper type which contains [Deep_]Finalize
8091 if Is_Class_Wide_Type (Typ) then
8092 Utyp := Root_Type (Typ);
8093 Atyp := Utyp;
8095 elsif Is_Concurrent_Type (Typ) then
8096 Utyp := Corresponding_Record_Type (Typ);
8097 Atyp := Empty;
8098 Ref := Convert_Concurrent (Ref, Typ);
8100 elsif Is_Private_Type (Typ)
8101 and then Present (Full_View (Typ))
8102 and then Is_Concurrent_Type (Full_View (Typ))
8103 then
8104 Utyp := Corresponding_Record_Type (Full_View (Typ));
8105 Atyp := Typ;
8106 Ref := Convert_Concurrent (Ref, Full_View (Typ));
8108 else
8109 Utyp := Typ;
8110 Atyp := Typ;
8111 end if;
8113 Utyp := Underlying_Type (Base_Type (Utyp));
8114 Set_Assignment_OK (Ref);
8116 -- Deal with untagged derivation of private views. If the parent type
8117 -- is a protected type, Deep_Finalize is found on the corresponding
8118 -- record of the ancestor.
8120 if Is_Untagged_Derivation (Typ) then
8121 if Is_Protected_Type (Typ) then
8122 Utyp := Corresponding_Record_Type (Root_Type (Base_Type (Typ)));
8123 else
8124 Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
8126 if Is_Protected_Type (Utyp) then
8127 Utyp := Corresponding_Record_Type (Utyp);
8128 end if;
8129 end if;
8131 Ref := Unchecked_Convert_To (Utyp, Ref);
8132 Set_Assignment_OK (Ref);
8133 end if;
8135 -- Deal with derived private types which do not inherit primitives from
8136 -- their parents. In this case, [Deep_]Finalize can be found in the full
8137 -- view of the parent type.
8139 if Present (Utyp)
8140 and then Is_Tagged_Type (Utyp)
8141 and then Is_Derived_Type (Utyp)
8142 and then Is_Empty_Elmt_List (Primitive_Operations (Utyp))
8143 and then Is_Private_Type (Etype (Utyp))
8144 and then Present (Full_View (Etype (Utyp)))
8145 then
8146 Utyp := Full_View (Etype (Utyp));
8147 Ref := Unchecked_Convert_To (Utyp, Ref);
8148 Set_Assignment_OK (Ref);
8149 end if;
8151 -- When dealing with the completion of a private type, use the base type
8152 -- instead.
8154 if Present (Utyp) and then Utyp /= Base_Type (Utyp) then
8155 pragma Assert (Present (Atyp) and then Is_Private_Type (Atyp));
8157 Utyp := Base_Type (Utyp);
8158 Ref := Unchecked_Convert_To (Utyp, Ref);
8159 Set_Assignment_OK (Ref);
8160 end if;
8162 -- The underlying type may not be present due to a missing full view. In
8163 -- this case freezing did not take place and there is no [Deep_]Finalize
8164 -- primitive to call.
8166 if No (Utyp) then
8167 return Empty;
8169 elsif Skip_Self then
8170 if Has_Controlled_Component (Utyp) then
8171 if Is_Tagged_Type (Utyp) then
8172 Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize);
8173 else
8174 Fin_Id := TSS (Utyp, TSS_Deep_Finalize);
8175 end if;
8176 end if;
8178 -- Class-wide types, interfaces and types with controlled components
8180 elsif Is_Class_Wide_Type (Typ)
8181 or else Is_Interface (Typ)
8182 or else Has_Controlled_Component (Utyp)
8183 then
8184 if Is_Tagged_Type (Utyp) then
8185 Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize);
8186 else
8187 Fin_Id := TSS (Utyp, TSS_Deep_Finalize);
8188 end if;
8190 -- Derivations from [Limited_]Controlled
8192 elsif Is_Controlled (Utyp) then
8193 if Has_Controlled_Component (Utyp) then
8194 Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize);
8195 else
8196 Fin_Id := Find_Optional_Prim_Op (Utyp, Name_Of (Finalize_Case));
8197 end if;
8199 -- Tagged types
8201 elsif Is_Tagged_Type (Utyp) then
8202 Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize);
8204 else
8205 raise Program_Error;
8206 end if;
8208 if Present (Fin_Id) then
8210 -- When finalizing a class-wide object, do not convert to the root
8211 -- type in order to produce a dispatching call.
8213 if Is_Class_Wide_Type (Typ) then
8214 null;
8216 -- Ensure that a finalization routine is at least decorated in order
8217 -- to inspect the object parameter.
8219 elsif Analyzed (Fin_Id)
8220 or else Ekind (Fin_Id) = E_Procedure
8221 then
8222 -- In certain cases, such as the creation of Stream_Read, the
8223 -- visible entity of the type is its full view. Since Stream_Read
8224 -- will have to create an object of type Typ, the local object
8225 -- will be finalzed by the scope finalizer generated later on. The
8226 -- object parameter of Deep_Finalize will always use the private
8227 -- view of the type. To avoid such a clash between a private and a
8228 -- full view, perform an unchecked conversion of the object
8229 -- reference to the private view.
8231 declare
8232 Formal_Typ : constant Entity_Id :=
8233 Etype (First_Formal (Fin_Id));
8234 begin
8235 if Is_Private_Type (Formal_Typ)
8236 and then Present (Full_View (Formal_Typ))
8237 and then Full_View (Formal_Typ) = Utyp
8238 then
8239 Ref := Unchecked_Convert_To (Formal_Typ, Ref);
8240 end if;
8241 end;
8243 Ref := Convert_View (Fin_Id, Ref);
8244 end if;
8246 return
8247 Make_Call (Loc,
8248 Proc_Id => Fin_Id,
8249 Param => Ref,
8250 Skip_Self => Skip_Self);
8251 else
8252 return Empty;
8253 end if;
8254 end Make_Final_Call;
8256 --------------------------------
8257 -- Make_Finalize_Address_Body --
8258 --------------------------------
8260 procedure Make_Finalize_Address_Body (Typ : Entity_Id) is
8261 Is_Task : constant Boolean :=
8262 Ekind (Typ) = E_Record_Type
8263 and then Is_Concurrent_Record_Type (Typ)
8264 and then Ekind (Corresponding_Concurrent_Type (Typ)) =
8265 E_Task_Type;
8266 Loc : constant Source_Ptr := Sloc (Typ);
8267 Proc_Id : Entity_Id;
8268 Stmts : List_Id;
8270 begin
8271 -- The corresponding records of task types are not controlled by design.
8272 -- For the sake of completeness, create an empty Finalize_Address to be
8273 -- used in task class-wide allocations.
8275 if Is_Task then
8276 null;
8278 -- Nothing to do if the type is not controlled or it already has a
8279 -- TSS entry for Finalize_Address. Skip class-wide subtypes which do not
8280 -- come from source. These are usually generated for completeness and
8281 -- do not need the Finalize_Address primitive.
8283 elsif not Needs_Finalization (Typ)
8284 or else Present (TSS (Typ, TSS_Finalize_Address))
8285 or else
8286 (Is_Class_Wide_Type (Typ)
8287 and then Ekind (Root_Type (Typ)) = E_Record_Subtype
8288 and then not Comes_From_Source (Root_Type (Typ)))
8289 then
8290 return;
8291 end if;
8293 -- Do not generate Finalize_Address routine for CodePeer
8295 if CodePeer_Mode then
8296 return;
8297 end if;
8299 Proc_Id :=
8300 Make_Defining_Identifier (Loc,
8301 Make_TSS_Name (Typ, TSS_Finalize_Address));
8303 -- Generate:
8305 -- procedure <Typ>FD (V : System.Address) is
8306 -- begin
8307 -- null; -- for tasks
8309 -- declare -- for all other types
8310 -- type Pnn is access all Typ;
8311 -- for Pnn'Storage_Size use 0;
8312 -- begin
8313 -- [Deep_]Finalize (Pnn (V).all);
8314 -- end;
8315 -- end TypFD;
8317 if Is_Task then
8318 Stmts := New_List (Make_Null_Statement (Loc));
8319 else
8320 Stmts := Make_Finalize_Address_Stmts (Typ);
8321 end if;
8323 Discard_Node (
8324 Make_Subprogram_Body (Loc,
8325 Specification =>
8326 Make_Procedure_Specification (Loc,
8327 Defining_Unit_Name => Proc_Id,
8329 Parameter_Specifications => New_List (
8330 Make_Parameter_Specification (Loc,
8331 Defining_Identifier =>
8332 Make_Defining_Identifier (Loc, Name_V),
8333 Parameter_Type =>
8334 New_Occurrence_Of (RTE (RE_Address), Loc)))),
8336 Declarations => No_List,
8338 Handled_Statement_Sequence =>
8339 Make_Handled_Sequence_Of_Statements (Loc,
8340 Statements => Stmts)));
8342 Set_TSS (Typ, Proc_Id);
8343 end Make_Finalize_Address_Body;
8345 ---------------------------------
8346 -- Make_Finalize_Address_Stmts --
8347 ---------------------------------
8349 function Make_Finalize_Address_Stmts (Typ : Entity_Id) return List_Id is
8350 Loc : constant Source_Ptr := Sloc (Typ);
8352 Decls : List_Id;
8353 Desig_Typ : Entity_Id;
8354 Fin_Block : Node_Id;
8355 Fin_Call : Node_Id;
8356 Obj_Expr : Node_Id;
8357 Ptr_Typ : Entity_Id;
8359 begin
8360 if Is_Array_Type (Typ) then
8361 if Is_Constrained (First_Subtype (Typ)) then
8362 Desig_Typ := First_Subtype (Typ);
8363 else
8364 Desig_Typ := Base_Type (Typ);
8365 end if;
8367 -- Class-wide types of constrained root types
8369 elsif Is_Class_Wide_Type (Typ)
8370 and then Has_Discriminants (Root_Type (Typ))
8371 and then not
8372 Is_Empty_Elmt_List (Discriminant_Constraint (Root_Type (Typ)))
8373 then
8374 declare
8375 Parent_Typ : Entity_Id;
8377 begin
8378 -- Climb the parent type chain looking for a non-constrained type
8380 Parent_Typ := Root_Type (Typ);
8381 while Parent_Typ /= Etype (Parent_Typ)
8382 and then Has_Discriminants (Parent_Typ)
8383 and then not
8384 Is_Empty_Elmt_List (Discriminant_Constraint (Parent_Typ))
8385 loop
8386 Parent_Typ := Etype (Parent_Typ);
8387 end loop;
8389 -- Handle views created for tagged types with unknown
8390 -- discriminants.
8392 if Is_Underlying_Record_View (Parent_Typ) then
8393 Parent_Typ := Underlying_Record_View (Parent_Typ);
8394 end if;
8396 Desig_Typ := Class_Wide_Type (Underlying_Type (Parent_Typ));
8397 end;
8399 -- General case
8401 else
8402 Desig_Typ := Typ;
8403 end if;
8405 -- Generate:
8406 -- type Ptr_Typ is access all Typ;
8407 -- for Ptr_Typ'Storage_Size use 0;
8409 Ptr_Typ := Make_Temporary (Loc, 'P');
8411 Decls := New_List (
8412 Make_Full_Type_Declaration (Loc,
8413 Defining_Identifier => Ptr_Typ,
8414 Type_Definition =>
8415 Make_Access_To_Object_Definition (Loc,
8416 All_Present => True,
8417 Subtype_Indication => New_Occurrence_Of (Desig_Typ, Loc))),
8419 Make_Attribute_Definition_Clause (Loc,
8420 Name => New_Occurrence_Of (Ptr_Typ, Loc),
8421 Chars => Name_Storage_Size,
8422 Expression => Make_Integer_Literal (Loc, 0)));
8424 Obj_Expr := Make_Identifier (Loc, Name_V);
8426 -- Unconstrained arrays require special processing in order to retrieve
8427 -- the elements. To achieve this, we have to skip the dope vector which
8428 -- lays in front of the elements and then use a thin pointer to perform
8429 -- the address-to-access conversion.
8431 if Is_Array_Type (Typ)
8432 and then not Is_Constrained (First_Subtype (Typ))
8433 then
8434 declare
8435 Dope_Id : Entity_Id;
8437 begin
8438 -- Ensure that Ptr_Typ a thin pointer, generate:
8439 -- for Ptr_Typ'Size use System.Address'Size;
8441 Append_To (Decls,
8442 Make_Attribute_Definition_Clause (Loc,
8443 Name => New_Occurrence_Of (Ptr_Typ, Loc),
8444 Chars => Name_Size,
8445 Expression =>
8446 Make_Integer_Literal (Loc, System_Address_Size)));
8448 -- Generate:
8449 -- Dnn : constant Storage_Offset :=
8450 -- Desig_Typ'Descriptor_Size / Storage_Unit;
8452 Dope_Id := Make_Temporary (Loc, 'D');
8454 Append_To (Decls,
8455 Make_Object_Declaration (Loc,
8456 Defining_Identifier => Dope_Id,
8457 Constant_Present => True,
8458 Object_Definition =>
8459 New_Occurrence_Of (RTE (RE_Storage_Offset), Loc),
8460 Expression =>
8461 Make_Op_Divide (Loc,
8462 Left_Opnd =>
8463 Make_Attribute_Reference (Loc,
8464 Prefix => New_Occurrence_Of (Desig_Typ, Loc),
8465 Attribute_Name => Name_Descriptor_Size),
8466 Right_Opnd =>
8467 Make_Integer_Literal (Loc, System_Storage_Unit))));
8469 -- Shift the address from the start of the dope vector to the
8470 -- start of the elements:
8472 -- V + Dnn
8474 -- Note that this is done through a wrapper routine since RTSfind
8475 -- cannot retrieve operations with string names of the form "+".
8477 Obj_Expr :=
8478 Make_Function_Call (Loc,
8479 Name =>
8480 New_Occurrence_Of (RTE (RE_Add_Offset_To_Address), Loc),
8481 Parameter_Associations => New_List (
8482 Obj_Expr,
8483 New_Occurrence_Of (Dope_Id, Loc)));
8484 end;
8485 end if;
8487 Fin_Call :=
8488 Make_Final_Call (
8489 Obj_Ref =>
8490 Make_Explicit_Dereference (Loc,
8491 Prefix => Unchecked_Convert_To (Ptr_Typ, Obj_Expr)),
8492 Typ => Desig_Typ);
8494 if Present (Fin_Call) then
8495 Fin_Block :=
8496 Make_Block_Statement (Loc,
8497 Declarations => Decls,
8498 Handled_Statement_Sequence =>
8499 Make_Handled_Sequence_Of_Statements (Loc,
8500 Statements => New_List (Fin_Call)));
8502 -- Otherwise previous errors or a missing full view may prevent the
8503 -- proper freezing of the designated type. If this is the case, there
8504 -- is no [Deep_]Finalize primitive to call.
8506 else
8507 Fin_Block := Make_Null_Statement (Loc);
8508 end if;
8510 return New_List (Fin_Block);
8511 end Make_Finalize_Address_Stmts;
8513 -------------------------------------
8514 -- Make_Handler_For_Ctrl_Operation --
8515 -------------------------------------
8517 -- Generate:
8519 -- when E : others =>
8520 -- Raise_From_Controlled_Operation (E);
8522 -- or:
8524 -- when others =>
8525 -- raise Program_Error [finalize raised exception];
8527 -- depending on whether Raise_From_Controlled_Operation is available
8529 function Make_Handler_For_Ctrl_Operation
8530 (Loc : Source_Ptr) return Node_Id
8532 E_Occ : Entity_Id;
8533 -- Choice parameter (for the first case above)
8535 Raise_Node : Node_Id;
8536 -- Procedure call or raise statement
8538 begin
8539 -- Standard run-time: add choice parameter E and pass it to
8540 -- Raise_From_Controlled_Operation so that the original exception
8541 -- name and message can be recorded in the exception message for
8542 -- Program_Error.
8544 if RTE_Available (RE_Raise_From_Controlled_Operation) then
8545 E_Occ := Make_Defining_Identifier (Loc, Name_E);
8546 Raise_Node :=
8547 Make_Procedure_Call_Statement (Loc,
8548 Name =>
8549 New_Occurrence_Of
8550 (RTE (RE_Raise_From_Controlled_Operation), Loc),
8551 Parameter_Associations => New_List (
8552 New_Occurrence_Of (E_Occ, Loc)));
8554 -- Restricted run-time: exception messages are not supported
8556 else
8557 E_Occ := Empty;
8558 Raise_Node :=
8559 Make_Raise_Program_Error (Loc,
8560 Reason => PE_Finalize_Raised_Exception);
8561 end if;
8563 return
8564 Make_Implicit_Exception_Handler (Loc,
8565 Exception_Choices => New_List (Make_Others_Choice (Loc)),
8566 Choice_Parameter => E_Occ,
8567 Statements => New_List (Raise_Node));
8568 end Make_Handler_For_Ctrl_Operation;
8570 --------------------
8571 -- Make_Init_Call --
8572 --------------------
8574 function Make_Init_Call
8575 (Obj_Ref : Node_Id;
8576 Typ : Entity_Id) return Node_Id
8578 Loc : constant Source_Ptr := Sloc (Obj_Ref);
8579 Is_Conc : Boolean;
8580 Proc : Entity_Id;
8581 Ref : Node_Id;
8582 Utyp : Entity_Id;
8584 begin
8585 Ref := Obj_Ref;
8587 -- Deal with the type and object reference. Depending on the context, an
8588 -- object reference may need several conversions.
8590 if Is_Concurrent_Type (Typ) then
8591 Is_Conc := True;
8592 Utyp := Corresponding_Record_Type (Typ);
8593 Ref := Convert_Concurrent (Ref, Typ);
8595 elsif Is_Private_Type (Typ)
8596 and then Present (Full_View (Typ))
8597 and then Is_Concurrent_Type (Underlying_Type (Typ))
8598 then
8599 Is_Conc := True;
8600 Utyp := Corresponding_Record_Type (Underlying_Type (Typ));
8601 Ref := Convert_Concurrent (Ref, Underlying_Type (Typ));
8603 else
8604 Is_Conc := False;
8605 Utyp := Typ;
8606 end if;
8608 Utyp := Underlying_Type (Base_Type (Utyp));
8609 Set_Assignment_OK (Ref);
8611 -- Deal with untagged derivation of private views
8613 if Is_Untagged_Derivation (Typ) and then not Is_Conc then
8614 Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
8615 Ref := Unchecked_Convert_To (Utyp, Ref);
8617 -- The following is to prevent problems with UC see 1.156 RH ???
8619 Set_Assignment_OK (Ref);
8620 end if;
8622 -- If the underlying_type is a subtype, then we are dealing with the
8623 -- completion of a private type. We need to access the base type and
8624 -- generate a conversion to it.
8626 if Present (Utyp) and then Utyp /= Base_Type (Utyp) then
8627 pragma Assert (Is_Private_Type (Typ));
8628 Utyp := Base_Type (Utyp);
8629 Ref := Unchecked_Convert_To (Utyp, Ref);
8630 end if;
8632 -- The underlying type may not be present due to a missing full view.
8633 -- In this case freezing did not take place and there is no suitable
8634 -- [Deep_]Initialize primitive to call.
8636 if No (Utyp) then
8637 return Empty;
8638 end if;
8640 -- Select the appropriate version of initialize
8642 if Has_Controlled_Component (Utyp) then
8643 Proc := TSS (Utyp, Deep_Name_Of (Initialize_Case));
8644 else
8645 Proc := Find_Prim_Op (Utyp, Name_Of (Initialize_Case));
8646 Check_Visibly_Controlled (Initialize_Case, Typ, Proc, Ref);
8647 end if;
8649 -- If initialization procedure for an array of controlled objects is
8650 -- trivial, do not generate a useless call to it.
8652 if (Is_Array_Type (Utyp) and then Is_Trivial_Subprogram (Proc))
8653 or else
8654 (not Comes_From_Source (Proc)
8655 and then Present (Alias (Proc))
8656 and then Is_Trivial_Subprogram (Alias (Proc)))
8657 then
8658 return Make_Null_Statement (Loc);
8659 end if;
8661 -- The object reference may need another conversion depending on the
8662 -- type of the formal and that of the actual.
8664 Ref := Convert_View (Proc, Ref);
8666 -- Generate:
8667 -- [Deep_]Initialize (Ref);
8669 return
8670 Make_Procedure_Call_Statement (Loc,
8671 Name => New_Occurrence_Of (Proc, Loc),
8672 Parameter_Associations => New_List (Ref));
8673 end Make_Init_Call;
8675 ------------------------------
8676 -- Make_Local_Deep_Finalize --
8677 ------------------------------
8679 function Make_Local_Deep_Finalize
8680 (Typ : Entity_Id;
8681 Nam : Entity_Id) return Node_Id
8683 Loc : constant Source_Ptr := Sloc (Typ);
8684 Formals : List_Id;
8686 begin
8687 Formals := New_List (
8689 -- V : in out Typ
8691 Make_Parameter_Specification (Loc,
8692 Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
8693 In_Present => True,
8694 Out_Present => True,
8695 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
8697 -- F : Boolean := True
8699 Make_Parameter_Specification (Loc,
8700 Defining_Identifier => Make_Defining_Identifier (Loc, Name_F),
8701 Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc),
8702 Expression => New_Occurrence_Of (Standard_True, Loc)));
8704 -- Add the necessary number of counters to represent the initialization
8705 -- state of an object.
8707 return
8708 Make_Subprogram_Body (Loc,
8709 Specification =>
8710 Make_Procedure_Specification (Loc,
8711 Defining_Unit_Name => Nam,
8712 Parameter_Specifications => Formals),
8714 Declarations => No_List,
8716 Handled_Statement_Sequence =>
8717 Make_Handled_Sequence_Of_Statements (Loc,
8718 Statements => Make_Deep_Record_Body (Finalize_Case, Typ, True)));
8719 end Make_Local_Deep_Finalize;
8721 ------------------------------------
8722 -- Make_Set_Finalize_Address_Call --
8723 ------------------------------------
8725 function Make_Set_Finalize_Address_Call
8726 (Loc : Source_Ptr;
8727 Ptr_Typ : Entity_Id) return Node_Id
8729 -- It is possible for Ptr_Typ to be a partial view, if the access type
8730 -- is a full view declared in the private part of a nested package, and
8731 -- the finalization actions take place when completing analysis of the
8732 -- enclosing unit. For this reason use Underlying_Type twice below.
8734 Desig_Typ : constant Entity_Id :=
8735 Available_View
8736 (Designated_Type (Underlying_Type (Ptr_Typ)));
8737 Fin_Addr : constant Entity_Id := Finalize_Address (Desig_Typ);
8738 Fin_Mas : constant Entity_Id :=
8739 Finalization_Master (Underlying_Type (Ptr_Typ));
8741 begin
8742 -- Both the finalization master and primitive Finalize_Address must be
8743 -- available.
8745 pragma Assert (Present (Fin_Addr) and Present (Fin_Mas));
8747 -- Generate:
8748 -- Set_Finalize_Address
8749 -- (<Ptr_Typ>FM, <Desig_Typ>FD'Unrestricted_Access);
8751 return
8752 Make_Procedure_Call_Statement (Loc,
8753 Name =>
8754 New_Occurrence_Of (RTE (RE_Set_Finalize_Address), Loc),
8755 Parameter_Associations => New_List (
8756 New_Occurrence_Of (Fin_Mas, Loc),
8758 Make_Attribute_Reference (Loc,
8759 Prefix => New_Occurrence_Of (Fin_Addr, Loc),
8760 Attribute_Name => Name_Unrestricted_Access)));
8761 end Make_Set_Finalize_Address_Call;
8763 --------------------------
8764 -- Make_Transient_Block --
8765 --------------------------
8767 function Make_Transient_Block
8768 (Loc : Source_Ptr;
8769 Action : Node_Id;
8770 Par : Node_Id) return Node_Id
8772 function Manages_Sec_Stack (Id : Entity_Id) return Boolean;
8773 -- Determine whether scoping entity Id manages the secondary stack
8775 function Within_Loop_Statement (N : Node_Id) return Boolean;
8776 -- Return True when N appears within a loop and no block is containing N
8778 -----------------------
8779 -- Manages_Sec_Stack --
8780 -----------------------
8782 function Manages_Sec_Stack (Id : Entity_Id) return Boolean is
8783 begin
8784 case Ekind (Id) is
8786 -- An exception handler with a choice parameter utilizes a dummy
8787 -- block to provide a declarative region. Such a block should not
8788 -- be considered because it never manifests in the tree and can
8789 -- never release the secondary stack.
8791 when E_Block =>
8792 return
8793 Uses_Sec_Stack (Id) and then not Is_Exception_Handler (Id);
8795 when E_Entry
8796 | E_Entry_Family
8797 | E_Function
8798 | E_Procedure
8800 return Uses_Sec_Stack (Id);
8802 when others =>
8803 return False;
8804 end case;
8805 end Manages_Sec_Stack;
8807 ---------------------------
8808 -- Within_Loop_Statement --
8809 ---------------------------
8811 function Within_Loop_Statement (N : Node_Id) return Boolean is
8812 Par : Node_Id := Parent (N);
8814 begin
8815 while not (Nkind_In (Par, N_Handled_Sequence_Of_Statements,
8816 N_Loop_Statement,
8817 N_Package_Specification)
8818 or else Nkind (Par) in N_Proper_Body)
8819 loop
8820 pragma Assert (Present (Par));
8821 Par := Parent (Par);
8822 end loop;
8824 return Nkind (Par) = N_Loop_Statement;
8825 end Within_Loop_Statement;
8827 -- Local variables
8829 Decls : constant List_Id := New_List;
8830 Instrs : constant List_Id := New_List (Action);
8831 Trans_Id : constant Entity_Id := Current_Scope;
8833 Block : Node_Id;
8834 Insert : Node_Id;
8835 Scop : Entity_Id;
8837 -- Start of processing for Make_Transient_Block
8839 begin
8840 -- Even though the transient block is tasked with managing the secondary
8841 -- stack, the block may forgo this functionality depending on how the
8842 -- secondary stack is managed by enclosing scopes.
8844 if Manages_Sec_Stack (Trans_Id) then
8846 -- Determine whether an enclosing scope already manages the secondary
8847 -- stack.
8849 Scop := Scope (Trans_Id);
8850 while Present (Scop) loop
8852 -- It should not be possible to reach Standard without hitting one
8853 -- of the other cases first unless Standard was manually pushed.
8855 if Scop = Standard_Standard then
8856 exit;
8858 -- The transient block is within a function which returns on the
8859 -- secondary stack. Take a conservative approach and assume that
8860 -- the value on the secondary stack is part of the result. Note
8861 -- that it is not possible to detect this dependency without flow
8862 -- analysis which the compiler does not have. Letting the object
8863 -- live longer than the transient block will not leak any memory
8864 -- because the caller will reclaim the total storage used by the
8865 -- function.
8867 elsif Ekind (Scop) = E_Function
8868 and then Sec_Stack_Needed_For_Return (Scop)
8869 then
8870 Set_Uses_Sec_Stack (Trans_Id, False);
8871 exit;
8873 -- The transient block must manage the secondary stack when the
8874 -- block appears within a loop in order to reclaim the memory at
8875 -- each iteration.
8877 elsif Ekind (Scop) = E_Loop then
8878 exit;
8880 -- Ditto when the block appears without a block that does not
8881 -- manage the secondary stack and is located within a loop.
8883 elsif Ekind (Scop) = E_Block
8884 and then not Manages_Sec_Stack (Scop)
8885 and then Present (Block_Node (Scop))
8886 and then Within_Loop_Statement (Block_Node (Scop))
8887 then
8888 exit;
8890 -- The transient block does not need to manage the secondary stack
8891 -- when there is an enclosing construct which already does that.
8892 -- This optimization saves on SS_Mark and SS_Release calls but may
8893 -- allow objects to live a little longer than required.
8895 -- The transient block must manage the secondary stack when switch
8896 -- -gnatd.s (strict management) is in effect.
8898 elsif Manages_Sec_Stack (Scop) and then not Debug_Flag_Dot_S then
8899 Set_Uses_Sec_Stack (Trans_Id, False);
8900 exit;
8902 -- Prevent the search from going too far because transient blocks
8903 -- are bounded by packages and subprogram scopes.
8905 elsif Ekind_In (Scop, E_Entry,
8906 E_Entry_Family,
8907 E_Function,
8908 E_Package,
8909 E_Procedure,
8910 E_Subprogram_Body)
8911 then
8912 exit;
8913 end if;
8915 Scop := Scope (Scop);
8916 end loop;
8917 end if;
8919 -- Create the transient block. Set the parent now since the block itself
8920 -- is not part of the tree. The current scope is the E_Block entity that
8921 -- has been pushed by Establish_Transient_Scope.
8923 pragma Assert (Ekind (Trans_Id) = E_Block);
8925 Block :=
8926 Make_Block_Statement (Loc,
8927 Identifier => New_Occurrence_Of (Trans_Id, Loc),
8928 Declarations => Decls,
8929 Handled_Statement_Sequence =>
8930 Make_Handled_Sequence_Of_Statements (Loc, Statements => Instrs),
8931 Has_Created_Identifier => True);
8932 Set_Parent (Block, Par);
8934 -- Insert actions stuck in the transient scopes as well as all freezing
8935 -- nodes needed by those actions. Do not insert cleanup actions here,
8936 -- they will be transferred to the newly created block.
8938 Insert_Actions_In_Scope_Around
8939 (Action, Clean => False, Manage_SS => False);
8941 Insert := Prev (Action);
8943 if Present (Insert) then
8944 Freeze_All (First_Entity (Trans_Id), Insert);
8945 end if;
8947 -- Transfer cleanup actions to the newly created block
8949 declare
8950 Cleanup_Actions : List_Id
8951 renames Scope_Stack.Table (Scope_Stack.Last).
8952 Actions_To_Be_Wrapped (Cleanup);
8953 begin
8954 Set_Cleanup_Actions (Block, Cleanup_Actions);
8955 Cleanup_Actions := No_List;
8956 end;
8958 -- When the transient scope was established, we pushed the entry for the
8959 -- transient scope onto the scope stack, so that the scope was active
8960 -- for the installation of finalizable entities etc. Now we must remove
8961 -- this entry, since we have constructed a proper block.
8963 Pop_Scope;
8965 return Block;
8966 end Make_Transient_Block;
8968 ------------------------
8969 -- Node_To_Be_Wrapped --
8970 ------------------------
8972 function Node_To_Be_Wrapped return Node_Id is
8973 begin
8974 return Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped;
8975 end Node_To_Be_Wrapped;
8977 ----------------------------
8978 -- Set_Node_To_Be_Wrapped --
8979 ----------------------------
8981 procedure Set_Node_To_Be_Wrapped (N : Node_Id) is
8982 begin
8983 Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped := N;
8984 end Set_Node_To_Be_Wrapped;
8986 ----------------------------
8987 -- Store_Actions_In_Scope --
8988 ----------------------------
8990 procedure Store_Actions_In_Scope (AK : Scope_Action_Kind; L : List_Id) is
8991 SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
8992 Actions : List_Id renames SE.Actions_To_Be_Wrapped (AK);
8994 begin
8995 if No (Actions) then
8996 Actions := L;
8998 if Is_List_Member (SE.Node_To_Be_Wrapped) then
8999 Set_Parent (L, Parent (SE.Node_To_Be_Wrapped));
9000 else
9001 Set_Parent (L, SE.Node_To_Be_Wrapped);
9002 end if;
9004 Analyze_List (L);
9006 elsif AK = Before then
9007 Insert_List_After_And_Analyze (Last (Actions), L);
9009 else
9010 Insert_List_Before_And_Analyze (First (Actions), L);
9011 end if;
9012 end Store_Actions_In_Scope;
9014 ----------------------------------
9015 -- Store_After_Actions_In_Scope --
9016 ----------------------------------
9018 procedure Store_After_Actions_In_Scope (L : List_Id) is
9019 begin
9020 Store_Actions_In_Scope (After, L);
9021 end Store_After_Actions_In_Scope;
9023 -----------------------------------
9024 -- Store_Before_Actions_In_Scope --
9025 -----------------------------------
9027 procedure Store_Before_Actions_In_Scope (L : List_Id) is
9028 begin
9029 Store_Actions_In_Scope (Before, L);
9030 end Store_Before_Actions_In_Scope;
9032 -----------------------------------
9033 -- Store_Cleanup_Actions_In_Scope --
9034 -----------------------------------
9036 procedure Store_Cleanup_Actions_In_Scope (L : List_Id) is
9037 begin
9038 Store_Actions_In_Scope (Cleanup, L);
9039 end Store_Cleanup_Actions_In_Scope;
9041 --------------------------------
9042 -- Wrap_Transient_Declaration --
9043 --------------------------------
9045 -- If a transient scope has been established during the processing of the
9046 -- Expression of an Object_Declaration, it is not possible to wrap the
9047 -- declaration into a transient block as usual case, otherwise the object
9048 -- would be itself declared in the wrong scope. Therefore, all entities (if
9049 -- any) defined in the transient block are moved to the proper enclosing
9050 -- scope. Furthermore, if they are controlled variables they are finalized
9051 -- right after the declaration. The finalization list of the transient
9052 -- scope is defined as a renaming of the enclosing one so during their
9053 -- initialization they will be attached to the proper finalization list.
9054 -- For instance, the following declaration :
9056 -- X : Typ := F (G (A), G (B));
9058 -- (where G(A) and G(B) return controlled values, expanded as _v1 and _v2)
9059 -- is expanded into :
9061 -- X : Typ := [ complex Expression-Action ];
9062 -- [Deep_]Finalize (_v1);
9063 -- [Deep_]Finalize (_v2);
9065 procedure Wrap_Transient_Declaration (N : Node_Id) is
9066 Curr_S : Entity_Id;
9067 Encl_S : Entity_Id;
9069 begin
9070 Curr_S := Current_Scope;
9071 Encl_S := Scope (Curr_S);
9073 -- Insert all actions including cleanup generated while analyzing or
9074 -- expanding the transient context back into the tree. Manage the
9075 -- secondary stack when the object declaration appears in a library
9076 -- level package [body].
9078 Insert_Actions_In_Scope_Around
9079 (N => N,
9080 Clean => True,
9081 Manage_SS =>
9082 Uses_Sec_Stack (Curr_S)
9083 and then Nkind (N) = N_Object_Declaration
9084 and then Ekind_In (Encl_S, E_Package, E_Package_Body)
9085 and then Is_Library_Level_Entity (Encl_S));
9086 Pop_Scope;
9088 -- Relocate local entities declared within the transient scope to the
9089 -- enclosing scope. This action sets their Is_Public flag accordingly.
9091 Transfer_Entities (Curr_S, Encl_S);
9093 -- Mark the enclosing dynamic scope to ensure that the secondary stack
9094 -- is properly released upon exiting the said scope.
9096 if Uses_Sec_Stack (Curr_S) then
9097 Curr_S := Enclosing_Dynamic_Scope (Curr_S);
9099 -- Do not mark a function that returns on the secondary stack as the
9100 -- reclamation is done by the caller.
9102 if Ekind (Curr_S) = E_Function
9103 and then Requires_Transient_Scope (Etype (Curr_S))
9104 then
9105 null;
9107 -- Otherwise mark the enclosing dynamic scope
9109 else
9110 Set_Uses_Sec_Stack (Curr_S);
9111 Check_Restriction (No_Secondary_Stack, N);
9112 end if;
9113 end if;
9114 end Wrap_Transient_Declaration;
9116 -------------------------------
9117 -- Wrap_Transient_Expression --
9118 -------------------------------
9120 procedure Wrap_Transient_Expression (N : Node_Id) is
9121 Loc : constant Source_Ptr := Sloc (N);
9122 Expr : Node_Id := Relocate_Node (N);
9123 Temp : constant Entity_Id := Make_Temporary (Loc, 'E', N);
9124 Typ : constant Entity_Id := Etype (N);
9126 begin
9127 -- Generate:
9129 -- Temp : Typ;
9130 -- declare
9131 -- M : constant Mark_Id := SS_Mark;
9132 -- procedure Finalizer is ... (See Build_Finalizer)
9134 -- begin
9135 -- Temp := <Expr>; -- general case
9136 -- Temp := (if <Expr> then True else False); -- boolean case
9138 -- at end
9139 -- Finalizer;
9140 -- end;
9142 -- A special case is made for Boolean expressions so that the back end
9143 -- knows to generate a conditional branch instruction, if running with
9144 -- -fpreserve-control-flow. This ensures that a control-flow change
9145 -- signaling the decision outcome occurs before the cleanup actions.
9147 if Opt.Suppress_Control_Flow_Optimizations
9148 and then Is_Boolean_Type (Typ)
9149 then
9150 Expr :=
9151 Make_If_Expression (Loc,
9152 Expressions => New_List (
9153 Expr,
9154 New_Occurrence_Of (Standard_True, Loc),
9155 New_Occurrence_Of (Standard_False, Loc)));
9156 end if;
9158 Insert_Actions (N, New_List (
9159 Make_Object_Declaration (Loc,
9160 Defining_Identifier => Temp,
9161 Object_Definition => New_Occurrence_Of (Typ, Loc)),
9163 Make_Transient_Block (Loc,
9164 Action =>
9165 Make_Assignment_Statement (Loc,
9166 Name => New_Occurrence_Of (Temp, Loc),
9167 Expression => Expr),
9168 Par => Parent (N))));
9170 Rewrite (N, New_Occurrence_Of (Temp, Loc));
9171 Analyze_And_Resolve (N, Typ);
9172 end Wrap_Transient_Expression;
9174 ------------------------------
9175 -- Wrap_Transient_Statement --
9176 ------------------------------
9178 procedure Wrap_Transient_Statement (N : Node_Id) is
9179 Loc : constant Source_Ptr := Sloc (N);
9180 New_Stmt : constant Node_Id := Relocate_Node (N);
9182 begin
9183 -- Generate:
9184 -- declare
9185 -- M : constant Mark_Id := SS_Mark;
9186 -- procedure Finalizer is ... (See Build_Finalizer)
9188 -- begin
9189 -- <New_Stmt>;
9191 -- at end
9192 -- Finalizer;
9193 -- end;
9195 Rewrite (N,
9196 Make_Transient_Block (Loc,
9197 Action => New_Stmt,
9198 Par => Parent (N)));
9200 -- With the scope stack back to normal, we can call analyze on the
9201 -- resulting block. At this point, the transient scope is being
9202 -- treated like a perfectly normal scope, so there is nothing
9203 -- special about it.
9205 -- Note: Wrap_Transient_Statement is called with the node already
9206 -- analyzed (i.e. Analyzed (N) is True). This is important, since
9207 -- otherwise we would get a recursive processing of the node when
9208 -- we do this Analyze call.
9210 Analyze (N);
9211 end Wrap_Transient_Statement;
9213 end Exp_Ch7;