[AArch64] Improve LDP/STP generation that requires a base register
[official-gcc.git] / gcc / ada / exp_ch7.adb
blob8f510c6042019ce0cf03d7745ae68a49f729f4a0
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);
3993 Elab_Body : Node_Id;
3994 Elab_Call : Node_Id;
3995 Elab_Proc : Entity_Id;
3996 Stat : Node_Id;
3998 begin
3999 if Unnest_Subprogram_Mode
4000 and then Present (Handled_Statement_Sequence (N))
4001 and then Is_Compilation_Unit (Current_Scope)
4002 then
4003 Stat := First (Statements (Handled_Statement_Sequence (N)));
4004 while Present (Stat) loop
4005 if Nkind (Stat) = N_Block_Statement then
4006 exit;
4007 end if;
4009 Next (Stat);
4010 end loop;
4012 if Present (Stat) then
4013 Elab_Proc :=
4014 Make_Defining_Identifier (Loc,
4015 Chars => New_Internal_Name ('I'));
4017 Elab_Body :=
4018 Make_Subprogram_Body (Loc,
4019 Specification =>
4020 Make_Procedure_Specification (Loc,
4021 Defining_Unit_Name => Elab_Proc),
4022 Declarations => New_List,
4023 Handled_Statement_Sequence =>
4024 Relocate_Node (Handled_Statement_Sequence (N)));
4026 Elab_Call :=
4027 Make_Procedure_Call_Statement (Loc,
4028 Name => New_Occurrence_Of (Elab_Proc, Loc));
4030 Append_To (Declarations (N), Elab_Body);
4031 Analyze (Elab_Body);
4032 Set_Has_Nested_Subprogram (Elab_Proc);
4034 Set_Handled_Statement_Sequence (N,
4035 Make_Handled_Sequence_Of_Statements (Loc,
4036 Statements => New_List (Elab_Call)));
4038 Analyze (Elab_Call);
4040 -- The scope of all blocks in the elaboration code is now the
4041 -- constructed elaboration procedure. Nested subprograms within
4042 -- those blocks will have activation records if they contain
4043 -- references to entities in the enclosing block.
4045 Stat :=
4046 First (Statements (Handled_Statement_Sequence (Elab_Body)));
4048 while Present (Stat) loop
4049 if Nkind (Stat) = N_Block_Statement then
4050 Set_Scope (Entity (Identifier (Stat)), Elab_Proc);
4051 end if;
4053 Next (Stat);
4054 end loop;
4055 end if;
4056 end if;
4057 end Check_Unnesting_Elaboration_Code;
4059 ------------------------------
4060 -- Check_Visibly_Controlled --
4061 ------------------------------
4063 procedure Check_Visibly_Controlled
4064 (Prim : Final_Primitives;
4065 Typ : Entity_Id;
4066 E : in out Entity_Id;
4067 Cref : in out Node_Id)
4069 Parent_Type : Entity_Id;
4070 Op : Entity_Id;
4072 begin
4073 if Is_Derived_Type (Typ)
4074 and then Comes_From_Source (E)
4075 and then not Present (Overridden_Operation (E))
4076 then
4077 -- We know that the explicit operation on the type does not override
4078 -- the inherited operation of the parent, and that the derivation
4079 -- is from a private type that is not visibly controlled.
4081 Parent_Type := Etype (Typ);
4082 Op := Find_Optional_Prim_Op (Parent_Type, Name_Of (Prim));
4084 if Present (Op) then
4085 E := Op;
4087 -- Wrap the object to be initialized into the proper
4088 -- unchecked conversion, to be compatible with the operation
4089 -- to be called.
4091 if Nkind (Cref) = N_Unchecked_Type_Conversion then
4092 Cref := Unchecked_Convert_To (Parent_Type, Expression (Cref));
4093 else
4094 Cref := Unchecked_Convert_To (Parent_Type, Cref);
4095 end if;
4096 end if;
4097 end if;
4098 end Check_Visibly_Controlled;
4100 ------------------
4101 -- Convert_View --
4102 ------------------
4104 function Convert_View
4105 (Proc : Entity_Id;
4106 Arg : Node_Id;
4107 Ind : Pos := 1) return Node_Id
4109 Fent : Entity_Id := First_Entity (Proc);
4110 Ftyp : Entity_Id;
4111 Atyp : Entity_Id;
4113 begin
4114 for J in 2 .. Ind loop
4115 Next_Entity (Fent);
4116 end loop;
4118 Ftyp := Etype (Fent);
4120 if Nkind_In (Arg, N_Type_Conversion, N_Unchecked_Type_Conversion) then
4121 Atyp := Entity (Subtype_Mark (Arg));
4122 else
4123 Atyp := Etype (Arg);
4124 end if;
4126 if Is_Abstract_Subprogram (Proc) and then Is_Tagged_Type (Ftyp) then
4127 return Unchecked_Convert_To (Class_Wide_Type (Ftyp), Arg);
4129 elsif Ftyp /= Atyp
4130 and then Present (Atyp)
4131 and then (Is_Private_Type (Ftyp) or else Is_Private_Type (Atyp))
4132 and then Base_Type (Underlying_Type (Atyp)) =
4133 Base_Type (Underlying_Type (Ftyp))
4134 then
4135 return Unchecked_Convert_To (Ftyp, Arg);
4137 -- If the argument is already a conversion, as generated by
4138 -- Make_Init_Call, set the target type to the type of the formal
4139 -- directly, to avoid spurious typing problems.
4141 elsif Nkind_In (Arg, N_Unchecked_Type_Conversion, N_Type_Conversion)
4142 and then not Is_Class_Wide_Type (Atyp)
4143 then
4144 Set_Subtype_Mark (Arg, New_Occurrence_Of (Ftyp, Sloc (Arg)));
4145 Set_Etype (Arg, Ftyp);
4146 return Arg;
4148 -- Otherwise, introduce a conversion when the designated object
4149 -- has a type derived from the formal of the controlled routine.
4151 elsif Is_Private_Type (Ftyp)
4152 and then Present (Atyp)
4153 and then Is_Derived_Type (Underlying_Type (Base_Type (Atyp)))
4154 then
4155 return Unchecked_Convert_To (Ftyp, Arg);
4157 else
4158 return Arg;
4159 end if;
4160 end Convert_View;
4162 -------------------------------
4163 -- CW_Or_Has_Controlled_Part --
4164 -------------------------------
4166 function CW_Or_Has_Controlled_Part (T : Entity_Id) return Boolean is
4167 begin
4168 return Is_Class_Wide_Type (T) or else Needs_Finalization (T);
4169 end CW_Or_Has_Controlled_Part;
4171 ------------------------
4172 -- Enclosing_Function --
4173 ------------------------
4175 function Enclosing_Function (E : Entity_Id) return Entity_Id is
4176 Func_Id : Entity_Id;
4178 begin
4179 Func_Id := E;
4180 while Present (Func_Id) and then Func_Id /= Standard_Standard loop
4181 if Ekind (Func_Id) = E_Function then
4182 return Func_Id;
4183 end if;
4185 Func_Id := Scope (Func_Id);
4186 end loop;
4188 return Empty;
4189 end Enclosing_Function;
4191 -------------------------------
4192 -- Establish_Transient_Scope --
4193 -------------------------------
4195 -- This procedure is called each time a transient block has to be inserted
4196 -- that is to say for each call to a function with unconstrained or tagged
4197 -- result. It creates a new scope on the scope stack in order to enclose
4198 -- all transient variables generated.
4200 procedure Establish_Transient_Scope
4201 (N : Node_Id;
4202 Manage_Sec_Stack : Boolean)
4204 procedure Create_Transient_Scope (Constr : Node_Id);
4205 -- Place a new scope on the scope stack in order to service construct
4206 -- Constr. The new scope may also manage the secondary stack.
4208 procedure Delegate_Sec_Stack_Management;
4209 -- Move the management of the secondary stack to the nearest enclosing
4210 -- suitable scope.
4212 function Find_Enclosing_Transient_Scope return Entity_Id;
4213 -- Examine the scope stack looking for the nearest enclosing transient
4214 -- scope. Return Empty if no such scope exists.
4216 function Is_Package_Or_Subprogram (Id : Entity_Id) return Boolean;
4217 -- Determine whether arbitrary Id denotes a package or subprogram [body]
4219 ----------------------------
4220 -- Create_Transient_Scope --
4221 ----------------------------
4223 procedure Create_Transient_Scope (Constr : Node_Id) is
4224 Loc : constant Source_Ptr := Sloc (N);
4226 Iter_Loop : Entity_Id;
4227 Trans_Scop : Entity_Id;
4229 begin
4230 Trans_Scop := New_Internal_Entity (E_Block, Current_Scope, Loc, 'B');
4231 Set_Etype (Trans_Scop, Standard_Void_Type);
4233 Push_Scope (Trans_Scop);
4234 Set_Node_To_Be_Wrapped (Constr);
4235 Set_Scope_Is_Transient;
4237 -- The transient scope must also manage the secondary stack
4239 if Manage_Sec_Stack then
4240 Set_Uses_Sec_Stack (Trans_Scop);
4241 Check_Restriction (No_Secondary_Stack, N);
4243 -- The expansion of iterator loops generates references to objects
4244 -- in order to extract elements from a container:
4246 -- Ref : Reference_Type_Ptr := Reference (Container, Cursor);
4247 -- Obj : <object type> renames Ref.all.Element.all;
4249 -- These references are controlled and returned on the secondary
4250 -- stack. A new reference is created at each iteration of the loop
4251 -- and as a result it must be finalized and the space occupied by
4252 -- it on the secondary stack reclaimed at the end of the current
4253 -- iteration.
4255 -- When the context that requires a transient scope is a call to
4256 -- routine Reference, the node to be wrapped is the source object:
4258 -- for Obj of Container loop
4260 -- Routine Wrap_Transient_Declaration however does not generate
4261 -- a physical block as wrapping a declaration will kill it too
4262 -- early. To handle this peculiar case, mark the related iterator
4263 -- loop as requiring the secondary stack. This signals the
4264 -- finalization machinery to manage the secondary stack (see
4265 -- routine Process_Statements_For_Controlled_Objects).
4267 Iter_Loop := Find_Enclosing_Iterator_Loop (Trans_Scop);
4269 if Present (Iter_Loop) then
4270 Set_Uses_Sec_Stack (Iter_Loop);
4271 end if;
4272 end if;
4274 if Debug_Flag_W then
4275 Write_Str (" <Transient>");
4276 Write_Eol;
4277 end if;
4278 end Create_Transient_Scope;
4280 -----------------------------------
4281 -- Delegate_Sec_Stack_Management --
4282 -----------------------------------
4284 procedure Delegate_Sec_Stack_Management is
4285 Scop_Id : Entity_Id;
4286 Scop_Rec : Scope_Stack_Entry;
4288 begin
4289 for Index in reverse Scope_Stack.First .. Scope_Stack.Last loop
4290 Scop_Rec := Scope_Stack.Table (Index);
4291 Scop_Id := Scop_Rec.Entity;
4293 -- Prevent the search from going too far or within the scope space
4294 -- of another unit.
4296 if Scop_Id = Standard_Standard then
4297 return;
4299 -- No transient scope should be encountered during the traversal
4300 -- because Establish_Transient_Scope should have already handled
4301 -- this case.
4303 elsif Scop_Rec.Is_Transient then
4304 pragma Assert (False);
4305 return;
4307 -- The construct which requires secondary stack management is
4308 -- always enclosed by a package or subprogram scope.
4310 elsif Is_Package_Or_Subprogram (Scop_Id) then
4311 Set_Uses_Sec_Stack (Scop_Id);
4312 Check_Restriction (No_Secondary_Stack, N);
4314 return;
4315 end if;
4316 end loop;
4318 -- At this point no suitable scope was found. This should never occur
4319 -- because a construct is always enclosed by a compilation unit which
4320 -- has a scope.
4322 pragma Assert (False);
4323 end Delegate_Sec_Stack_Management;
4325 ------------------------------------
4326 -- Find_Enclosing_Transient_Scope --
4327 ------------------------------------
4329 function Find_Enclosing_Transient_Scope return Entity_Id is
4330 Scop_Id : Entity_Id;
4331 Scop_Rec : Scope_Stack_Entry;
4333 begin
4334 for Index in reverse Scope_Stack.First .. Scope_Stack.Last loop
4335 Scop_Rec := Scope_Stack.Table (Index);
4336 Scop_Id := Scop_Rec.Entity;
4338 -- Prevent the search from going too far or within the scope space
4339 -- of another unit.
4341 if Scop_Id = Standard_Standard
4342 or else Is_Package_Or_Subprogram (Scop_Id)
4343 then
4344 exit;
4346 elsif Scop_Rec.Is_Transient then
4347 return Scop_Id;
4348 end if;
4349 end loop;
4351 return Empty;
4352 end Find_Enclosing_Transient_Scope;
4354 ------------------------------
4355 -- Is_Package_Or_Subprogram --
4356 ------------------------------
4358 function Is_Package_Or_Subprogram (Id : Entity_Id) return Boolean is
4359 begin
4360 return Ekind_In (Id, E_Entry,
4361 E_Entry_Family,
4362 E_Function,
4363 E_Package,
4364 E_Procedure,
4365 E_Subprogram_Body);
4366 end Is_Package_Or_Subprogram;
4368 -- Local variables
4370 Trans_Id : constant Entity_Id := Find_Enclosing_Transient_Scope;
4371 Context : Node_Id;
4373 -- Start of processing for Establish_Transient_Scope
4375 begin
4376 -- Do not create a new transient scope if there is an existing transient
4377 -- scope on the stack.
4379 if Present (Trans_Id) then
4381 -- If the transient scope was requested for purposes of managing the
4382 -- secondary stack, then the existing scope must perform this task.
4384 if Manage_Sec_Stack then
4385 Set_Uses_Sec_Stack (Trans_Id);
4386 end if;
4388 return;
4389 end if;
4391 -- At this point it is known that the scope stack is free of transient
4392 -- scopes. Locate the proper construct which must be serviced by a new
4393 -- transient scope.
4395 Context := Find_Transient_Context (N);
4397 if Present (Context) then
4398 if Nkind (Context) = N_Assignment_Statement then
4400 -- An assignment statement with suppressed controlled semantics
4401 -- does not need a transient scope because finalization is not
4402 -- desirable at this point. Note that No_Ctrl_Actions is also
4403 -- set for non-controlled assignments to suppress dispatching
4404 -- _assign.
4406 if No_Ctrl_Actions (Context)
4407 and then Needs_Finalization (Etype (Name (Context)))
4408 then
4409 -- When a controlled component is initialized by a function
4410 -- call, the result on the secondary stack is always assigned
4411 -- to the component. Signal the nearest suitable scope that it
4412 -- is safe to manage the secondary stack.
4414 if Manage_Sec_Stack and then Within_Init_Proc then
4415 Delegate_Sec_Stack_Management;
4416 end if;
4418 -- Otherwise the assignment is a normal transient context and thus
4419 -- requires a transient scope.
4421 else
4422 Create_Transient_Scope (Context);
4423 end if;
4425 -- General case
4427 else
4428 Create_Transient_Scope (Context);
4429 end if;
4430 end if;
4431 end Establish_Transient_Scope;
4433 ----------------------------
4434 -- Expand_Cleanup_Actions --
4435 ----------------------------
4437 procedure Expand_Cleanup_Actions (N : Node_Id) is
4438 pragma Assert (Nkind_In (N, N_Block_Statement,
4439 N_Entry_Body,
4440 N_Extended_Return_Statement,
4441 N_Subprogram_Body,
4442 N_Task_Body));
4444 Scop : constant Entity_Id := Current_Scope;
4446 Is_Asynchronous_Call : constant Boolean :=
4447 Nkind (N) = N_Block_Statement
4448 and then Is_Asynchronous_Call_Block (N);
4449 Is_Master : constant Boolean :=
4450 Nkind (N) /= N_Extended_Return_Statement
4451 and then Nkind (N) /= N_Entry_Body
4452 and then Is_Task_Master (N);
4453 Is_Protected_Subp_Body : constant Boolean :=
4454 Nkind (N) = N_Subprogram_Body
4455 and then Is_Protected_Subprogram_Body (N);
4456 Is_Task_Allocation : constant Boolean :=
4457 Nkind (N) = N_Block_Statement
4458 and then Is_Task_Allocation_Block (N);
4459 Is_Task_Body : constant Boolean :=
4460 Nkind (Original_Node (N)) = N_Task_Body;
4462 -- We mark the secondary stack if it is used in this construct, and
4463 -- we're not returning a function result on the secondary stack, except
4464 -- that a build-in-place function that might or might not return on the
4465 -- secondary stack always needs a mark. A run-time test is required in
4466 -- the case where the build-in-place function has a BIP_Alloc extra
4467 -- parameter (see Create_Finalizer).
4469 Needs_Sec_Stack_Mark : constant Boolean :=
4470 (Uses_Sec_Stack (Scop)
4471 and then
4472 not Sec_Stack_Needed_For_Return (Scop))
4473 or else
4474 (Is_Build_In_Place_Function (Scop)
4475 and then Needs_BIP_Alloc_Form (Scop));
4477 Needs_Custom_Cleanup : constant Boolean :=
4478 Nkind (N) = N_Block_Statement
4479 and then Present (Cleanup_Actions (N));
4481 Actions_Required : constant Boolean :=
4482 Requires_Cleanup_Actions (N, True)
4483 or else Is_Asynchronous_Call
4484 or else Is_Master
4485 or else Is_Protected_Subp_Body
4486 or else Is_Task_Allocation
4487 or else Is_Task_Body
4488 or else Needs_Sec_Stack_Mark
4489 or else Needs_Custom_Cleanup;
4491 HSS : Node_Id := Handled_Statement_Sequence (N);
4492 Loc : Source_Ptr;
4493 Cln : List_Id;
4495 procedure Wrap_HSS_In_Block;
4496 -- Move HSS inside a new block along with the original exception
4497 -- handlers. Make the newly generated block the sole statement of HSS.
4499 -----------------------
4500 -- Wrap_HSS_In_Block --
4501 -----------------------
4503 procedure Wrap_HSS_In_Block is
4504 Block : Node_Id;
4505 Block_Id : Entity_Id;
4506 End_Lab : Node_Id;
4508 begin
4509 -- Preserve end label to provide proper cross-reference information
4511 End_Lab := End_Label (HSS);
4512 Block :=
4513 Make_Block_Statement (Loc, Handled_Statement_Sequence => HSS);
4515 Block_Id := New_Internal_Entity (E_Block, Current_Scope, Loc, 'B');
4516 Set_Identifier (Block, New_Occurrence_Of (Block_Id, Loc));
4517 Set_Etype (Block_Id, Standard_Void_Type);
4518 Set_Block_Node (Block_Id, Identifier (Block));
4520 -- Signal the finalization machinery that this particular block
4521 -- contains the original context.
4523 Set_Is_Finalization_Wrapper (Block);
4525 Set_Handled_Statement_Sequence (N,
4526 Make_Handled_Sequence_Of_Statements (Loc, New_List (Block)));
4527 HSS := Handled_Statement_Sequence (N);
4529 Set_First_Real_Statement (HSS, Block);
4530 Set_End_Label (HSS, End_Lab);
4532 -- Comment needed here, see RH for 1.306 ???
4534 if Nkind (N) = N_Subprogram_Body then
4535 Set_Has_Nested_Block_With_Handler (Scop);
4536 end if;
4537 end Wrap_HSS_In_Block;
4539 -- Start of processing for Expand_Cleanup_Actions
4541 begin
4542 -- The current construct does not need any form of servicing
4544 if not Actions_Required then
4545 return;
4547 -- If the current node is a rewritten task body and the descriptors have
4548 -- not been delayed (due to some nested instantiations), do not generate
4549 -- redundant cleanup actions.
4551 elsif Is_Task_Body
4552 and then Nkind (N) = N_Subprogram_Body
4553 and then not Delay_Subprogram_Descriptors (Corresponding_Spec (N))
4554 then
4555 return;
4556 end if;
4558 -- If an extended return statement contains something like
4560 -- X := F (...);
4562 -- where F is a build-in-place function call returning a controlled
4563 -- type, then a temporary object will be implicitly declared as part
4564 -- of the statement list, and this will need cleanup. In such cases,
4565 -- we transform:
4567 -- return Result : T := ... do
4568 -- <statements> -- possibly with handlers
4569 -- end return;
4571 -- into:
4573 -- return Result : T := ... do
4574 -- declare -- no declarations
4575 -- begin
4576 -- <statements> -- possibly with handlers
4577 -- end; -- no handlers
4578 -- end return;
4580 -- So Expand_Cleanup_Actions will end up being called recursively on the
4581 -- block statement.
4583 if Nkind (N) = N_Extended_Return_Statement then
4584 declare
4585 Block : constant Node_Id :=
4586 Make_Block_Statement (Sloc (N),
4587 Declarations => Empty_List,
4588 Handled_Statement_Sequence =>
4589 Handled_Statement_Sequence (N));
4590 begin
4591 Set_Handled_Statement_Sequence (N,
4592 Make_Handled_Sequence_Of_Statements (Sloc (N),
4593 Statements => New_List (Block)));
4595 Analyze (Block);
4596 end;
4598 -- Analysis of the block did all the work
4600 return;
4601 end if;
4603 if Needs_Custom_Cleanup then
4604 Cln := Cleanup_Actions (N);
4605 else
4606 Cln := No_List;
4607 end if;
4609 declare
4610 Decls : List_Id := Declarations (N);
4611 Fin_Id : Entity_Id;
4612 Mark : Entity_Id := Empty;
4613 New_Decls : List_Id;
4614 Old_Poll : Boolean;
4616 begin
4617 -- If we are generating expanded code for debugging purposes, use the
4618 -- Sloc of the point of insertion for the cleanup code. The Sloc will
4619 -- be updated subsequently to reference the proper line in .dg files.
4620 -- If we are not debugging generated code, use No_Location instead,
4621 -- so that no debug information is generated for the cleanup code.
4622 -- This makes the behavior of the NEXT command in GDB monotonic, and
4623 -- makes the placement of breakpoints more accurate.
4625 if Debug_Generated_Code then
4626 Loc := Sloc (Scop);
4627 else
4628 Loc := No_Location;
4629 end if;
4631 -- Set polling off. The finalization and cleanup code is executed
4632 -- with aborts deferred.
4634 Old_Poll := Polling_Required;
4635 Polling_Required := False;
4637 -- A task activation call has already been built for a task
4638 -- allocation block.
4640 if not Is_Task_Allocation then
4641 Build_Task_Activation_Call (N);
4642 end if;
4644 if Is_Master then
4645 Establish_Task_Master (N);
4646 end if;
4648 New_Decls := New_List;
4650 -- If secondary stack is in use, generate:
4652 -- Mnn : constant Mark_Id := SS_Mark;
4654 if Needs_Sec_Stack_Mark then
4655 Mark := Make_Temporary (Loc, 'M');
4657 Append_To (New_Decls, Build_SS_Mark_Call (Loc, Mark));
4658 Set_Uses_Sec_Stack (Scop, False);
4659 end if;
4661 -- If exception handlers are present, wrap the sequence of statements
4662 -- in a block since it is not possible to have exception handlers and
4663 -- an At_End handler in the same construct.
4665 if Present (Exception_Handlers (HSS)) then
4666 Wrap_HSS_In_Block;
4668 -- Ensure that the First_Real_Statement field is set
4670 elsif No (First_Real_Statement (HSS)) then
4671 Set_First_Real_Statement (HSS, First (Statements (HSS)));
4672 end if;
4674 -- Do not move the Activation_Chain declaration in the context of
4675 -- task allocation blocks. Task allocation blocks use _chain in their
4676 -- cleanup handlers and gigi complains if it is declared in the
4677 -- sequence of statements of the scope that declares the handler.
4679 if Is_Task_Allocation then
4680 declare
4681 Chain : constant Entity_Id := Activation_Chain_Entity (N);
4682 Decl : Node_Id;
4684 begin
4685 Decl := First (Decls);
4686 while Nkind (Decl) /= N_Object_Declaration
4687 or else Defining_Identifier (Decl) /= Chain
4688 loop
4689 Next (Decl);
4691 -- A task allocation block should always include a _chain
4692 -- declaration.
4694 pragma Assert (Present (Decl));
4695 end loop;
4697 Remove (Decl);
4698 Prepend_To (New_Decls, Decl);
4699 end;
4700 end if;
4702 -- Ensure the presence of a declaration list in order to successfully
4703 -- append all original statements to it.
4705 if No (Decls) then
4706 Set_Declarations (N, New_List);
4707 Decls := Declarations (N);
4708 end if;
4710 -- Move the declarations into the sequence of statements in order to
4711 -- have them protected by the At_End handler. It may seem weird to
4712 -- put declarations in the sequence of statement but in fact nothing
4713 -- forbids that at the tree level.
4715 Append_List_To (Decls, Statements (HSS));
4716 Set_Statements (HSS, Decls);
4718 -- Reset the Sloc of the handled statement sequence to properly
4719 -- reflect the new initial "statement" in the sequence.
4721 Set_Sloc (HSS, Sloc (First (Decls)));
4723 -- The declarations of finalizer spec and auxiliary variables replace
4724 -- the old declarations that have been moved inward.
4726 Set_Declarations (N, New_Decls);
4727 Analyze_Declarations (New_Decls);
4729 -- Generate finalization calls for all controlled objects appearing
4730 -- in the statements of N. Add context specific cleanup for various
4731 -- constructs.
4733 Build_Finalizer
4734 (N => N,
4735 Clean_Stmts => Build_Cleanup_Statements (N, Cln),
4736 Mark_Id => Mark,
4737 Top_Decls => New_Decls,
4738 Defer_Abort => Nkind (Original_Node (N)) = N_Task_Body
4739 or else Is_Master,
4740 Fin_Id => Fin_Id);
4742 if Present (Fin_Id) then
4743 Build_Finalizer_Call (N, Fin_Id);
4744 end if;
4746 -- Restore saved polling mode
4748 Polling_Required := Old_Poll;
4749 end;
4750 end Expand_Cleanup_Actions;
4752 ---------------------------
4753 -- Expand_N_Package_Body --
4754 ---------------------------
4756 -- Add call to Activate_Tasks if body is an activator (actual processing
4757 -- is in chapter 9).
4759 -- Generate subprogram descriptor for elaboration routine
4761 -- Encode entity names in package body
4763 procedure Expand_N_Package_Body (N : Node_Id) is
4764 Spec_Id : constant Entity_Id := Corresponding_Spec (N);
4765 Fin_Id : Entity_Id;
4767 begin
4768 -- This is done only for non-generic packages
4770 if Ekind (Spec_Id) = E_Package then
4771 Push_Scope (Spec_Id);
4773 -- Build dispatch tables of library level tagged types
4775 if Tagged_Type_Expansion
4776 and then Is_Library_Level_Entity (Spec_Id)
4777 then
4778 Build_Static_Dispatch_Tables (N);
4779 end if;
4781 Build_Task_Activation_Call (N);
4783 -- Verify the run-time semantics of pragma Initial_Condition at the
4784 -- end of the body statements.
4786 Expand_Pragma_Initial_Condition (Spec_Id, N);
4787 Check_Unnesting_Elaboration_Code (N);
4789 Pop_Scope;
4790 end if;
4792 Set_Elaboration_Flag (N, Spec_Id);
4793 Set_In_Package_Body (Spec_Id, False);
4795 -- Set to encode entity names in package body before gigi is called
4797 Qualify_Entity_Names (N);
4799 if Ekind (Spec_Id) /= E_Generic_Package then
4800 Build_Finalizer
4801 (N => N,
4802 Clean_Stmts => No_List,
4803 Mark_Id => Empty,
4804 Top_Decls => No_List,
4805 Defer_Abort => False,
4806 Fin_Id => Fin_Id);
4808 if Present (Fin_Id) then
4809 declare
4810 Body_Ent : Node_Id := Defining_Unit_Name (N);
4812 begin
4813 if Nkind (Body_Ent) = N_Defining_Program_Unit_Name then
4814 Body_Ent := Defining_Identifier (Body_Ent);
4815 end if;
4817 Set_Finalizer (Body_Ent, Fin_Id);
4818 end;
4819 end if;
4820 end if;
4821 end Expand_N_Package_Body;
4823 ----------------------------------
4824 -- Expand_N_Package_Declaration --
4825 ----------------------------------
4827 -- Add call to Activate_Tasks if there are tasks declared and the package
4828 -- has no body. Note that in Ada 83 this may result in premature activation
4829 -- of some tasks, given that we cannot tell whether a body will eventually
4830 -- appear.
4832 procedure Expand_N_Package_Declaration (N : Node_Id) is
4833 Id : constant Entity_Id := Defining_Entity (N);
4834 Spec : constant Node_Id := Specification (N);
4835 Decls : List_Id;
4836 Fin_Id : Entity_Id;
4838 No_Body : Boolean := False;
4839 -- True in the case of a package declaration that is a compilation
4840 -- unit and for which no associated body will be compiled in this
4841 -- compilation.
4843 begin
4844 -- Case of a package declaration other than a compilation unit
4846 if Nkind (Parent (N)) /= N_Compilation_Unit then
4847 null;
4849 -- Case of a compilation unit that does not require a body
4851 elsif not Body_Required (Parent (N))
4852 and then not Unit_Requires_Body (Id)
4853 then
4854 No_Body := True;
4856 -- Special case of generating calling stubs for a remote call interface
4857 -- package: even though the package declaration requires one, the body
4858 -- won't be processed in this compilation (so any stubs for RACWs
4859 -- declared in the package must be generated here, along with the spec).
4861 elsif Parent (N) = Cunit (Main_Unit)
4862 and then Is_Remote_Call_Interface (Id)
4863 and then Distribution_Stub_Mode = Generate_Caller_Stub_Body
4864 then
4865 No_Body := True;
4866 end if;
4868 -- For a nested instance, delay processing until freeze point
4870 if Has_Delayed_Freeze (Id)
4871 and then Nkind (Parent (N)) /= N_Compilation_Unit
4872 then
4873 return;
4874 end if;
4876 -- For a package declaration that implies no associated body, generate
4877 -- task activation call and RACW supporting bodies now (since we won't
4878 -- have a specific separate compilation unit for that).
4880 if No_Body then
4881 Push_Scope (Id);
4883 -- Generate RACW subprogram bodies
4885 if Has_RACW (Id) then
4886 Decls := Private_Declarations (Spec);
4888 if No (Decls) then
4889 Decls := Visible_Declarations (Spec);
4890 end if;
4892 if No (Decls) then
4893 Decls := New_List;
4894 Set_Visible_Declarations (Spec, Decls);
4895 end if;
4897 Append_RACW_Bodies (Decls, Id);
4898 Analyze_List (Decls);
4899 end if;
4901 -- Generate task activation call as last step of elaboration
4903 if Present (Activation_Chain_Entity (N)) then
4904 Build_Task_Activation_Call (N);
4905 end if;
4907 -- Verify the run-time semantics of pragma Initial_Condition at the
4908 -- end of the private declarations when the package lacks a body.
4910 Expand_Pragma_Initial_Condition (Id, N);
4912 Pop_Scope;
4913 end if;
4915 -- Build dispatch tables of library level tagged types
4917 if Tagged_Type_Expansion
4918 and then (Is_Compilation_Unit (Id)
4919 or else (Is_Generic_Instance (Id)
4920 and then Is_Library_Level_Entity (Id)))
4921 then
4922 Build_Static_Dispatch_Tables (N);
4923 end if;
4925 -- Note: it is not necessary to worry about generating a subprogram
4926 -- descriptor, since the only way to get exception handlers into a
4927 -- package spec is to include instantiations, and that would cause
4928 -- generation of subprogram descriptors to be delayed in any case.
4930 -- Set to encode entity names in package spec before gigi is called
4932 Qualify_Entity_Names (N);
4934 if Ekind (Id) /= E_Generic_Package then
4935 Build_Finalizer
4936 (N => N,
4937 Clean_Stmts => No_List,
4938 Mark_Id => Empty,
4939 Top_Decls => No_List,
4940 Defer_Abort => False,
4941 Fin_Id => Fin_Id);
4943 Set_Finalizer (Id, Fin_Id);
4944 end if;
4945 end Expand_N_Package_Declaration;
4947 ----------------------------
4948 -- Find_Transient_Context --
4949 ----------------------------
4951 function Find_Transient_Context (N : Node_Id) return Node_Id is
4952 Curr : Node_Id;
4953 Prev : Node_Id;
4955 begin
4956 Curr := N;
4957 Prev := Empty;
4958 while Present (Curr) loop
4959 case Nkind (Curr) is
4961 -- Declarations
4963 -- Declarations act as a boundary for a transient scope even if
4964 -- they are not wrapped, see Wrap_Transient_Declaration.
4966 when N_Object_Declaration
4967 | N_Object_Renaming_Declaration
4968 | N_Subtype_Declaration
4970 return Curr;
4972 -- Statements
4974 -- Statements and statement-like constructs act as a boundary for
4975 -- a transient scope.
4977 when N_Accept_Alternative
4978 | N_Attribute_Definition_Clause
4979 | N_Case_Statement
4980 | N_Case_Statement_Alternative
4981 | N_Code_Statement
4982 | N_Delay_Alternative
4983 | N_Delay_Until_Statement
4984 | N_Delay_Relative_Statement
4985 | N_Discriminant_Association
4986 | N_Elsif_Part
4987 | N_Entry_Body_Formal_Part
4988 | N_Exit_Statement
4989 | N_If_Statement
4990 | N_Terminate_Alternative
4992 pragma Assert (Present (Prev));
4993 return Prev;
4995 when N_Assignment_Statement =>
4996 return Curr;
4998 when N_Entry_Call_Statement
4999 | N_Procedure_Call_Statement
5001 -- When an entry or procedure call acts as the alternative of a
5002 -- conditional or timed entry call, the proper context is that
5003 -- of the alternative.
5005 if Nkind (Parent (Curr)) = N_Entry_Call_Alternative
5006 and then Nkind_In (Parent (Parent (Curr)),
5007 N_Conditional_Entry_Call,
5008 N_Timed_Entry_Call)
5009 then
5010 return Parent (Parent (Curr));
5012 -- General case for entry or procedure calls
5014 else
5015 return Curr;
5016 end if;
5018 when N_Pragma =>
5020 -- Pragma Check is not a valid transient context in GNATprove
5021 -- mode because the pragma must remain unchanged.
5023 if GNATprove_Mode
5024 and then Get_Pragma_Id (Curr) = Pragma_Check
5025 then
5026 return Empty;
5028 -- General case for pragmas
5030 else
5031 return Curr;
5032 end if;
5034 when N_Raise_Statement =>
5035 return Curr;
5037 when N_Simple_Return_Statement =>
5039 -- A return statement is not a valid transient context when the
5040 -- function itself requires transient scope management because
5041 -- the result will be reclaimed too early.
5043 if Requires_Transient_Scope (Etype
5044 (Return_Applies_To (Return_Statement_Entity (Curr))))
5045 then
5046 return Empty;
5048 -- General case for return statements
5050 else
5051 return Curr;
5052 end if;
5054 -- Special
5056 when N_Attribute_Reference =>
5057 if Is_Procedure_Attribute_Name (Attribute_Name (Curr)) then
5058 return Curr;
5059 end if;
5061 -- An iteration scheme or an Ada 2012 iterator specification is
5062 -- not a valid context because Analyze_Iteration_Scheme already
5063 -- employs special processing for them.
5065 when N_Iteration_Scheme
5066 | N_Iterator_Specification
5068 return Empty;
5070 when N_Loop_Parameter_Specification =>
5072 -- An iteration scheme is not a valid context because routine
5073 -- Analyze_Iteration_Scheme already employs special processing.
5075 if Nkind (Parent (Curr)) = N_Iteration_Scheme then
5076 return Empty;
5077 else
5078 return Parent (Curr);
5079 end if;
5081 -- Termination
5083 -- The following nodes represent "dummy contexts" which do not
5084 -- need to be wrapped.
5086 when N_Component_Declaration
5087 | N_Discriminant_Specification
5088 | N_Parameter_Specification
5090 return Empty;
5092 -- If the traversal leaves a scope without having been able to
5093 -- find a construct to wrap, something is going wrong, but this
5094 -- can happen in error situations that are not detected yet (such
5095 -- as a dynamic string in a pragma Export).
5097 when N_Block_Statement
5098 | N_Entry_Body
5099 | N_Package_Body
5100 | N_Package_Declaration
5101 | N_Protected_Body
5102 | N_Subprogram_Body
5103 | N_Task_Body
5105 return Empty;
5107 -- Default
5109 when others =>
5110 null;
5111 end case;
5113 Prev := Curr;
5114 Curr := Parent (Curr);
5115 end loop;
5117 return Empty;
5118 end Find_Transient_Context;
5120 ----------------------------------
5121 -- Has_New_Controlled_Component --
5122 ----------------------------------
5124 function Has_New_Controlled_Component (E : Entity_Id) return Boolean is
5125 Comp : Entity_Id;
5127 begin
5128 if not Is_Tagged_Type (E) then
5129 return Has_Controlled_Component (E);
5130 elsif not Is_Derived_Type (E) then
5131 return Has_Controlled_Component (E);
5132 end if;
5134 Comp := First_Component (E);
5135 while Present (Comp) loop
5136 if Chars (Comp) = Name_uParent then
5137 null;
5139 elsif Scope (Original_Record_Component (Comp)) = E
5140 and then Needs_Finalization (Etype (Comp))
5141 then
5142 return True;
5143 end if;
5145 Next_Component (Comp);
5146 end loop;
5148 return False;
5149 end Has_New_Controlled_Component;
5151 ---------------------------------
5152 -- Has_Simple_Protected_Object --
5153 ---------------------------------
5155 function Has_Simple_Protected_Object (T : Entity_Id) return Boolean is
5156 begin
5157 if Has_Task (T) then
5158 return False;
5160 elsif Is_Simple_Protected_Type (T) then
5161 return True;
5163 elsif Is_Array_Type (T) then
5164 return Has_Simple_Protected_Object (Component_Type (T));
5166 elsif Is_Record_Type (T) then
5167 declare
5168 Comp : Entity_Id;
5170 begin
5171 Comp := First_Component (T);
5172 while Present (Comp) loop
5173 if Has_Simple_Protected_Object (Etype (Comp)) then
5174 return True;
5175 end if;
5177 Next_Component (Comp);
5178 end loop;
5180 return False;
5181 end;
5183 else
5184 return False;
5185 end if;
5186 end Has_Simple_Protected_Object;
5188 ------------------------------------
5189 -- Insert_Actions_In_Scope_Around --
5190 ------------------------------------
5192 procedure Insert_Actions_In_Scope_Around
5193 (N : Node_Id;
5194 Clean : Boolean;
5195 Manage_SS : Boolean)
5197 Act_Before : constant List_Id :=
5198 Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (Before);
5199 Act_After : constant List_Id :=
5200 Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (After);
5201 Act_Cleanup : constant List_Id :=
5202 Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (Cleanup);
5203 -- Note: We used to use renamings of Scope_Stack.Table (Scope_Stack.
5204 -- Last), but this was incorrect as Process_Transients_In_Scope may
5205 -- introduce new scopes and cause a reallocation of Scope_Stack.Table.
5207 procedure Process_Transients_In_Scope
5208 (First_Object : Node_Id;
5209 Last_Object : Node_Id;
5210 Related_Node : Node_Id);
5211 -- Find all transient objects in the list First_Object .. Last_Object
5212 -- and generate finalization actions for them. Related_Node denotes the
5213 -- node which created all transient objects.
5215 ---------------------------------
5216 -- Process_Transients_In_Scope --
5217 ---------------------------------
5219 procedure Process_Transients_In_Scope
5220 (First_Object : Node_Id;
5221 Last_Object : Node_Id;
5222 Related_Node : Node_Id)
5224 Exceptions_OK : constant Boolean := Exceptions_In_Finalization_OK;
5226 Must_Hook : Boolean := False;
5227 -- Flag denoting whether the context requires transient object
5228 -- export to the outer finalizer.
5230 function Is_Subprogram_Call (N : Node_Id) return Traverse_Result;
5231 -- Determine whether an arbitrary node denotes a subprogram call
5233 procedure Detect_Subprogram_Call is
5234 new Traverse_Proc (Is_Subprogram_Call);
5236 procedure Process_Transient_In_Scope
5237 (Obj_Decl : Node_Id;
5238 Blk_Data : Finalization_Exception_Data;
5239 Blk_Stmts : List_Id);
5240 -- Generate finalization actions for a single transient object
5241 -- denoted by object declaration Obj_Decl. Blk_Data is the
5242 -- exception data of the enclosing block. Blk_Stmts denotes the
5243 -- statements of the enclosing block.
5245 ------------------------
5246 -- Is_Subprogram_Call --
5247 ------------------------
5249 function Is_Subprogram_Call (N : Node_Id) return Traverse_Result is
5250 begin
5251 -- A regular procedure or function call
5253 if Nkind (N) in N_Subprogram_Call then
5254 Must_Hook := True;
5255 return Abandon;
5257 -- Special cases
5259 -- Heavy expansion may relocate function calls outside the related
5260 -- node. Inspect the original node to detect the initial placement
5261 -- of the call.
5263 elsif Is_Rewrite_Substitution (N) then
5264 Detect_Subprogram_Call (Original_Node (N));
5266 if Must_Hook then
5267 return Abandon;
5268 else
5269 return OK;
5270 end if;
5272 -- Generalized indexing always involves a function call
5274 elsif Nkind (N) = N_Indexed_Component
5275 and then Present (Generalized_Indexing (N))
5276 then
5277 Must_Hook := True;
5278 return Abandon;
5280 -- Keep searching
5282 else
5283 return OK;
5284 end if;
5285 end Is_Subprogram_Call;
5287 --------------------------------
5288 -- Process_Transient_In_Scope --
5289 --------------------------------
5291 procedure Process_Transient_In_Scope
5292 (Obj_Decl : Node_Id;
5293 Blk_Data : Finalization_Exception_Data;
5294 Blk_Stmts : List_Id)
5296 Loc : constant Source_Ptr := Sloc (Obj_Decl);
5297 Obj_Id : constant Entity_Id := Defining_Entity (Obj_Decl);
5298 Fin_Call : Node_Id;
5299 Fin_Stmts : List_Id;
5300 Hook_Assign : Node_Id;
5301 Hook_Clear : Node_Id;
5302 Hook_Decl : Node_Id;
5303 Hook_Insert : Node_Id;
5304 Ptr_Decl : Node_Id;
5306 begin
5307 -- Mark the transient object as successfully processed to avoid
5308 -- double finalization.
5310 Set_Is_Finalized_Transient (Obj_Id);
5312 -- Construct all the pieces necessary to hook and finalize the
5313 -- transient object.
5315 Build_Transient_Object_Statements
5316 (Obj_Decl => Obj_Decl,
5317 Fin_Call => Fin_Call,
5318 Hook_Assign => Hook_Assign,
5319 Hook_Clear => Hook_Clear,
5320 Hook_Decl => Hook_Decl,
5321 Ptr_Decl => Ptr_Decl);
5323 -- The context contains at least one subprogram call which may
5324 -- raise an exception. This scenario employs "hooking" to pass
5325 -- transient objects to the enclosing finalizer in case of an
5326 -- exception.
5328 if Must_Hook then
5330 -- Add the access type which provides a reference to the
5331 -- transient object. Generate:
5333 -- type Ptr_Typ is access all Desig_Typ;
5335 Insert_Action (Obj_Decl, Ptr_Decl);
5337 -- Add the temporary which acts as a hook to the transient
5338 -- object. Generate:
5340 -- Hook : Ptr_Typ := null;
5342 Insert_Action (Obj_Decl, Hook_Decl);
5344 -- When the transient object is initialized by an aggregate,
5345 -- the hook must capture the object after the last aggregate
5346 -- assignment takes place. Only then is the object considered
5347 -- fully initialized. Generate:
5349 -- Hook := Ptr_Typ (Obj_Id);
5350 -- <or>
5351 -- Hook := Obj_Id'Unrestricted_Access;
5353 if Ekind_In (Obj_Id, E_Constant, E_Variable)
5354 and then Present (Last_Aggregate_Assignment (Obj_Id))
5355 then
5356 Hook_Insert := Last_Aggregate_Assignment (Obj_Id);
5358 -- Otherwise the hook seizes the related object immediately
5360 else
5361 Hook_Insert := Obj_Decl;
5362 end if;
5364 Insert_After_And_Analyze (Hook_Insert, Hook_Assign);
5365 end if;
5367 -- When exception propagation is enabled wrap the hook clear
5368 -- statement and the finalization call into a block to catch
5369 -- potential exceptions raised during finalization. Generate:
5371 -- begin
5372 -- [Hook := null;]
5373 -- [Deep_]Finalize (Obj_Ref);
5375 -- exception
5376 -- when others =>
5377 -- if not Raised then
5378 -- Raised := True;
5379 -- Save_Occurrence
5380 -- (Enn, Get_Current_Excep.all.all);
5381 -- end if;
5382 -- end;
5384 if Exceptions_OK then
5385 Fin_Stmts := New_List;
5387 if Must_Hook then
5388 Append_To (Fin_Stmts, Hook_Clear);
5389 end if;
5391 Append_To (Fin_Stmts, Fin_Call);
5393 Prepend_To (Blk_Stmts,
5394 Make_Block_Statement (Loc,
5395 Handled_Statement_Sequence =>
5396 Make_Handled_Sequence_Of_Statements (Loc,
5397 Statements => Fin_Stmts,
5398 Exception_Handlers => New_List (
5399 Build_Exception_Handler (Blk_Data)))));
5401 -- Otherwise generate:
5403 -- [Hook := null;]
5404 -- [Deep_]Finalize (Obj_Ref);
5406 -- Note that the statements are inserted in reverse order to
5407 -- achieve the desired final order outlined above.
5409 else
5410 Prepend_To (Blk_Stmts, Fin_Call);
5412 if Must_Hook then
5413 Prepend_To (Blk_Stmts, Hook_Clear);
5414 end if;
5415 end if;
5416 end Process_Transient_In_Scope;
5418 -- Local variables
5420 Built : Boolean := False;
5421 Blk_Data : Finalization_Exception_Data;
5422 Blk_Decl : Node_Id := Empty;
5423 Blk_Decls : List_Id := No_List;
5424 Blk_Ins : Node_Id;
5425 Blk_Stmts : List_Id;
5426 Loc : Source_Ptr;
5427 Obj_Decl : Node_Id;
5429 -- Start of processing for Process_Transients_In_Scope
5431 begin
5432 -- The expansion performed by this routine is as follows:
5434 -- type Ptr_Typ_1 is access all Ctrl_Trans_Obj_1_Typ;
5435 -- Hook_1 : Ptr_Typ_1 := null;
5436 -- Ctrl_Trans_Obj_1 : ...;
5437 -- Hook_1 := Ctrl_Trans_Obj_1'Unrestricted_Access;
5438 -- . . .
5439 -- type Ptr_Typ_N is access all Ctrl_Trans_Obj_N_Typ;
5440 -- Hook_N : Ptr_Typ_N := null;
5441 -- Ctrl_Trans_Obj_N : ...;
5442 -- Hook_N := Ctrl_Trans_Obj_N'Unrestricted_Access;
5444 -- declare
5445 -- Abrt : constant Boolean := ...;
5446 -- Ex : Exception_Occurrence;
5447 -- Raised : Boolean := False;
5449 -- begin
5450 -- Abort_Defer;
5452 -- begin
5453 -- Hook_N := null;
5454 -- [Deep_]Finalize (Ctrl_Trans_Obj_N);
5456 -- exception
5457 -- when others =>
5458 -- if not Raised then
5459 -- Raised := True;
5460 -- Save_Occurrence (Ex, Get_Current_Excep.all.all);
5461 -- end;
5462 -- . . .
5463 -- begin
5464 -- Hook_1 := null;
5465 -- [Deep_]Finalize (Ctrl_Trans_Obj_1);
5467 -- exception
5468 -- when others =>
5469 -- if not Raised then
5470 -- Raised := True;
5471 -- Save_Occurrence (Ex, Get_Current_Excep.all.all);
5472 -- end;
5474 -- Abort_Undefer;
5476 -- if Raised and not Abrt then
5477 -- Raise_From_Controlled_Operation (Ex);
5478 -- end if;
5479 -- end;
5481 -- Recognize a scenario where the transient context is an object
5482 -- declaration initialized by a build-in-place function call:
5484 -- Obj : ... := BIP_Function_Call (Ctrl_Func_Call);
5486 -- The rough expansion of the above is:
5488 -- Temp : ... := Ctrl_Func_Call;
5489 -- Obj : ...;
5490 -- Res : ... := BIP_Func_Call (..., Obj, ...);
5492 -- The finalization of any transient object must happen after the
5493 -- build-in-place function call is executed.
5495 if Nkind (N) = N_Object_Declaration
5496 and then Present (BIP_Initialization_Call (Defining_Identifier (N)))
5497 then
5498 Must_Hook := True;
5499 Blk_Ins := BIP_Initialization_Call (Defining_Identifier (N));
5501 -- Search the context for at least one subprogram call. If found, the
5502 -- machinery exports all transient objects to the enclosing finalizer
5503 -- due to the possibility of abnormal call termination.
5505 else
5506 Detect_Subprogram_Call (N);
5507 Blk_Ins := Last_Object;
5508 end if;
5510 if Clean then
5511 Insert_List_After_And_Analyze (Blk_Ins, Act_Cleanup);
5512 end if;
5514 -- Examine all objects in the list First_Object .. Last_Object
5516 Obj_Decl := First_Object;
5517 while Present (Obj_Decl) loop
5518 if Nkind (Obj_Decl) = N_Object_Declaration
5519 and then Analyzed (Obj_Decl)
5520 and then Is_Finalizable_Transient (Obj_Decl, N)
5522 -- Do not process the node to be wrapped since it will be
5523 -- handled by the enclosing finalizer.
5525 and then Obj_Decl /= Related_Node
5526 then
5527 Loc := Sloc (Obj_Decl);
5529 -- Before generating the cleanup code for the first transient
5530 -- object, create a wrapper block which houses all hook clear
5531 -- statements and finalization calls. This wrapper is needed by
5532 -- the back end.
5534 if not Built then
5535 Built := True;
5536 Blk_Stmts := New_List;
5538 -- Generate:
5539 -- Abrt : constant Boolean := ...;
5540 -- Ex : Exception_Occurrence;
5541 -- Raised : Boolean := False;
5543 if Exceptions_OK then
5544 Blk_Decls := New_List;
5545 Build_Object_Declarations (Blk_Data, Blk_Decls, Loc);
5546 end if;
5548 Blk_Decl :=
5549 Make_Block_Statement (Loc,
5550 Declarations => Blk_Decls,
5551 Handled_Statement_Sequence =>
5552 Make_Handled_Sequence_Of_Statements (Loc,
5553 Statements => Blk_Stmts));
5554 end if;
5556 -- Construct all necessary circuitry to hook and finalize a
5557 -- single transient object.
5559 Process_Transient_In_Scope
5560 (Obj_Decl => Obj_Decl,
5561 Blk_Data => Blk_Data,
5562 Blk_Stmts => Blk_Stmts);
5563 end if;
5565 -- Terminate the scan after the last object has been processed to
5566 -- avoid touching unrelated code.
5568 if Obj_Decl = Last_Object then
5569 exit;
5570 end if;
5572 Next (Obj_Decl);
5573 end loop;
5575 -- Complete the decoration of the enclosing finalization block and
5576 -- insert it into the tree.
5578 if Present (Blk_Decl) then
5580 -- Note that this Abort_Undefer does not require a extra block or
5581 -- an AT_END handler because each finalization exception is caught
5582 -- in its own corresponding finalization block. As a result, the
5583 -- call to Abort_Defer always takes place.
5585 if Abort_Allowed then
5586 Prepend_To (Blk_Stmts,
5587 Build_Runtime_Call (Loc, RE_Abort_Defer));
5589 Append_To (Blk_Stmts,
5590 Build_Runtime_Call (Loc, RE_Abort_Undefer));
5591 end if;
5593 -- Generate:
5594 -- if Raised and then not Abrt then
5595 -- Raise_From_Controlled_Operation (Ex);
5596 -- end if;
5598 if Exceptions_OK then
5599 Append_To (Blk_Stmts, Build_Raise_Statement (Blk_Data));
5600 end if;
5602 Insert_After_And_Analyze (Blk_Ins, Blk_Decl);
5603 end if;
5604 end Process_Transients_In_Scope;
5606 -- Local variables
5608 Loc : constant Source_Ptr := Sloc (N);
5609 Node_To_Wrap : constant Node_Id := Node_To_Be_Wrapped;
5610 First_Obj : Node_Id;
5611 Last_Obj : Node_Id;
5612 Mark_Id : Entity_Id;
5613 Target : Node_Id;
5615 -- Start of processing for Insert_Actions_In_Scope_Around
5617 begin
5618 -- Nothing to do if the scope does not manage the secondary stack or
5619 -- does not contain meaninful actions for insertion.
5621 if not Manage_SS
5622 and then No (Act_Before)
5623 and then No (Act_After)
5624 and then No (Act_Cleanup)
5625 then
5626 return;
5627 end if;
5629 -- If the node to be wrapped is the trigger of an asynchronous select,
5630 -- it is not part of a statement list. The actions must be inserted
5631 -- before the select itself, which is part of some list of statements.
5632 -- Note that the triggering alternative includes the triggering
5633 -- statement and an optional statement list. If the node to be
5634 -- wrapped is part of that list, the normal insertion applies.
5636 if Nkind (Parent (Node_To_Wrap)) = N_Triggering_Alternative
5637 and then not Is_List_Member (Node_To_Wrap)
5638 then
5639 Target := Parent (Parent (Node_To_Wrap));
5640 else
5641 Target := N;
5642 end if;
5644 First_Obj := Target;
5645 Last_Obj := Target;
5647 -- Add all actions associated with a transient scope into the main tree.
5648 -- There are several scenarios here:
5650 -- +--- Before ----+ +----- After ---+
5651 -- 1) First_Obj ....... Target ........ Last_Obj
5653 -- 2) First_Obj ....... Target
5655 -- 3) Target ........ Last_Obj
5657 -- Flag declarations are inserted before the first object
5659 if Present (Act_Before) then
5660 First_Obj := First (Act_Before);
5661 Insert_List_Before (Target, Act_Before);
5662 end if;
5664 -- Finalization calls are inserted after the last object
5666 if Present (Act_After) then
5667 Last_Obj := Last (Act_After);
5668 Insert_List_After (Target, Act_After);
5669 end if;
5671 -- Mark and release the secondary stack when the context warrants it
5673 if Manage_SS then
5674 Mark_Id := Make_Temporary (Loc, 'M');
5676 -- Generate:
5677 -- Mnn : constant Mark_Id := SS_Mark;
5679 Insert_Before_And_Analyze
5680 (First_Obj, Build_SS_Mark_Call (Loc, Mark_Id));
5682 -- Generate:
5683 -- SS_Release (Mnn);
5685 Insert_After_And_Analyze
5686 (Last_Obj, Build_SS_Release_Call (Loc, Mark_Id));
5687 end if;
5689 -- Check for transient objects associated with Target and generate the
5690 -- appropriate finalization actions for them.
5692 Process_Transients_In_Scope
5693 (First_Object => First_Obj,
5694 Last_Object => Last_Obj,
5695 Related_Node => Target);
5697 -- Reset the action lists
5699 Scope_Stack.Table
5700 (Scope_Stack.Last).Actions_To_Be_Wrapped (Before) := No_List;
5701 Scope_Stack.Table
5702 (Scope_Stack.Last).Actions_To_Be_Wrapped (After) := No_List;
5704 if Clean then
5705 Scope_Stack.Table
5706 (Scope_Stack.Last).Actions_To_Be_Wrapped (Cleanup) := No_List;
5707 end if;
5708 end Insert_Actions_In_Scope_Around;
5710 ------------------------------
5711 -- Is_Simple_Protected_Type --
5712 ------------------------------
5714 function Is_Simple_Protected_Type (T : Entity_Id) return Boolean is
5715 begin
5716 return
5717 Is_Protected_Type (T)
5718 and then not Uses_Lock_Free (T)
5719 and then not Has_Entries (T)
5720 and then Is_RTE (Find_Protection_Type (T), RE_Protection);
5721 end Is_Simple_Protected_Type;
5723 -----------------------
5724 -- Make_Adjust_Call --
5725 -----------------------
5727 function Make_Adjust_Call
5728 (Obj_Ref : Node_Id;
5729 Typ : Entity_Id;
5730 Skip_Self : Boolean := False) return Node_Id
5732 Loc : constant Source_Ptr := Sloc (Obj_Ref);
5733 Adj_Id : Entity_Id := Empty;
5734 Ref : Node_Id;
5735 Utyp : Entity_Id;
5737 begin
5738 Ref := Obj_Ref;
5740 -- Recover the proper type which contains Deep_Adjust
5742 if Is_Class_Wide_Type (Typ) then
5743 Utyp := Root_Type (Typ);
5744 else
5745 Utyp := Typ;
5746 end if;
5748 Utyp := Underlying_Type (Base_Type (Utyp));
5749 Set_Assignment_OK (Ref);
5751 -- Deal with untagged derivation of private views
5753 if Present (Utyp) and then Is_Untagged_Derivation (Typ) then
5754 Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
5755 Ref := Unchecked_Convert_To (Utyp, Ref);
5756 Set_Assignment_OK (Ref);
5757 end if;
5759 -- When dealing with the completion of a private type, use the base
5760 -- type instead.
5762 if Present (Utyp) and then Utyp /= Base_Type (Utyp) then
5763 pragma Assert (Is_Private_Type (Typ));
5765 Utyp := Base_Type (Utyp);
5766 Ref := Unchecked_Convert_To (Utyp, Ref);
5767 end if;
5769 -- The underlying type may not be present due to a missing full view. In
5770 -- this case freezing did not take place and there is no [Deep_]Adjust
5771 -- primitive to call.
5773 if No (Utyp) then
5774 return Empty;
5776 elsif Skip_Self then
5777 if Has_Controlled_Component (Utyp) then
5778 if Is_Tagged_Type (Utyp) then
5779 Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust);
5780 else
5781 Adj_Id := TSS (Utyp, TSS_Deep_Adjust);
5782 end if;
5783 end if;
5785 -- Class-wide types, interfaces and types with controlled components
5787 elsif Is_Class_Wide_Type (Typ)
5788 or else Is_Interface (Typ)
5789 or else Has_Controlled_Component (Utyp)
5790 then
5791 if Is_Tagged_Type (Utyp) then
5792 Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust);
5793 else
5794 Adj_Id := TSS (Utyp, TSS_Deep_Adjust);
5795 end if;
5797 -- Derivations from [Limited_]Controlled
5799 elsif Is_Controlled (Utyp) then
5800 if Has_Controlled_Component (Utyp) then
5801 Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust);
5802 else
5803 Adj_Id := Find_Optional_Prim_Op (Utyp, Name_Of (Adjust_Case));
5804 end if;
5806 -- Tagged types
5808 elsif Is_Tagged_Type (Utyp) then
5809 Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust);
5811 else
5812 raise Program_Error;
5813 end if;
5815 if Present (Adj_Id) then
5817 -- If the object is unanalyzed, set its expected type for use in
5818 -- Convert_View in case an additional conversion is needed.
5820 if No (Etype (Ref))
5821 and then Nkind (Ref) /= N_Unchecked_Type_Conversion
5822 then
5823 Set_Etype (Ref, Typ);
5824 end if;
5826 -- The object reference may need another conversion depending on the
5827 -- type of the formal and that of the actual.
5829 if not Is_Class_Wide_Type (Typ) then
5830 Ref := Convert_View (Adj_Id, Ref);
5831 end if;
5833 return
5834 Make_Call (Loc,
5835 Proc_Id => Adj_Id,
5836 Param => Ref,
5837 Skip_Self => Skip_Self);
5838 else
5839 return Empty;
5840 end if;
5841 end Make_Adjust_Call;
5843 ----------------------
5844 -- Make_Detach_Call --
5845 ----------------------
5847 function Make_Detach_Call (Obj_Ref : Node_Id) return Node_Id is
5848 Loc : constant Source_Ptr := Sloc (Obj_Ref);
5850 begin
5851 return
5852 Make_Procedure_Call_Statement (Loc,
5853 Name =>
5854 New_Occurrence_Of (RTE (RE_Detach), Loc),
5855 Parameter_Associations => New_List (
5856 Unchecked_Convert_To (RTE (RE_Root_Controlled_Ptr), Obj_Ref)));
5857 end Make_Detach_Call;
5859 ---------------
5860 -- Make_Call --
5861 ---------------
5863 function Make_Call
5864 (Loc : Source_Ptr;
5865 Proc_Id : Entity_Id;
5866 Param : Node_Id;
5867 Skip_Self : Boolean := False) return Node_Id
5869 Params : constant List_Id := New_List (Param);
5871 begin
5872 -- Do not apply the controlled action to the object itself by signaling
5873 -- the related routine to avoid self.
5875 if Skip_Self then
5876 Append_To (Params, New_Occurrence_Of (Standard_False, Loc));
5877 end if;
5879 return
5880 Make_Procedure_Call_Statement (Loc,
5881 Name => New_Occurrence_Of (Proc_Id, Loc),
5882 Parameter_Associations => Params);
5883 end Make_Call;
5885 --------------------------
5886 -- Make_Deep_Array_Body --
5887 --------------------------
5889 function Make_Deep_Array_Body
5890 (Prim : Final_Primitives;
5891 Typ : Entity_Id) return List_Id
5893 Exceptions_OK : constant Boolean := Exceptions_In_Finalization_OK;
5895 function Build_Adjust_Or_Finalize_Statements
5896 (Typ : Entity_Id) return List_Id;
5897 -- Create the statements necessary to adjust or finalize an array of
5898 -- controlled elements. Generate:
5900 -- declare
5901 -- Abort : constant Boolean := Triggered_By_Abort;
5902 -- <or>
5903 -- Abort : constant Boolean := False; -- no abort
5905 -- E : Exception_Occurrence;
5906 -- Raised : Boolean := False;
5908 -- begin
5909 -- for J1 in [reverse] Typ'First (1) .. Typ'Last (1) loop
5910 -- ^-- in the finalization case
5911 -- ...
5912 -- for Jn in [reverse] Typ'First (n) .. Typ'Last (n) loop
5913 -- begin
5914 -- [Deep_]Adjust / Finalize (V (J1, ..., Jn));
5916 -- exception
5917 -- when others =>
5918 -- if not Raised then
5919 -- Raised := True;
5920 -- Save_Occurrence (E, Get_Current_Excep.all.all);
5921 -- end if;
5922 -- end;
5923 -- end loop;
5924 -- ...
5925 -- end loop;
5927 -- if Raised and then not Abort then
5928 -- Raise_From_Controlled_Operation (E);
5929 -- end if;
5930 -- end;
5932 function Build_Initialize_Statements (Typ : Entity_Id) return List_Id;
5933 -- Create the statements necessary to initialize an array of controlled
5934 -- elements. Include a mechanism to carry out partial finalization if an
5935 -- exception occurs. Generate:
5937 -- declare
5938 -- Counter : Integer := 0;
5940 -- begin
5941 -- for J1 in V'Range (1) loop
5942 -- ...
5943 -- for JN in V'Range (N) loop
5944 -- begin
5945 -- [Deep_]Initialize (V (J1, ..., JN));
5947 -- Counter := Counter + 1;
5949 -- exception
5950 -- when others =>
5951 -- declare
5952 -- Abort : constant Boolean := Triggered_By_Abort;
5953 -- <or>
5954 -- Abort : constant Boolean := False; -- no abort
5955 -- E : Exception_Occurrence;
5956 -- Raised : Boolean := False;
5958 -- begin
5959 -- Counter :=
5960 -- V'Length (1) *
5961 -- V'Length (2) *
5962 -- ...
5963 -- V'Length (N) - Counter;
5965 -- for F1 in reverse V'Range (1) loop
5966 -- ...
5967 -- for FN in reverse V'Range (N) loop
5968 -- if Counter > 0 then
5969 -- Counter := Counter - 1;
5970 -- else
5971 -- begin
5972 -- [Deep_]Finalize (V (F1, ..., FN));
5974 -- exception
5975 -- when others =>
5976 -- if not Raised then
5977 -- Raised := True;
5978 -- Save_Occurrence (E,
5979 -- Get_Current_Excep.all.all);
5980 -- end if;
5981 -- end;
5982 -- end if;
5983 -- end loop;
5984 -- ...
5985 -- end loop;
5986 -- end;
5988 -- if Raised and then not Abort then
5989 -- Raise_From_Controlled_Operation (E);
5990 -- end if;
5992 -- raise;
5993 -- end;
5994 -- end loop;
5995 -- end loop;
5996 -- end;
5998 function New_References_To
5999 (L : List_Id;
6000 Loc : Source_Ptr) return List_Id;
6001 -- Given a list of defining identifiers, return a list of references to
6002 -- the original identifiers, in the same order as they appear.
6004 -----------------------------------------
6005 -- Build_Adjust_Or_Finalize_Statements --
6006 -----------------------------------------
6008 function Build_Adjust_Or_Finalize_Statements
6009 (Typ : Entity_Id) return List_Id
6011 Comp_Typ : constant Entity_Id := Component_Type (Typ);
6012 Index_List : constant List_Id := New_List;
6013 Loc : constant Source_Ptr := Sloc (Typ);
6014 Num_Dims : constant Int := Number_Dimensions (Typ);
6016 procedure Build_Indexes;
6017 -- Generate the indexes used in the dimension loops
6019 -------------------
6020 -- Build_Indexes --
6021 -------------------
6023 procedure Build_Indexes is
6024 begin
6025 -- Generate the following identifiers:
6026 -- Jnn - for initialization
6028 for Dim in 1 .. Num_Dims loop
6029 Append_To (Index_List,
6030 Make_Defining_Identifier (Loc, New_External_Name ('J', Dim)));
6031 end loop;
6032 end Build_Indexes;
6034 -- Local variables
6036 Final_Decls : List_Id := No_List;
6037 Final_Data : Finalization_Exception_Data;
6038 Block : Node_Id;
6039 Call : Node_Id;
6040 Comp_Ref : Node_Id;
6041 Core_Loop : Node_Id;
6042 Dim : Int;
6043 J : Entity_Id;
6044 Loop_Id : Entity_Id;
6045 Stmts : List_Id;
6047 -- Start of processing for Build_Adjust_Or_Finalize_Statements
6049 begin
6050 Final_Decls := New_List;
6052 Build_Indexes;
6053 Build_Object_Declarations (Final_Data, Final_Decls, Loc);
6055 Comp_Ref :=
6056 Make_Indexed_Component (Loc,
6057 Prefix => Make_Identifier (Loc, Name_V),
6058 Expressions => New_References_To (Index_List, Loc));
6059 Set_Etype (Comp_Ref, Comp_Typ);
6061 -- Generate:
6062 -- [Deep_]Adjust (V (J1, ..., JN))
6064 if Prim = Adjust_Case then
6065 Call := Make_Adjust_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ);
6067 -- Generate:
6068 -- [Deep_]Finalize (V (J1, ..., JN))
6070 else pragma Assert (Prim = Finalize_Case);
6071 Call := Make_Final_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ);
6072 end if;
6074 if Present (Call) then
6076 -- Generate the block which houses the adjust or finalize call:
6078 -- begin
6079 -- <adjust or finalize call>
6081 -- exception
6082 -- when others =>
6083 -- if not Raised then
6084 -- Raised := True;
6085 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6086 -- end if;
6087 -- end;
6089 if Exceptions_OK then
6090 Core_Loop :=
6091 Make_Block_Statement (Loc,
6092 Handled_Statement_Sequence =>
6093 Make_Handled_Sequence_Of_Statements (Loc,
6094 Statements => New_List (Call),
6095 Exception_Handlers => New_List (
6096 Build_Exception_Handler (Final_Data))));
6097 else
6098 Core_Loop := Call;
6099 end if;
6101 -- Generate the dimension loops starting from the innermost one
6103 -- for Jnn in [reverse] V'Range (Dim) loop
6104 -- <core loop>
6105 -- end loop;
6107 J := Last (Index_List);
6108 Dim := Num_Dims;
6109 while Present (J) and then Dim > 0 loop
6110 Loop_Id := J;
6111 Prev (J);
6112 Remove (Loop_Id);
6114 Core_Loop :=
6115 Make_Loop_Statement (Loc,
6116 Iteration_Scheme =>
6117 Make_Iteration_Scheme (Loc,
6118 Loop_Parameter_Specification =>
6119 Make_Loop_Parameter_Specification (Loc,
6120 Defining_Identifier => Loop_Id,
6121 Discrete_Subtype_Definition =>
6122 Make_Attribute_Reference (Loc,
6123 Prefix => Make_Identifier (Loc, Name_V),
6124 Attribute_Name => Name_Range,
6125 Expressions => New_List (
6126 Make_Integer_Literal (Loc, Dim))),
6128 Reverse_Present =>
6129 Prim = Finalize_Case)),
6131 Statements => New_List (Core_Loop),
6132 End_Label => Empty);
6134 Dim := Dim - 1;
6135 end loop;
6137 -- Generate the block which contains the core loop, declarations
6138 -- of the abort flag, the exception occurrence, the raised flag
6139 -- and the conditional raise:
6141 -- declare
6142 -- Abort : constant Boolean := Triggered_By_Abort;
6143 -- <or>
6144 -- Abort : constant Boolean := False; -- no abort
6146 -- E : Exception_Occurrence;
6147 -- Raised : Boolean := False;
6149 -- begin
6150 -- <core loop>
6152 -- if Raised and then not Abort then
6153 -- Raise_From_Controlled_Operation (E);
6154 -- end if;
6155 -- end;
6157 Stmts := New_List (Core_Loop);
6159 if Exceptions_OK then
6160 Append_To (Stmts, Build_Raise_Statement (Final_Data));
6161 end if;
6163 Block :=
6164 Make_Block_Statement (Loc,
6165 Declarations => Final_Decls,
6166 Handled_Statement_Sequence =>
6167 Make_Handled_Sequence_Of_Statements (Loc,
6168 Statements => Stmts));
6170 -- Otherwise previous errors or a missing full view may prevent the
6171 -- proper freezing of the component type. If this is the case, there
6172 -- is no [Deep_]Adjust or [Deep_]Finalize primitive to call.
6174 else
6175 Block := Make_Null_Statement (Loc);
6176 end if;
6178 return New_List (Block);
6179 end Build_Adjust_Or_Finalize_Statements;
6181 ---------------------------------
6182 -- Build_Initialize_Statements --
6183 ---------------------------------
6185 function Build_Initialize_Statements (Typ : Entity_Id) return List_Id is
6186 Comp_Typ : constant Entity_Id := Component_Type (Typ);
6187 Final_List : constant List_Id := New_List;
6188 Index_List : constant List_Id := New_List;
6189 Loc : constant Source_Ptr := Sloc (Typ);
6190 Num_Dims : constant Int := Number_Dimensions (Typ);
6192 function Build_Assignment (Counter_Id : Entity_Id) return Node_Id;
6193 -- Generate the following assignment:
6194 -- Counter := V'Length (1) *
6195 -- ...
6196 -- V'Length (N) - Counter;
6198 -- Counter_Id denotes the entity of the counter.
6200 function Build_Finalization_Call return Node_Id;
6201 -- Generate a deep finalization call for an array element
6203 procedure Build_Indexes;
6204 -- Generate the initialization and finalization indexes used in the
6205 -- dimension loops.
6207 function Build_Initialization_Call return Node_Id;
6208 -- Generate a deep initialization call for an array element
6210 ----------------------
6211 -- Build_Assignment --
6212 ----------------------
6214 function Build_Assignment (Counter_Id : Entity_Id) return Node_Id is
6215 Dim : Int;
6216 Expr : Node_Id;
6218 begin
6219 -- Start from the first dimension and generate:
6220 -- V'Length (1)
6222 Dim := 1;
6223 Expr :=
6224 Make_Attribute_Reference (Loc,
6225 Prefix => Make_Identifier (Loc, Name_V),
6226 Attribute_Name => Name_Length,
6227 Expressions => New_List (Make_Integer_Literal (Loc, Dim)));
6229 -- Process the rest of the dimensions, generate:
6230 -- Expr * V'Length (N)
6232 Dim := Dim + 1;
6233 while Dim <= Num_Dims loop
6234 Expr :=
6235 Make_Op_Multiply (Loc,
6236 Left_Opnd => Expr,
6237 Right_Opnd =>
6238 Make_Attribute_Reference (Loc,
6239 Prefix => Make_Identifier (Loc, Name_V),
6240 Attribute_Name => Name_Length,
6241 Expressions => New_List (
6242 Make_Integer_Literal (Loc, Dim))));
6244 Dim := Dim + 1;
6245 end loop;
6247 -- Generate:
6248 -- Counter := Expr - Counter;
6250 return
6251 Make_Assignment_Statement (Loc,
6252 Name => New_Occurrence_Of (Counter_Id, Loc),
6253 Expression =>
6254 Make_Op_Subtract (Loc,
6255 Left_Opnd => Expr,
6256 Right_Opnd => New_Occurrence_Of (Counter_Id, Loc)));
6257 end Build_Assignment;
6259 -----------------------------
6260 -- Build_Finalization_Call --
6261 -----------------------------
6263 function Build_Finalization_Call return Node_Id is
6264 Comp_Ref : constant Node_Id :=
6265 Make_Indexed_Component (Loc,
6266 Prefix => Make_Identifier (Loc, Name_V),
6267 Expressions => New_References_To (Final_List, Loc));
6269 begin
6270 Set_Etype (Comp_Ref, Comp_Typ);
6272 -- Generate:
6273 -- [Deep_]Finalize (V);
6275 return Make_Final_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ);
6276 end Build_Finalization_Call;
6278 -------------------
6279 -- Build_Indexes --
6280 -------------------
6282 procedure Build_Indexes is
6283 begin
6284 -- Generate the following identifiers:
6285 -- Jnn - for initialization
6286 -- Fnn - for finalization
6288 for Dim in 1 .. Num_Dims loop
6289 Append_To (Index_List,
6290 Make_Defining_Identifier (Loc, New_External_Name ('J', Dim)));
6292 Append_To (Final_List,
6293 Make_Defining_Identifier (Loc, New_External_Name ('F', Dim)));
6294 end loop;
6295 end Build_Indexes;
6297 -------------------------------
6298 -- Build_Initialization_Call --
6299 -------------------------------
6301 function Build_Initialization_Call return Node_Id is
6302 Comp_Ref : constant Node_Id :=
6303 Make_Indexed_Component (Loc,
6304 Prefix => Make_Identifier (Loc, Name_V),
6305 Expressions => New_References_To (Index_List, Loc));
6307 begin
6308 Set_Etype (Comp_Ref, Comp_Typ);
6310 -- Generate:
6311 -- [Deep_]Initialize (V (J1, ..., JN));
6313 return Make_Init_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ);
6314 end Build_Initialization_Call;
6316 -- Local variables
6318 Counter_Id : Entity_Id;
6319 Dim : Int;
6320 F : Node_Id;
6321 Fin_Stmt : Node_Id;
6322 Final_Block : Node_Id;
6323 Final_Data : Finalization_Exception_Data;
6324 Final_Decls : List_Id := No_List;
6325 Final_Loop : Node_Id;
6326 Init_Block : Node_Id;
6327 Init_Call : Node_Id;
6328 Init_Loop : Node_Id;
6329 J : Node_Id;
6330 Loop_Id : Node_Id;
6331 Stmts : List_Id;
6333 -- Start of processing for Build_Initialize_Statements
6335 begin
6336 Counter_Id := Make_Temporary (Loc, 'C');
6337 Final_Decls := New_List;
6339 Build_Indexes;
6340 Build_Object_Declarations (Final_Data, Final_Decls, Loc);
6342 -- Generate the block which houses the finalization call, the index
6343 -- guard and the handler which triggers Program_Error later on.
6345 -- if Counter > 0 then
6346 -- Counter := Counter - 1;
6347 -- else
6348 -- begin
6349 -- [Deep_]Finalize (V (F1, ..., FN));
6350 -- exception
6351 -- when others =>
6352 -- if not Raised then
6353 -- Raised := True;
6354 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6355 -- end if;
6356 -- end;
6357 -- end if;
6359 Fin_Stmt := Build_Finalization_Call;
6361 if Present (Fin_Stmt) then
6362 if Exceptions_OK then
6363 Fin_Stmt :=
6364 Make_Block_Statement (Loc,
6365 Handled_Statement_Sequence =>
6366 Make_Handled_Sequence_Of_Statements (Loc,
6367 Statements => New_List (Fin_Stmt),
6368 Exception_Handlers => New_List (
6369 Build_Exception_Handler (Final_Data))));
6370 end if;
6372 -- This is the core of the loop, the dimension iterators are added
6373 -- one by one in reverse.
6375 Final_Loop :=
6376 Make_If_Statement (Loc,
6377 Condition =>
6378 Make_Op_Gt (Loc,
6379 Left_Opnd => New_Occurrence_Of (Counter_Id, Loc),
6380 Right_Opnd => Make_Integer_Literal (Loc, 0)),
6382 Then_Statements => New_List (
6383 Make_Assignment_Statement (Loc,
6384 Name => New_Occurrence_Of (Counter_Id, Loc),
6385 Expression =>
6386 Make_Op_Subtract (Loc,
6387 Left_Opnd => New_Occurrence_Of (Counter_Id, Loc),
6388 Right_Opnd => Make_Integer_Literal (Loc, 1)))),
6390 Else_Statements => New_List (Fin_Stmt));
6392 -- Generate all finalization loops starting from the innermost
6393 -- dimension.
6395 -- for Fnn in reverse V'Range (Dim) loop
6396 -- <final loop>
6397 -- end loop;
6399 F := Last (Final_List);
6400 Dim := Num_Dims;
6401 while Present (F) and then Dim > 0 loop
6402 Loop_Id := F;
6403 Prev (F);
6404 Remove (Loop_Id);
6406 Final_Loop :=
6407 Make_Loop_Statement (Loc,
6408 Iteration_Scheme =>
6409 Make_Iteration_Scheme (Loc,
6410 Loop_Parameter_Specification =>
6411 Make_Loop_Parameter_Specification (Loc,
6412 Defining_Identifier => Loop_Id,
6413 Discrete_Subtype_Definition =>
6414 Make_Attribute_Reference (Loc,
6415 Prefix => Make_Identifier (Loc, Name_V),
6416 Attribute_Name => Name_Range,
6417 Expressions => New_List (
6418 Make_Integer_Literal (Loc, Dim))),
6420 Reverse_Present => True)),
6422 Statements => New_List (Final_Loop),
6423 End_Label => Empty);
6425 Dim := Dim - 1;
6426 end loop;
6428 -- Generate the block which contains the finalization loops, the
6429 -- declarations of the abort flag, the exception occurrence, the
6430 -- raised flag and the conditional raise.
6432 -- declare
6433 -- Abort : constant Boolean := Triggered_By_Abort;
6434 -- <or>
6435 -- Abort : constant Boolean := False; -- no abort
6437 -- E : Exception_Occurrence;
6438 -- Raised : Boolean := False;
6440 -- begin
6441 -- Counter :=
6442 -- V'Length (1) *
6443 -- ...
6444 -- V'Length (N) - Counter;
6446 -- <final loop>
6448 -- if Raised and then not Abort then
6449 -- Raise_From_Controlled_Operation (E);
6450 -- end if;
6452 -- raise;
6453 -- end;
6455 Stmts := New_List (Build_Assignment (Counter_Id), Final_Loop);
6457 if Exceptions_OK then
6458 Append_To (Stmts, Build_Raise_Statement (Final_Data));
6459 Append_To (Stmts, Make_Raise_Statement (Loc));
6460 end if;
6462 Final_Block :=
6463 Make_Block_Statement (Loc,
6464 Declarations => Final_Decls,
6465 Handled_Statement_Sequence =>
6466 Make_Handled_Sequence_Of_Statements (Loc,
6467 Statements => Stmts));
6469 -- Otherwise previous errors or a missing full view may prevent the
6470 -- proper freezing of the component type. If this is the case, there
6471 -- is no [Deep_]Finalize primitive to call.
6473 else
6474 Final_Block := Make_Null_Statement (Loc);
6475 end if;
6477 -- Generate the block which contains the initialization call and
6478 -- the partial finalization code.
6480 -- begin
6481 -- [Deep_]Initialize (V (J1, ..., JN));
6483 -- Counter := Counter + 1;
6485 -- exception
6486 -- when others =>
6487 -- <finalization code>
6488 -- end;
6490 Init_Call := Build_Initialization_Call;
6492 -- Only create finalization block if there is a non-trivial
6493 -- call to initialization.
6495 if Present (Init_Call)
6496 and then Nkind (Init_Call) /= N_Null_Statement
6497 then
6498 Init_Loop :=
6499 Make_Block_Statement (Loc,
6500 Handled_Statement_Sequence =>
6501 Make_Handled_Sequence_Of_Statements (Loc,
6502 Statements => New_List (Init_Call),
6503 Exception_Handlers => New_List (
6504 Make_Exception_Handler (Loc,
6505 Exception_Choices => New_List (
6506 Make_Others_Choice (Loc)),
6507 Statements => New_List (Final_Block)))));
6509 Append_To (Statements (Handled_Statement_Sequence (Init_Loop)),
6510 Make_Assignment_Statement (Loc,
6511 Name => New_Occurrence_Of (Counter_Id, Loc),
6512 Expression =>
6513 Make_Op_Add (Loc,
6514 Left_Opnd => New_Occurrence_Of (Counter_Id, Loc),
6515 Right_Opnd => Make_Integer_Literal (Loc, 1))));
6517 -- Generate all initialization loops starting from the innermost
6518 -- dimension.
6520 -- for Jnn in V'Range (Dim) loop
6521 -- <init loop>
6522 -- end loop;
6524 J := Last (Index_List);
6525 Dim := Num_Dims;
6526 while Present (J) and then Dim > 0 loop
6527 Loop_Id := J;
6528 Prev (J);
6529 Remove (Loop_Id);
6531 Init_Loop :=
6532 Make_Loop_Statement (Loc,
6533 Iteration_Scheme =>
6534 Make_Iteration_Scheme (Loc,
6535 Loop_Parameter_Specification =>
6536 Make_Loop_Parameter_Specification (Loc,
6537 Defining_Identifier => Loop_Id,
6538 Discrete_Subtype_Definition =>
6539 Make_Attribute_Reference (Loc,
6540 Prefix => Make_Identifier (Loc, Name_V),
6541 Attribute_Name => Name_Range,
6542 Expressions => New_List (
6543 Make_Integer_Literal (Loc, Dim))))),
6545 Statements => New_List (Init_Loop),
6546 End_Label => Empty);
6548 Dim := Dim - 1;
6549 end loop;
6551 -- Generate the block which contains the counter variable and the
6552 -- initialization loops.
6554 -- declare
6555 -- Counter : Integer := 0;
6556 -- begin
6557 -- <init loop>
6558 -- end;
6560 Init_Block :=
6561 Make_Block_Statement (Loc,
6562 Declarations => New_List (
6563 Make_Object_Declaration (Loc,
6564 Defining_Identifier => Counter_Id,
6565 Object_Definition =>
6566 New_Occurrence_Of (Standard_Integer, Loc),
6567 Expression => Make_Integer_Literal (Loc, 0))),
6569 Handled_Statement_Sequence =>
6570 Make_Handled_Sequence_Of_Statements (Loc,
6571 Statements => New_List (Init_Loop)));
6573 -- Otherwise previous errors or a missing full view may prevent the
6574 -- proper freezing of the component type. If this is the case, there
6575 -- is no [Deep_]Initialize primitive to call.
6577 else
6578 Init_Block := Make_Null_Statement (Loc);
6579 end if;
6581 return New_List (Init_Block);
6582 end Build_Initialize_Statements;
6584 -----------------------
6585 -- New_References_To --
6586 -----------------------
6588 function New_References_To
6589 (L : List_Id;
6590 Loc : Source_Ptr) return List_Id
6592 Refs : constant List_Id := New_List;
6593 Id : Node_Id;
6595 begin
6596 Id := First (L);
6597 while Present (Id) loop
6598 Append_To (Refs, New_Occurrence_Of (Id, Loc));
6599 Next (Id);
6600 end loop;
6602 return Refs;
6603 end New_References_To;
6605 -- Start of processing for Make_Deep_Array_Body
6607 begin
6608 case Prim is
6609 when Address_Case =>
6610 return Make_Finalize_Address_Stmts (Typ);
6612 when Adjust_Case
6613 | Finalize_Case
6615 return Build_Adjust_Or_Finalize_Statements (Typ);
6617 when Initialize_Case =>
6618 return Build_Initialize_Statements (Typ);
6619 end case;
6620 end Make_Deep_Array_Body;
6622 --------------------
6623 -- Make_Deep_Proc --
6624 --------------------
6626 function Make_Deep_Proc
6627 (Prim : Final_Primitives;
6628 Typ : Entity_Id;
6629 Stmts : List_Id) return Entity_Id
6631 Loc : constant Source_Ptr := Sloc (Typ);
6632 Formals : List_Id;
6633 Proc_Id : Entity_Id;
6635 begin
6636 -- Create the object formal, generate:
6637 -- V : System.Address
6639 if Prim = Address_Case then
6640 Formals := New_List (
6641 Make_Parameter_Specification (Loc,
6642 Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
6643 Parameter_Type =>
6644 New_Occurrence_Of (RTE (RE_Address), Loc)));
6646 -- Default case
6648 else
6649 -- V : in out Typ
6651 Formals := New_List (
6652 Make_Parameter_Specification (Loc,
6653 Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
6654 In_Present => True,
6655 Out_Present => True,
6656 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
6658 -- F : Boolean := True
6660 if Prim = Adjust_Case
6661 or else Prim = Finalize_Case
6662 then
6663 Append_To (Formals,
6664 Make_Parameter_Specification (Loc,
6665 Defining_Identifier => Make_Defining_Identifier (Loc, Name_F),
6666 Parameter_Type =>
6667 New_Occurrence_Of (Standard_Boolean, Loc),
6668 Expression =>
6669 New_Occurrence_Of (Standard_True, Loc)));
6670 end if;
6671 end if;
6673 Proc_Id :=
6674 Make_Defining_Identifier (Loc,
6675 Chars => Make_TSS_Name (Typ, Deep_Name_Of (Prim)));
6677 -- Generate:
6678 -- procedure Deep_Initialize / Adjust / Finalize (V : in out <typ>) is
6679 -- begin
6680 -- <stmts>
6681 -- exception -- Finalize and Adjust cases only
6682 -- raise Program_Error;
6683 -- end Deep_Initialize / Adjust / Finalize;
6685 -- or
6687 -- procedure Finalize_Address (V : System.Address) is
6688 -- begin
6689 -- <stmts>
6690 -- end Finalize_Address;
6692 Discard_Node (
6693 Make_Subprogram_Body (Loc,
6694 Specification =>
6695 Make_Procedure_Specification (Loc,
6696 Defining_Unit_Name => Proc_Id,
6697 Parameter_Specifications => Formals),
6699 Declarations => Empty_List,
6701 Handled_Statement_Sequence =>
6702 Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts)));
6704 -- If there are no calls to component initialization, indicate that
6705 -- the procedure is trivial, so prevent calls to it.
6707 if Is_Empty_List (Stmts)
6708 or else Nkind (First (Stmts)) = N_Null_Statement
6709 then
6710 Set_Is_Trivial_Subprogram (Proc_Id);
6711 end if;
6713 return Proc_Id;
6714 end Make_Deep_Proc;
6716 ---------------------------
6717 -- Make_Deep_Record_Body --
6718 ---------------------------
6720 function Make_Deep_Record_Body
6721 (Prim : Final_Primitives;
6722 Typ : Entity_Id;
6723 Is_Local : Boolean := False) return List_Id
6725 Exceptions_OK : constant Boolean := Exceptions_In_Finalization_OK;
6727 function Build_Adjust_Statements (Typ : Entity_Id) return List_Id;
6728 -- Build the statements necessary to adjust a record type. The type may
6729 -- have discriminants and contain variant parts. Generate:
6731 -- begin
6732 -- begin
6733 -- [Deep_]Adjust (V.Comp_1);
6734 -- exception
6735 -- when Id : others =>
6736 -- if not Raised then
6737 -- Raised := True;
6738 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6739 -- end if;
6740 -- end;
6741 -- . . .
6742 -- begin
6743 -- [Deep_]Adjust (V.Comp_N);
6744 -- exception
6745 -- when Id : others =>
6746 -- if not Raised then
6747 -- Raised := True;
6748 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6749 -- end if;
6750 -- end;
6752 -- begin
6753 -- Deep_Adjust (V._parent, False); -- If applicable
6754 -- exception
6755 -- when Id : others =>
6756 -- if not Raised then
6757 -- Raised := True;
6758 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6759 -- end if;
6760 -- end;
6762 -- if F then
6763 -- begin
6764 -- Adjust (V); -- If applicable
6765 -- exception
6766 -- when others =>
6767 -- if not Raised then
6768 -- Raised := True;
6769 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6770 -- end if;
6771 -- end;
6772 -- end if;
6774 -- if Raised and then not Abort then
6775 -- Raise_From_Controlled_Operation (E);
6776 -- end if;
6777 -- end;
6779 function Build_Finalize_Statements (Typ : Entity_Id) return List_Id;
6780 -- Build the statements necessary to finalize a record type. The type
6781 -- may have discriminants and contain variant parts. Generate:
6783 -- declare
6784 -- Abort : constant Boolean := Triggered_By_Abort;
6785 -- <or>
6786 -- Abort : constant Boolean := False; -- no abort
6787 -- E : Exception_Occurrence;
6788 -- Raised : Boolean := False;
6790 -- begin
6791 -- if F then
6792 -- begin
6793 -- Finalize (V); -- If applicable
6794 -- exception
6795 -- when others =>
6796 -- if not Raised then
6797 -- Raised := True;
6798 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6799 -- end if;
6800 -- end;
6801 -- end if;
6803 -- case Variant_1 is
6804 -- when Value_1 =>
6805 -- case State_Counter_N => -- If Is_Local is enabled
6806 -- when N => .
6807 -- goto LN; .
6808 -- ... .
6809 -- when 1 => .
6810 -- goto L1; .
6811 -- when others => .
6812 -- goto L0; .
6813 -- end case; .
6815 -- <<LN>> -- If Is_Local is enabled
6816 -- begin
6817 -- [Deep_]Finalize (V.Comp_N);
6818 -- exception
6819 -- when others =>
6820 -- if not Raised then
6821 -- Raised := True;
6822 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6823 -- end if;
6824 -- end;
6825 -- . . .
6826 -- <<L1>>
6827 -- begin
6828 -- [Deep_]Finalize (V.Comp_1);
6829 -- exception
6830 -- when others =>
6831 -- if not Raised then
6832 -- Raised := True;
6833 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6834 -- end if;
6835 -- end;
6836 -- <<L0>>
6837 -- end case;
6839 -- case State_Counter_1 => -- If Is_Local is enabled
6840 -- when M => .
6841 -- goto LM; .
6842 -- ...
6844 -- begin
6845 -- Deep_Finalize (V._parent, False); -- If applicable
6846 -- exception
6847 -- when Id : others =>
6848 -- if not Raised then
6849 -- Raised := True;
6850 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6851 -- end if;
6852 -- end;
6854 -- if Raised and then not Abort then
6855 -- Raise_From_Controlled_Operation (E);
6856 -- end if;
6857 -- end;
6859 function Parent_Field_Type (Typ : Entity_Id) return Entity_Id;
6860 -- Given a derived tagged type Typ, traverse all components, find field
6861 -- _parent and return its type.
6863 procedure Preprocess_Components
6864 (Comps : Node_Id;
6865 Num_Comps : out Nat;
6866 Has_POC : out Boolean);
6867 -- Examine all components in component list Comps, count all controlled
6868 -- components and determine whether at least one of them is per-object
6869 -- constrained. Component _parent is always skipped.
6871 -----------------------------
6872 -- Build_Adjust_Statements --
6873 -----------------------------
6875 function Build_Adjust_Statements (Typ : Entity_Id) return List_Id is
6876 Loc : constant Source_Ptr := Sloc (Typ);
6877 Typ_Def : constant Node_Id := Type_Definition (Parent (Typ));
6879 Finalizer_Data : Finalization_Exception_Data;
6881 function Process_Component_List_For_Adjust
6882 (Comps : Node_Id) return List_Id;
6883 -- Build all necessary adjust statements for a single component list
6885 ---------------------------------------
6886 -- Process_Component_List_For_Adjust --
6887 ---------------------------------------
6889 function Process_Component_List_For_Adjust
6890 (Comps : Node_Id) return List_Id
6892 Stmts : constant List_Id := New_List;
6894 procedure Process_Component_For_Adjust (Decl : Node_Id);
6895 -- Process the declaration of a single controlled component
6897 ----------------------------------
6898 -- Process_Component_For_Adjust --
6899 ----------------------------------
6901 procedure Process_Component_For_Adjust (Decl : Node_Id) is
6902 Id : constant Entity_Id := Defining_Identifier (Decl);
6903 Typ : constant Entity_Id := Etype (Id);
6905 Adj_Call : Node_Id;
6907 begin
6908 -- begin
6909 -- [Deep_]Adjust (V.Id);
6911 -- exception
6912 -- when others =>
6913 -- if not Raised then
6914 -- Raised := True;
6915 -- Save_Occurrence (E, Get_Current_Excep.all.all);
6916 -- end if;
6917 -- end;
6919 Adj_Call :=
6920 Make_Adjust_Call (
6921 Obj_Ref =>
6922 Make_Selected_Component (Loc,
6923 Prefix => Make_Identifier (Loc, Name_V),
6924 Selector_Name => Make_Identifier (Loc, Chars (Id))),
6925 Typ => Typ);
6927 -- Guard against a missing [Deep_]Adjust when the component
6928 -- type was not properly frozen.
6930 if Present (Adj_Call) then
6931 if Exceptions_OK then
6932 Adj_Call :=
6933 Make_Block_Statement (Loc,
6934 Handled_Statement_Sequence =>
6935 Make_Handled_Sequence_Of_Statements (Loc,
6936 Statements => New_List (Adj_Call),
6937 Exception_Handlers => New_List (
6938 Build_Exception_Handler (Finalizer_Data))));
6939 end if;
6941 Append_To (Stmts, Adj_Call);
6942 end if;
6943 end Process_Component_For_Adjust;
6945 -- Local variables
6947 Decl : Node_Id;
6948 Decl_Id : Entity_Id;
6949 Decl_Typ : Entity_Id;
6950 Has_POC : Boolean;
6951 Num_Comps : Nat;
6952 Var_Case : Node_Id;
6954 -- Start of processing for Process_Component_List_For_Adjust
6956 begin
6957 -- Perform an initial check, determine the number of controlled
6958 -- components in the current list and whether at least one of them
6959 -- is per-object constrained.
6961 Preprocess_Components (Comps, Num_Comps, Has_POC);
6963 -- The processing in this routine is done in the following order:
6964 -- 1) Regular components
6965 -- 2) Per-object constrained components
6966 -- 3) Variant parts
6968 if Num_Comps > 0 then
6970 -- Process all regular components in order of declarations
6972 Decl := First_Non_Pragma (Component_Items (Comps));
6973 while Present (Decl) loop
6974 Decl_Id := Defining_Identifier (Decl);
6975 Decl_Typ := Etype (Decl_Id);
6977 -- Skip _parent as well as per-object constrained components
6979 if Chars (Decl_Id) /= Name_uParent
6980 and then Needs_Finalization (Decl_Typ)
6981 then
6982 if Has_Access_Constraint (Decl_Id)
6983 and then No (Expression (Decl))
6984 then
6985 null;
6986 else
6987 Process_Component_For_Adjust (Decl);
6988 end if;
6989 end if;
6991 Next_Non_Pragma (Decl);
6992 end loop;
6994 -- Process all per-object constrained components in order of
6995 -- declarations.
6997 if Has_POC then
6998 Decl := First_Non_Pragma (Component_Items (Comps));
6999 while Present (Decl) loop
7000 Decl_Id := Defining_Identifier (Decl);
7001 Decl_Typ := Etype (Decl_Id);
7003 -- Skip _parent
7005 if Chars (Decl_Id) /= Name_uParent
7006 and then Needs_Finalization (Decl_Typ)
7007 and then Has_Access_Constraint (Decl_Id)
7008 and then No (Expression (Decl))
7009 then
7010 Process_Component_For_Adjust (Decl);
7011 end if;
7013 Next_Non_Pragma (Decl);
7014 end loop;
7015 end if;
7016 end if;
7018 -- Process all variants, if any
7020 Var_Case := Empty;
7021 if Present (Variant_Part (Comps)) then
7022 declare
7023 Var_Alts : constant List_Id := New_List;
7024 Var : Node_Id;
7026 begin
7027 Var := First_Non_Pragma (Variants (Variant_Part (Comps)));
7028 while Present (Var) loop
7030 -- Generate:
7031 -- when <discrete choices> =>
7032 -- <adjust statements>
7034 Append_To (Var_Alts,
7035 Make_Case_Statement_Alternative (Loc,
7036 Discrete_Choices =>
7037 New_Copy_List (Discrete_Choices (Var)),
7038 Statements =>
7039 Process_Component_List_For_Adjust (
7040 Component_List (Var))));
7042 Next_Non_Pragma (Var);
7043 end loop;
7045 -- Generate:
7046 -- case V.<discriminant> is
7047 -- when <discrete choices 1> =>
7048 -- <adjust statements 1>
7049 -- ...
7050 -- when <discrete choices N> =>
7051 -- <adjust statements N>
7052 -- end case;
7054 Var_Case :=
7055 Make_Case_Statement (Loc,
7056 Expression =>
7057 Make_Selected_Component (Loc,
7058 Prefix => Make_Identifier (Loc, Name_V),
7059 Selector_Name =>
7060 Make_Identifier (Loc,
7061 Chars => Chars (Name (Variant_Part (Comps))))),
7062 Alternatives => Var_Alts);
7063 end;
7064 end if;
7066 -- Add the variant case statement to the list of statements
7068 if Present (Var_Case) then
7069 Append_To (Stmts, Var_Case);
7070 end if;
7072 -- If the component list did not have any controlled components
7073 -- nor variants, return null.
7075 if Is_Empty_List (Stmts) then
7076 Append_To (Stmts, Make_Null_Statement (Loc));
7077 end if;
7079 return Stmts;
7080 end Process_Component_List_For_Adjust;
7082 -- Local variables
7084 Bod_Stmts : List_Id := No_List;
7085 Finalizer_Decls : List_Id := No_List;
7086 Rec_Def : Node_Id;
7088 -- Start of processing for Build_Adjust_Statements
7090 begin
7091 Finalizer_Decls := New_List;
7092 Build_Object_Declarations (Finalizer_Data, Finalizer_Decls, Loc);
7094 if Nkind (Typ_Def) = N_Derived_Type_Definition then
7095 Rec_Def := Record_Extension_Part (Typ_Def);
7096 else
7097 Rec_Def := Typ_Def;
7098 end if;
7100 -- Create an adjust sequence for all record components
7102 if Present (Component_List (Rec_Def)) then
7103 Bod_Stmts :=
7104 Process_Component_List_For_Adjust (Component_List (Rec_Def));
7105 end if;
7107 -- A derived record type must adjust all inherited components. This
7108 -- action poses the following problem:
7110 -- procedure Deep_Adjust (Obj : in out Parent_Typ) is
7111 -- begin
7112 -- Adjust (Obj);
7113 -- ...
7115 -- procedure Deep_Adjust (Obj : in out Derived_Typ) is
7116 -- begin
7117 -- Deep_Adjust (Obj._parent);
7118 -- ...
7119 -- Adjust (Obj);
7120 -- ...
7122 -- Adjusting the derived type will invoke Adjust of the parent and
7123 -- then that of the derived type. This is undesirable because both
7124 -- routines may modify shared components. Only the Adjust of the
7125 -- derived type should be invoked.
7127 -- To prevent this double adjustment of shared components,
7128 -- Deep_Adjust uses a flag to control the invocation of Adjust:
7130 -- procedure Deep_Adjust
7131 -- (Obj : in out Some_Type;
7132 -- Flag : Boolean := True)
7133 -- is
7134 -- begin
7135 -- if Flag then
7136 -- Adjust (Obj);
7137 -- end if;
7138 -- ...
7140 -- When Deep_Adjust is invokes for field _parent, a value of False is
7141 -- provided for the flag:
7143 -- Deep_Adjust (Obj._parent, False);
7145 if Is_Tagged_Type (Typ) and then Is_Derived_Type (Typ) then
7146 declare
7147 Par_Typ : constant Entity_Id := Parent_Field_Type (Typ);
7148 Adj_Stmt : Node_Id;
7149 Call : Node_Id;
7151 begin
7152 if Needs_Finalization (Par_Typ) then
7153 Call :=
7154 Make_Adjust_Call
7155 (Obj_Ref =>
7156 Make_Selected_Component (Loc,
7157 Prefix => Make_Identifier (Loc, Name_V),
7158 Selector_Name =>
7159 Make_Identifier (Loc, Name_uParent)),
7160 Typ => Par_Typ,
7161 Skip_Self => True);
7163 -- Generate:
7164 -- begin
7165 -- Deep_Adjust (V._parent, False);
7167 -- exception
7168 -- when Id : others =>
7169 -- if not Raised then
7170 -- Raised := True;
7171 -- Save_Occurrence (E,
7172 -- Get_Current_Excep.all.all);
7173 -- end if;
7174 -- end;
7176 if Present (Call) then
7177 Adj_Stmt := Call;
7179 if Exceptions_OK then
7180 Adj_Stmt :=
7181 Make_Block_Statement (Loc,
7182 Handled_Statement_Sequence =>
7183 Make_Handled_Sequence_Of_Statements (Loc,
7184 Statements => New_List (Adj_Stmt),
7185 Exception_Handlers => New_List (
7186 Build_Exception_Handler (Finalizer_Data))));
7187 end if;
7189 Prepend_To (Bod_Stmts, Adj_Stmt);
7190 end if;
7191 end if;
7192 end;
7193 end if;
7195 -- Adjust the object. This action must be performed last after all
7196 -- components have been adjusted.
7198 if Is_Controlled (Typ) then
7199 declare
7200 Adj_Stmt : Node_Id;
7201 Proc : Entity_Id;
7203 begin
7204 Proc := Find_Optional_Prim_Op (Typ, Name_Adjust);
7206 -- Generate:
7207 -- if F then
7208 -- begin
7209 -- Adjust (V);
7211 -- exception
7212 -- when others =>
7213 -- if not Raised then
7214 -- Raised := True;
7215 -- Save_Occurrence (E,
7216 -- Get_Current_Excep.all.all);
7217 -- end if;
7218 -- end;
7219 -- end if;
7221 if Present (Proc) then
7222 Adj_Stmt :=
7223 Make_Procedure_Call_Statement (Loc,
7224 Name => New_Occurrence_Of (Proc, Loc),
7225 Parameter_Associations => New_List (
7226 Make_Identifier (Loc, Name_V)));
7228 if Exceptions_OK then
7229 Adj_Stmt :=
7230 Make_Block_Statement (Loc,
7231 Handled_Statement_Sequence =>
7232 Make_Handled_Sequence_Of_Statements (Loc,
7233 Statements => New_List (Adj_Stmt),
7234 Exception_Handlers => New_List (
7235 Build_Exception_Handler
7236 (Finalizer_Data))));
7237 end if;
7239 Append_To (Bod_Stmts,
7240 Make_If_Statement (Loc,
7241 Condition => Make_Identifier (Loc, Name_F),
7242 Then_Statements => New_List (Adj_Stmt)));
7243 end if;
7244 end;
7245 end if;
7247 -- At this point either all adjustment statements have been generated
7248 -- or the type is not controlled.
7250 if Is_Empty_List (Bod_Stmts) then
7251 Append_To (Bod_Stmts, Make_Null_Statement (Loc));
7253 return Bod_Stmts;
7255 -- Generate:
7256 -- declare
7257 -- Abort : constant Boolean := Triggered_By_Abort;
7258 -- <or>
7259 -- Abort : constant Boolean := False; -- no abort
7261 -- E : Exception_Occurrence;
7262 -- Raised : Boolean := False;
7264 -- begin
7265 -- <adjust statements>
7267 -- if Raised and then not Abort then
7268 -- Raise_From_Controlled_Operation (E);
7269 -- end if;
7270 -- end;
7272 else
7273 if Exceptions_OK then
7274 Append_To (Bod_Stmts, Build_Raise_Statement (Finalizer_Data));
7275 end if;
7277 return
7278 New_List (
7279 Make_Block_Statement (Loc,
7280 Declarations =>
7281 Finalizer_Decls,
7282 Handled_Statement_Sequence =>
7283 Make_Handled_Sequence_Of_Statements (Loc, Bod_Stmts)));
7284 end if;
7285 end Build_Adjust_Statements;
7287 -------------------------------
7288 -- Build_Finalize_Statements --
7289 -------------------------------
7291 function Build_Finalize_Statements (Typ : Entity_Id) return List_Id is
7292 Loc : constant Source_Ptr := Sloc (Typ);
7293 Typ_Def : constant Node_Id := Type_Definition (Parent (Typ));
7295 Counter : Int := 0;
7296 Finalizer_Data : Finalization_Exception_Data;
7298 function Process_Component_List_For_Finalize
7299 (Comps : Node_Id) return List_Id;
7300 -- Build all necessary finalization statements for a single component
7301 -- list. The statements may include a jump circuitry if flag Is_Local
7302 -- is enabled.
7304 -----------------------------------------
7305 -- Process_Component_List_For_Finalize --
7306 -----------------------------------------
7308 function Process_Component_List_For_Finalize
7309 (Comps : Node_Id) return List_Id
7311 procedure Process_Component_For_Finalize
7312 (Decl : Node_Id;
7313 Alts : List_Id;
7314 Decls : List_Id;
7315 Stmts : List_Id;
7316 Num_Comps : in out Nat);
7317 -- Process the declaration of a single controlled component. If
7318 -- flag Is_Local is enabled, create the corresponding label and
7319 -- jump circuitry. Alts is the list of case alternatives, Decls
7320 -- is the top level declaration list where labels are declared
7321 -- and Stmts is the list of finalization actions. Num_Comps
7322 -- denotes the current number of components needing finalization.
7324 ------------------------------------
7325 -- Process_Component_For_Finalize --
7326 ------------------------------------
7328 procedure Process_Component_For_Finalize
7329 (Decl : Node_Id;
7330 Alts : List_Id;
7331 Decls : List_Id;
7332 Stmts : List_Id;
7333 Num_Comps : in out Nat)
7335 Id : constant Entity_Id := Defining_Identifier (Decl);
7336 Typ : constant Entity_Id := Etype (Id);
7337 Fin_Call : Node_Id;
7339 begin
7340 if Is_Local then
7341 declare
7342 Label : Node_Id;
7343 Label_Id : Entity_Id;
7345 begin
7346 -- Generate:
7347 -- LN : label;
7349 Label_Id :=
7350 Make_Identifier (Loc,
7351 Chars => New_External_Name ('L', Num_Comps));
7352 Set_Entity (Label_Id,
7353 Make_Defining_Identifier (Loc, Chars (Label_Id)));
7354 Label := Make_Label (Loc, Label_Id);
7356 Append_To (Decls,
7357 Make_Implicit_Label_Declaration (Loc,
7358 Defining_Identifier => Entity (Label_Id),
7359 Label_Construct => Label));
7361 -- Generate:
7362 -- when N =>
7363 -- goto LN;
7365 Append_To (Alts,
7366 Make_Case_Statement_Alternative (Loc,
7367 Discrete_Choices => New_List (
7368 Make_Integer_Literal (Loc, Num_Comps)),
7370 Statements => New_List (
7371 Make_Goto_Statement (Loc,
7372 Name =>
7373 New_Occurrence_Of (Entity (Label_Id), Loc)))));
7375 -- Generate:
7376 -- <<LN>>
7378 Append_To (Stmts, Label);
7380 -- Decrease the number of components to be processed.
7381 -- This action yields a new Label_Id in future calls.
7383 Num_Comps := Num_Comps - 1;
7384 end;
7385 end if;
7387 -- Generate:
7388 -- [Deep_]Finalize (V.Id); -- No_Exception_Propagation
7390 -- begin -- Exception handlers allowed
7391 -- [Deep_]Finalize (V.Id);
7392 -- exception
7393 -- when others =>
7394 -- if not Raised then
7395 -- Raised := True;
7396 -- Save_Occurrence (E,
7397 -- Get_Current_Excep.all.all);
7398 -- end if;
7399 -- end;
7401 Fin_Call :=
7402 Make_Final_Call
7403 (Obj_Ref =>
7404 Make_Selected_Component (Loc,
7405 Prefix => Make_Identifier (Loc, Name_V),
7406 Selector_Name => Make_Identifier (Loc, Chars (Id))),
7407 Typ => Typ);
7409 -- Guard against a missing [Deep_]Finalize when the component
7410 -- type was not properly frozen.
7412 if Present (Fin_Call) then
7413 if Exceptions_OK then
7414 Fin_Call :=
7415 Make_Block_Statement (Loc,
7416 Handled_Statement_Sequence =>
7417 Make_Handled_Sequence_Of_Statements (Loc,
7418 Statements => New_List (Fin_Call),
7419 Exception_Handlers => New_List (
7420 Build_Exception_Handler (Finalizer_Data))));
7421 end if;
7423 Append_To (Stmts, Fin_Call);
7424 end if;
7425 end Process_Component_For_Finalize;
7427 -- Local variables
7429 Alts : List_Id;
7430 Counter_Id : Entity_Id := Empty;
7431 Decl : Node_Id;
7432 Decl_Id : Entity_Id;
7433 Decl_Typ : Entity_Id;
7434 Decls : List_Id;
7435 Has_POC : Boolean;
7436 Jump_Block : Node_Id;
7437 Label : Node_Id;
7438 Label_Id : Entity_Id;
7439 Num_Comps : Nat;
7440 Stmts : List_Id;
7441 Var_Case : Node_Id;
7443 -- Start of processing for Process_Component_List_For_Finalize
7445 begin
7446 -- Perform an initial check, look for controlled and per-object
7447 -- constrained components.
7449 Preprocess_Components (Comps, Num_Comps, Has_POC);
7451 -- Create a state counter to service the current component list.
7452 -- This step is performed before the variants are inspected in
7453 -- order to generate the same state counter names as those from
7454 -- Build_Initialize_Statements.
7456 if Num_Comps > 0 and then Is_Local then
7457 Counter := Counter + 1;
7459 Counter_Id :=
7460 Make_Defining_Identifier (Loc,
7461 Chars => New_External_Name ('C', Counter));
7462 end if;
7464 -- Process the component in the following order:
7465 -- 1) Variants
7466 -- 2) Per-object constrained components
7467 -- 3) Regular components
7469 -- Start with the variant parts
7471 Var_Case := Empty;
7472 if Present (Variant_Part (Comps)) then
7473 declare
7474 Var_Alts : constant List_Id := New_List;
7475 Var : Node_Id;
7477 begin
7478 Var := First_Non_Pragma (Variants (Variant_Part (Comps)));
7479 while Present (Var) loop
7481 -- Generate:
7482 -- when <discrete choices> =>
7483 -- <finalize statements>
7485 Append_To (Var_Alts,
7486 Make_Case_Statement_Alternative (Loc,
7487 Discrete_Choices =>
7488 New_Copy_List (Discrete_Choices (Var)),
7489 Statements =>
7490 Process_Component_List_For_Finalize (
7491 Component_List (Var))));
7493 Next_Non_Pragma (Var);
7494 end loop;
7496 -- Generate:
7497 -- case V.<discriminant> is
7498 -- when <discrete choices 1> =>
7499 -- <finalize statements 1>
7500 -- ...
7501 -- when <discrete choices N> =>
7502 -- <finalize statements N>
7503 -- end case;
7505 Var_Case :=
7506 Make_Case_Statement (Loc,
7507 Expression =>
7508 Make_Selected_Component (Loc,
7509 Prefix => Make_Identifier (Loc, Name_V),
7510 Selector_Name =>
7511 Make_Identifier (Loc,
7512 Chars => Chars (Name (Variant_Part (Comps))))),
7513 Alternatives => Var_Alts);
7514 end;
7515 end if;
7517 -- The current component list does not have a single controlled
7518 -- component, however it may contain variants. Return the case
7519 -- statement for the variants or nothing.
7521 if Num_Comps = 0 then
7522 if Present (Var_Case) then
7523 return New_List (Var_Case);
7524 else
7525 return New_List (Make_Null_Statement (Loc));
7526 end if;
7527 end if;
7529 -- Prepare all lists
7531 Alts := New_List;
7532 Decls := New_List;
7533 Stmts := New_List;
7535 -- Process all per-object constrained components in reverse order
7537 if Has_POC then
7538 Decl := Last_Non_Pragma (Component_Items (Comps));
7539 while Present (Decl) loop
7540 Decl_Id := Defining_Identifier (Decl);
7541 Decl_Typ := Etype (Decl_Id);
7543 -- Skip _parent
7545 if Chars (Decl_Id) /= Name_uParent
7546 and then Needs_Finalization (Decl_Typ)
7547 and then Has_Access_Constraint (Decl_Id)
7548 and then No (Expression (Decl))
7549 then
7550 Process_Component_For_Finalize
7551 (Decl, Alts, Decls, Stmts, Num_Comps);
7552 end if;
7554 Prev_Non_Pragma (Decl);
7555 end loop;
7556 end if;
7558 -- Process the rest of the components in reverse order
7560 Decl := Last_Non_Pragma (Component_Items (Comps));
7561 while Present (Decl) loop
7562 Decl_Id := Defining_Identifier (Decl);
7563 Decl_Typ := Etype (Decl_Id);
7565 -- Skip _parent
7567 if Chars (Decl_Id) /= Name_uParent
7568 and then Needs_Finalization (Decl_Typ)
7569 then
7570 -- Skip per-object constrained components since they were
7571 -- handled in the above step.
7573 if Has_Access_Constraint (Decl_Id)
7574 and then No (Expression (Decl))
7575 then
7576 null;
7577 else
7578 Process_Component_For_Finalize
7579 (Decl, Alts, Decls, Stmts, Num_Comps);
7580 end if;
7581 end if;
7583 Prev_Non_Pragma (Decl);
7584 end loop;
7586 -- Generate:
7587 -- declare
7588 -- LN : label; -- If Is_Local is enabled
7589 -- ... .
7590 -- L0 : label; .
7592 -- begin .
7593 -- case CounterX is .
7594 -- when N => .
7595 -- goto LN; .
7596 -- ... .
7597 -- when 1 => .
7598 -- goto L1; .
7599 -- when others => .
7600 -- goto L0; .
7601 -- end case; .
7603 -- <<LN>> -- If Is_Local is enabled
7604 -- begin
7605 -- [Deep_]Finalize (V.CompY);
7606 -- exception
7607 -- when Id : others =>
7608 -- if not Raised then
7609 -- Raised := True;
7610 -- Save_Occurrence (E,
7611 -- Get_Current_Excep.all.all);
7612 -- end if;
7613 -- end;
7614 -- ...
7615 -- <<L0>> -- If Is_Local is enabled
7616 -- end;
7618 if Is_Local then
7620 -- Add the declaration of default jump location L0, its
7621 -- corresponding alternative and its place in the statements.
7623 Label_Id := Make_Identifier (Loc, New_External_Name ('L', 0));
7624 Set_Entity (Label_Id,
7625 Make_Defining_Identifier (Loc, Chars (Label_Id)));
7626 Label := Make_Label (Loc, Label_Id);
7628 Append_To (Decls, -- declaration
7629 Make_Implicit_Label_Declaration (Loc,
7630 Defining_Identifier => Entity (Label_Id),
7631 Label_Construct => Label));
7633 Append_To (Alts, -- alternative
7634 Make_Case_Statement_Alternative (Loc,
7635 Discrete_Choices => New_List (
7636 Make_Others_Choice (Loc)),
7638 Statements => New_List (
7639 Make_Goto_Statement (Loc,
7640 Name => New_Occurrence_Of (Entity (Label_Id), Loc)))));
7642 Append_To (Stmts, Label); -- statement
7644 -- Create the jump block
7646 Prepend_To (Stmts,
7647 Make_Case_Statement (Loc,
7648 Expression => Make_Identifier (Loc, Chars (Counter_Id)),
7649 Alternatives => Alts));
7650 end if;
7652 Jump_Block :=
7653 Make_Block_Statement (Loc,
7654 Declarations => Decls,
7655 Handled_Statement_Sequence =>
7656 Make_Handled_Sequence_Of_Statements (Loc, Stmts));
7658 if Present (Var_Case) then
7659 return New_List (Var_Case, Jump_Block);
7660 else
7661 return New_List (Jump_Block);
7662 end if;
7663 end Process_Component_List_For_Finalize;
7665 -- Local variables
7667 Bod_Stmts : List_Id := No_List;
7668 Finalizer_Decls : List_Id := No_List;
7669 Rec_Def : Node_Id;
7671 -- Start of processing for Build_Finalize_Statements
7673 begin
7674 Finalizer_Decls := New_List;
7675 Build_Object_Declarations (Finalizer_Data, Finalizer_Decls, Loc);
7677 if Nkind (Typ_Def) = N_Derived_Type_Definition then
7678 Rec_Def := Record_Extension_Part (Typ_Def);
7679 else
7680 Rec_Def := Typ_Def;
7681 end if;
7683 -- Create a finalization sequence for all record components
7685 if Present (Component_List (Rec_Def)) then
7686 Bod_Stmts :=
7687 Process_Component_List_For_Finalize (Component_List (Rec_Def));
7688 end if;
7690 -- A derived record type must finalize all inherited components. This
7691 -- action poses the following problem:
7693 -- procedure Deep_Finalize (Obj : in out Parent_Typ) is
7694 -- begin
7695 -- Finalize (Obj);
7696 -- ...
7698 -- procedure Deep_Finalize (Obj : in out Derived_Typ) is
7699 -- begin
7700 -- Deep_Finalize (Obj._parent);
7701 -- ...
7702 -- Finalize (Obj);
7703 -- ...
7705 -- Finalizing the derived type will invoke Finalize of the parent and
7706 -- then that of the derived type. This is undesirable because both
7707 -- routines may modify shared components. Only the Finalize of the
7708 -- derived type should be invoked.
7710 -- To prevent this double adjustment of shared components,
7711 -- Deep_Finalize uses a flag to control the invocation of Finalize:
7713 -- procedure Deep_Finalize
7714 -- (Obj : in out Some_Type;
7715 -- Flag : Boolean := True)
7716 -- is
7717 -- begin
7718 -- if Flag then
7719 -- Finalize (Obj);
7720 -- end if;
7721 -- ...
7723 -- When Deep_Finalize is invoked for field _parent, a value of False
7724 -- is provided for the flag:
7726 -- Deep_Finalize (Obj._parent, False);
7728 if Is_Tagged_Type (Typ) and then Is_Derived_Type (Typ) then
7729 declare
7730 Par_Typ : constant Entity_Id := Parent_Field_Type (Typ);
7731 Call : Node_Id;
7732 Fin_Stmt : Node_Id;
7734 begin
7735 if Needs_Finalization (Par_Typ) then
7736 Call :=
7737 Make_Final_Call
7738 (Obj_Ref =>
7739 Make_Selected_Component (Loc,
7740 Prefix => Make_Identifier (Loc, Name_V),
7741 Selector_Name =>
7742 Make_Identifier (Loc, Name_uParent)),
7743 Typ => Par_Typ,
7744 Skip_Self => True);
7746 -- Generate:
7747 -- begin
7748 -- Deep_Finalize (V._parent, False);
7750 -- exception
7751 -- when Id : others =>
7752 -- if not Raised then
7753 -- Raised := True;
7754 -- Save_Occurrence (E,
7755 -- Get_Current_Excep.all.all);
7756 -- end if;
7757 -- end;
7759 if Present (Call) then
7760 Fin_Stmt := Call;
7762 if Exceptions_OK then
7763 Fin_Stmt :=
7764 Make_Block_Statement (Loc,
7765 Handled_Statement_Sequence =>
7766 Make_Handled_Sequence_Of_Statements (Loc,
7767 Statements => New_List (Fin_Stmt),
7768 Exception_Handlers => New_List (
7769 Build_Exception_Handler
7770 (Finalizer_Data))));
7771 end if;
7773 Append_To (Bod_Stmts, Fin_Stmt);
7774 end if;
7775 end if;
7776 end;
7777 end if;
7779 -- Finalize the object. This action must be performed first before
7780 -- all components have been finalized.
7782 if Is_Controlled (Typ) and then not Is_Local then
7783 declare
7784 Fin_Stmt : Node_Id;
7785 Proc : Entity_Id;
7787 begin
7788 Proc := Find_Optional_Prim_Op (Typ, Name_Finalize);
7790 -- Generate:
7791 -- if F then
7792 -- begin
7793 -- Finalize (V);
7795 -- exception
7796 -- when others =>
7797 -- if not Raised then
7798 -- Raised := True;
7799 -- Save_Occurrence (E,
7800 -- Get_Current_Excep.all.all);
7801 -- end if;
7802 -- end;
7803 -- end if;
7805 if Present (Proc) then
7806 Fin_Stmt :=
7807 Make_Procedure_Call_Statement (Loc,
7808 Name => New_Occurrence_Of (Proc, Loc),
7809 Parameter_Associations => New_List (
7810 Make_Identifier (Loc, Name_V)));
7812 if Exceptions_OK then
7813 Fin_Stmt :=
7814 Make_Block_Statement (Loc,
7815 Handled_Statement_Sequence =>
7816 Make_Handled_Sequence_Of_Statements (Loc,
7817 Statements => New_List (Fin_Stmt),
7818 Exception_Handlers => New_List (
7819 Build_Exception_Handler
7820 (Finalizer_Data))));
7821 end if;
7823 Prepend_To (Bod_Stmts,
7824 Make_If_Statement (Loc,
7825 Condition => Make_Identifier (Loc, Name_F),
7826 Then_Statements => New_List (Fin_Stmt)));
7827 end if;
7828 end;
7829 end if;
7831 -- At this point either all finalization statements have been
7832 -- generated or the type is not controlled.
7834 if No (Bod_Stmts) then
7835 return New_List (Make_Null_Statement (Loc));
7837 -- Generate:
7838 -- declare
7839 -- Abort : constant Boolean := Triggered_By_Abort;
7840 -- <or>
7841 -- Abort : constant Boolean := False; -- no abort
7843 -- E : Exception_Occurrence;
7844 -- Raised : Boolean := False;
7846 -- begin
7847 -- <finalize statements>
7849 -- if Raised and then not Abort then
7850 -- Raise_From_Controlled_Operation (E);
7851 -- end if;
7852 -- end;
7854 else
7855 if Exceptions_OK then
7856 Append_To (Bod_Stmts, Build_Raise_Statement (Finalizer_Data));
7857 end if;
7859 return
7860 New_List (
7861 Make_Block_Statement (Loc,
7862 Declarations =>
7863 Finalizer_Decls,
7864 Handled_Statement_Sequence =>
7865 Make_Handled_Sequence_Of_Statements (Loc, Bod_Stmts)));
7866 end if;
7867 end Build_Finalize_Statements;
7869 -----------------------
7870 -- Parent_Field_Type --
7871 -----------------------
7873 function Parent_Field_Type (Typ : Entity_Id) return Entity_Id is
7874 Field : Entity_Id;
7876 begin
7877 Field := First_Entity (Typ);
7878 while Present (Field) loop
7879 if Chars (Field) = Name_uParent then
7880 return Etype (Field);
7881 end if;
7883 Next_Entity (Field);
7884 end loop;
7886 -- A derived tagged type should always have a parent field
7888 raise Program_Error;
7889 end Parent_Field_Type;
7891 ---------------------------
7892 -- Preprocess_Components --
7893 ---------------------------
7895 procedure Preprocess_Components
7896 (Comps : Node_Id;
7897 Num_Comps : out Nat;
7898 Has_POC : out Boolean)
7900 Decl : Node_Id;
7901 Id : Entity_Id;
7902 Typ : Entity_Id;
7904 begin
7905 Num_Comps := 0;
7906 Has_POC := False;
7908 Decl := First_Non_Pragma (Component_Items (Comps));
7909 while Present (Decl) loop
7910 Id := Defining_Identifier (Decl);
7911 Typ := Etype (Id);
7913 -- Skip field _parent
7915 if Chars (Id) /= Name_uParent
7916 and then Needs_Finalization (Typ)
7917 then
7918 Num_Comps := Num_Comps + 1;
7920 if Has_Access_Constraint (Id)
7921 and then No (Expression (Decl))
7922 then
7923 Has_POC := True;
7924 end if;
7925 end if;
7927 Next_Non_Pragma (Decl);
7928 end loop;
7929 end Preprocess_Components;
7931 -- Start of processing for Make_Deep_Record_Body
7933 begin
7934 case Prim is
7935 when Address_Case =>
7936 return Make_Finalize_Address_Stmts (Typ);
7938 when Adjust_Case =>
7939 return Build_Adjust_Statements (Typ);
7941 when Finalize_Case =>
7942 return Build_Finalize_Statements (Typ);
7944 when Initialize_Case =>
7945 declare
7946 Loc : constant Source_Ptr := Sloc (Typ);
7948 begin
7949 if Is_Controlled (Typ) then
7950 return New_List (
7951 Make_Procedure_Call_Statement (Loc,
7952 Name =>
7953 New_Occurrence_Of
7954 (Find_Prim_Op (Typ, Name_Of (Prim)), Loc),
7955 Parameter_Associations => New_List (
7956 Make_Identifier (Loc, Name_V))));
7957 else
7958 return Empty_List;
7959 end if;
7960 end;
7961 end case;
7962 end Make_Deep_Record_Body;
7964 ----------------------
7965 -- Make_Final_Call --
7966 ----------------------
7968 function Make_Final_Call
7969 (Obj_Ref : Node_Id;
7970 Typ : Entity_Id;
7971 Skip_Self : Boolean := False) return Node_Id
7973 Loc : constant Source_Ptr := Sloc (Obj_Ref);
7974 Atyp : Entity_Id;
7975 Fin_Id : Entity_Id := Empty;
7976 Ref : Node_Id;
7977 Utyp : Entity_Id;
7979 begin
7980 Ref := Obj_Ref;
7982 -- Recover the proper type which contains [Deep_]Finalize
7984 if Is_Class_Wide_Type (Typ) then
7985 Utyp := Root_Type (Typ);
7986 Atyp := Utyp;
7988 elsif Is_Concurrent_Type (Typ) then
7989 Utyp := Corresponding_Record_Type (Typ);
7990 Atyp := Empty;
7991 Ref := Convert_Concurrent (Ref, Typ);
7993 elsif Is_Private_Type (Typ)
7994 and then Present (Full_View (Typ))
7995 and then Is_Concurrent_Type (Full_View (Typ))
7996 then
7997 Utyp := Corresponding_Record_Type (Full_View (Typ));
7998 Atyp := Typ;
7999 Ref := Convert_Concurrent (Ref, Full_View (Typ));
8001 else
8002 Utyp := Typ;
8003 Atyp := Typ;
8004 end if;
8006 Utyp := Underlying_Type (Base_Type (Utyp));
8007 Set_Assignment_OK (Ref);
8009 -- Deal with untagged derivation of private views. If the parent type
8010 -- is a protected type, Deep_Finalize is found on the corresponding
8011 -- record of the ancestor.
8013 if Is_Untagged_Derivation (Typ) then
8014 if Is_Protected_Type (Typ) then
8015 Utyp := Corresponding_Record_Type (Root_Type (Base_Type (Typ)));
8016 else
8017 Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
8019 if Is_Protected_Type (Utyp) then
8020 Utyp := Corresponding_Record_Type (Utyp);
8021 end if;
8022 end if;
8024 Ref := Unchecked_Convert_To (Utyp, Ref);
8025 Set_Assignment_OK (Ref);
8026 end if;
8028 -- Deal with derived private types which do not inherit primitives from
8029 -- their parents. In this case, [Deep_]Finalize can be found in the full
8030 -- view of the parent type.
8032 if Present (Utyp)
8033 and then Is_Tagged_Type (Utyp)
8034 and then Is_Derived_Type (Utyp)
8035 and then Is_Empty_Elmt_List (Primitive_Operations (Utyp))
8036 and then Is_Private_Type (Etype (Utyp))
8037 and then Present (Full_View (Etype (Utyp)))
8038 then
8039 Utyp := Full_View (Etype (Utyp));
8040 Ref := Unchecked_Convert_To (Utyp, Ref);
8041 Set_Assignment_OK (Ref);
8042 end if;
8044 -- When dealing with the completion of a private type, use the base type
8045 -- instead.
8047 if Present (Utyp) and then Utyp /= Base_Type (Utyp) then
8048 pragma Assert (Present (Atyp) and then Is_Private_Type (Atyp));
8050 Utyp := Base_Type (Utyp);
8051 Ref := Unchecked_Convert_To (Utyp, Ref);
8052 Set_Assignment_OK (Ref);
8053 end if;
8055 -- The underlying type may not be present due to a missing full view. In
8056 -- this case freezing did not take place and there is no [Deep_]Finalize
8057 -- primitive to call.
8059 if No (Utyp) then
8060 return Empty;
8062 elsif Skip_Self then
8063 if Has_Controlled_Component (Utyp) then
8064 if Is_Tagged_Type (Utyp) then
8065 Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize);
8066 else
8067 Fin_Id := TSS (Utyp, TSS_Deep_Finalize);
8068 end if;
8069 end if;
8071 -- Class-wide types, interfaces and types with controlled components
8073 elsif Is_Class_Wide_Type (Typ)
8074 or else Is_Interface (Typ)
8075 or else Has_Controlled_Component (Utyp)
8076 then
8077 if Is_Tagged_Type (Utyp) then
8078 Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize);
8079 else
8080 Fin_Id := TSS (Utyp, TSS_Deep_Finalize);
8081 end if;
8083 -- Derivations from [Limited_]Controlled
8085 elsif Is_Controlled (Utyp) then
8086 if Has_Controlled_Component (Utyp) then
8087 Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize);
8088 else
8089 Fin_Id := Find_Optional_Prim_Op (Utyp, Name_Of (Finalize_Case));
8090 end if;
8092 -- Tagged types
8094 elsif Is_Tagged_Type (Utyp) then
8095 Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize);
8097 else
8098 raise Program_Error;
8099 end if;
8101 if Present (Fin_Id) then
8103 -- When finalizing a class-wide object, do not convert to the root
8104 -- type in order to produce a dispatching call.
8106 if Is_Class_Wide_Type (Typ) then
8107 null;
8109 -- Ensure that a finalization routine is at least decorated in order
8110 -- to inspect the object parameter.
8112 elsif Analyzed (Fin_Id)
8113 or else Ekind (Fin_Id) = E_Procedure
8114 then
8115 -- In certain cases, such as the creation of Stream_Read, the
8116 -- visible entity of the type is its full view. Since Stream_Read
8117 -- will have to create an object of type Typ, the local object
8118 -- will be finalzed by the scope finalizer generated later on. The
8119 -- object parameter of Deep_Finalize will always use the private
8120 -- view of the type. To avoid such a clash between a private and a
8121 -- full view, perform an unchecked conversion of the object
8122 -- reference to the private view.
8124 declare
8125 Formal_Typ : constant Entity_Id :=
8126 Etype (First_Formal (Fin_Id));
8127 begin
8128 if Is_Private_Type (Formal_Typ)
8129 and then Present (Full_View (Formal_Typ))
8130 and then Full_View (Formal_Typ) = Utyp
8131 then
8132 Ref := Unchecked_Convert_To (Formal_Typ, Ref);
8133 end if;
8134 end;
8136 Ref := Convert_View (Fin_Id, Ref);
8137 end if;
8139 return
8140 Make_Call (Loc,
8141 Proc_Id => Fin_Id,
8142 Param => Ref,
8143 Skip_Self => Skip_Self);
8144 else
8145 return Empty;
8146 end if;
8147 end Make_Final_Call;
8149 --------------------------------
8150 -- Make_Finalize_Address_Body --
8151 --------------------------------
8153 procedure Make_Finalize_Address_Body (Typ : Entity_Id) is
8154 Is_Task : constant Boolean :=
8155 Ekind (Typ) = E_Record_Type
8156 and then Is_Concurrent_Record_Type (Typ)
8157 and then Ekind (Corresponding_Concurrent_Type (Typ)) =
8158 E_Task_Type;
8159 Loc : constant Source_Ptr := Sloc (Typ);
8160 Proc_Id : Entity_Id;
8161 Stmts : List_Id;
8163 begin
8164 -- The corresponding records of task types are not controlled by design.
8165 -- For the sake of completeness, create an empty Finalize_Address to be
8166 -- used in task class-wide allocations.
8168 if Is_Task then
8169 null;
8171 -- Nothing to do if the type is not controlled or it already has a
8172 -- TSS entry for Finalize_Address. Skip class-wide subtypes which do not
8173 -- come from source. These are usually generated for completeness and
8174 -- do not need the Finalize_Address primitive.
8176 elsif not Needs_Finalization (Typ)
8177 or else Present (TSS (Typ, TSS_Finalize_Address))
8178 or else
8179 (Is_Class_Wide_Type (Typ)
8180 and then Ekind (Root_Type (Typ)) = E_Record_Subtype
8181 and then not Comes_From_Source (Root_Type (Typ)))
8182 then
8183 return;
8184 end if;
8186 -- Do not generate Finalize_Address routine for CodePeer
8188 if CodePeer_Mode then
8189 return;
8190 end if;
8192 Proc_Id :=
8193 Make_Defining_Identifier (Loc,
8194 Make_TSS_Name (Typ, TSS_Finalize_Address));
8196 -- Generate:
8198 -- procedure <Typ>FD (V : System.Address) is
8199 -- begin
8200 -- null; -- for tasks
8202 -- declare -- for all other types
8203 -- type Pnn is access all Typ;
8204 -- for Pnn'Storage_Size use 0;
8205 -- begin
8206 -- [Deep_]Finalize (Pnn (V).all);
8207 -- end;
8208 -- end TypFD;
8210 if Is_Task then
8211 Stmts := New_List (Make_Null_Statement (Loc));
8212 else
8213 Stmts := Make_Finalize_Address_Stmts (Typ);
8214 end if;
8216 Discard_Node (
8217 Make_Subprogram_Body (Loc,
8218 Specification =>
8219 Make_Procedure_Specification (Loc,
8220 Defining_Unit_Name => Proc_Id,
8222 Parameter_Specifications => New_List (
8223 Make_Parameter_Specification (Loc,
8224 Defining_Identifier =>
8225 Make_Defining_Identifier (Loc, Name_V),
8226 Parameter_Type =>
8227 New_Occurrence_Of (RTE (RE_Address), Loc)))),
8229 Declarations => No_List,
8231 Handled_Statement_Sequence =>
8232 Make_Handled_Sequence_Of_Statements (Loc,
8233 Statements => Stmts)));
8235 Set_TSS (Typ, Proc_Id);
8236 end Make_Finalize_Address_Body;
8238 ---------------------------------
8239 -- Make_Finalize_Address_Stmts --
8240 ---------------------------------
8242 function Make_Finalize_Address_Stmts (Typ : Entity_Id) return List_Id is
8243 Loc : constant Source_Ptr := Sloc (Typ);
8245 Decls : List_Id;
8246 Desig_Typ : Entity_Id;
8247 Fin_Block : Node_Id;
8248 Fin_Call : Node_Id;
8249 Obj_Expr : Node_Id;
8250 Ptr_Typ : Entity_Id;
8252 begin
8253 if Is_Array_Type (Typ) then
8254 if Is_Constrained (First_Subtype (Typ)) then
8255 Desig_Typ := First_Subtype (Typ);
8256 else
8257 Desig_Typ := Base_Type (Typ);
8258 end if;
8260 -- Class-wide types of constrained root types
8262 elsif Is_Class_Wide_Type (Typ)
8263 and then Has_Discriminants (Root_Type (Typ))
8264 and then not
8265 Is_Empty_Elmt_List (Discriminant_Constraint (Root_Type (Typ)))
8266 then
8267 declare
8268 Parent_Typ : Entity_Id;
8270 begin
8271 -- Climb the parent type chain looking for a non-constrained type
8273 Parent_Typ := Root_Type (Typ);
8274 while Parent_Typ /= Etype (Parent_Typ)
8275 and then Has_Discriminants (Parent_Typ)
8276 and then not
8277 Is_Empty_Elmt_List (Discriminant_Constraint (Parent_Typ))
8278 loop
8279 Parent_Typ := Etype (Parent_Typ);
8280 end loop;
8282 -- Handle views created for tagged types with unknown
8283 -- discriminants.
8285 if Is_Underlying_Record_View (Parent_Typ) then
8286 Parent_Typ := Underlying_Record_View (Parent_Typ);
8287 end if;
8289 Desig_Typ := Class_Wide_Type (Underlying_Type (Parent_Typ));
8290 end;
8292 -- General case
8294 else
8295 Desig_Typ := Typ;
8296 end if;
8298 -- Generate:
8299 -- type Ptr_Typ is access all Typ;
8300 -- for Ptr_Typ'Storage_Size use 0;
8302 Ptr_Typ := Make_Temporary (Loc, 'P');
8304 Decls := New_List (
8305 Make_Full_Type_Declaration (Loc,
8306 Defining_Identifier => Ptr_Typ,
8307 Type_Definition =>
8308 Make_Access_To_Object_Definition (Loc,
8309 All_Present => True,
8310 Subtype_Indication => New_Occurrence_Of (Desig_Typ, Loc))),
8312 Make_Attribute_Definition_Clause (Loc,
8313 Name => New_Occurrence_Of (Ptr_Typ, Loc),
8314 Chars => Name_Storage_Size,
8315 Expression => Make_Integer_Literal (Loc, 0)));
8317 Obj_Expr := Make_Identifier (Loc, Name_V);
8319 -- Unconstrained arrays require special processing in order to retrieve
8320 -- the elements. To achieve this, we have to skip the dope vector which
8321 -- lays in front of the elements and then use a thin pointer to perform
8322 -- the address-to-access conversion.
8324 if Is_Array_Type (Typ)
8325 and then not Is_Constrained (First_Subtype (Typ))
8326 then
8327 declare
8328 Dope_Id : Entity_Id;
8330 begin
8331 -- Ensure that Ptr_Typ a thin pointer, generate:
8332 -- for Ptr_Typ'Size use System.Address'Size;
8334 Append_To (Decls,
8335 Make_Attribute_Definition_Clause (Loc,
8336 Name => New_Occurrence_Of (Ptr_Typ, Loc),
8337 Chars => Name_Size,
8338 Expression =>
8339 Make_Integer_Literal (Loc, System_Address_Size)));
8341 -- Generate:
8342 -- Dnn : constant Storage_Offset :=
8343 -- Desig_Typ'Descriptor_Size / Storage_Unit;
8345 Dope_Id := Make_Temporary (Loc, 'D');
8347 Append_To (Decls,
8348 Make_Object_Declaration (Loc,
8349 Defining_Identifier => Dope_Id,
8350 Constant_Present => True,
8351 Object_Definition =>
8352 New_Occurrence_Of (RTE (RE_Storage_Offset), Loc),
8353 Expression =>
8354 Make_Op_Divide (Loc,
8355 Left_Opnd =>
8356 Make_Attribute_Reference (Loc,
8357 Prefix => New_Occurrence_Of (Desig_Typ, Loc),
8358 Attribute_Name => Name_Descriptor_Size),
8359 Right_Opnd =>
8360 Make_Integer_Literal (Loc, System_Storage_Unit))));
8362 -- Shift the address from the start of the dope vector to the
8363 -- start of the elements:
8365 -- V + Dnn
8367 -- Note that this is done through a wrapper routine since RTSfind
8368 -- cannot retrieve operations with string names of the form "+".
8370 Obj_Expr :=
8371 Make_Function_Call (Loc,
8372 Name =>
8373 New_Occurrence_Of (RTE (RE_Add_Offset_To_Address), Loc),
8374 Parameter_Associations => New_List (
8375 Obj_Expr,
8376 New_Occurrence_Of (Dope_Id, Loc)));
8377 end;
8378 end if;
8380 Fin_Call :=
8381 Make_Final_Call (
8382 Obj_Ref =>
8383 Make_Explicit_Dereference (Loc,
8384 Prefix => Unchecked_Convert_To (Ptr_Typ, Obj_Expr)),
8385 Typ => Desig_Typ);
8387 if Present (Fin_Call) then
8388 Fin_Block :=
8389 Make_Block_Statement (Loc,
8390 Declarations => Decls,
8391 Handled_Statement_Sequence =>
8392 Make_Handled_Sequence_Of_Statements (Loc,
8393 Statements => New_List (Fin_Call)));
8395 -- Otherwise previous errors or a missing full view may prevent the
8396 -- proper freezing of the designated type. If this is the case, there
8397 -- is no [Deep_]Finalize primitive to call.
8399 else
8400 Fin_Block := Make_Null_Statement (Loc);
8401 end if;
8403 return New_List (Fin_Block);
8404 end Make_Finalize_Address_Stmts;
8406 -------------------------------------
8407 -- Make_Handler_For_Ctrl_Operation --
8408 -------------------------------------
8410 -- Generate:
8412 -- when E : others =>
8413 -- Raise_From_Controlled_Operation (E);
8415 -- or:
8417 -- when others =>
8418 -- raise Program_Error [finalize raised exception];
8420 -- depending on whether Raise_From_Controlled_Operation is available
8422 function Make_Handler_For_Ctrl_Operation
8423 (Loc : Source_Ptr) return Node_Id
8425 E_Occ : Entity_Id;
8426 -- Choice parameter (for the first case above)
8428 Raise_Node : Node_Id;
8429 -- Procedure call or raise statement
8431 begin
8432 -- Standard run-time: add choice parameter E and pass it to
8433 -- Raise_From_Controlled_Operation so that the original exception
8434 -- name and message can be recorded in the exception message for
8435 -- Program_Error.
8437 if RTE_Available (RE_Raise_From_Controlled_Operation) then
8438 E_Occ := Make_Defining_Identifier (Loc, Name_E);
8439 Raise_Node :=
8440 Make_Procedure_Call_Statement (Loc,
8441 Name =>
8442 New_Occurrence_Of
8443 (RTE (RE_Raise_From_Controlled_Operation), Loc),
8444 Parameter_Associations => New_List (
8445 New_Occurrence_Of (E_Occ, Loc)));
8447 -- Restricted run-time: exception messages are not supported
8449 else
8450 E_Occ := Empty;
8451 Raise_Node :=
8452 Make_Raise_Program_Error (Loc,
8453 Reason => PE_Finalize_Raised_Exception);
8454 end if;
8456 return
8457 Make_Implicit_Exception_Handler (Loc,
8458 Exception_Choices => New_List (Make_Others_Choice (Loc)),
8459 Choice_Parameter => E_Occ,
8460 Statements => New_List (Raise_Node));
8461 end Make_Handler_For_Ctrl_Operation;
8463 --------------------
8464 -- Make_Init_Call --
8465 --------------------
8467 function Make_Init_Call
8468 (Obj_Ref : Node_Id;
8469 Typ : Entity_Id) return Node_Id
8471 Loc : constant Source_Ptr := Sloc (Obj_Ref);
8472 Is_Conc : Boolean;
8473 Proc : Entity_Id;
8474 Ref : Node_Id;
8475 Utyp : Entity_Id;
8477 begin
8478 Ref := Obj_Ref;
8480 -- Deal with the type and object reference. Depending on the context, an
8481 -- object reference may need several conversions.
8483 if Is_Concurrent_Type (Typ) then
8484 Is_Conc := True;
8485 Utyp := Corresponding_Record_Type (Typ);
8486 Ref := Convert_Concurrent (Ref, Typ);
8488 elsif Is_Private_Type (Typ)
8489 and then Present (Full_View (Typ))
8490 and then Is_Concurrent_Type (Underlying_Type (Typ))
8491 then
8492 Is_Conc := True;
8493 Utyp := Corresponding_Record_Type (Underlying_Type (Typ));
8494 Ref := Convert_Concurrent (Ref, Underlying_Type (Typ));
8496 else
8497 Is_Conc := False;
8498 Utyp := Typ;
8499 end if;
8501 Utyp := Underlying_Type (Base_Type (Utyp));
8502 Set_Assignment_OK (Ref);
8504 -- Deal with untagged derivation of private views
8506 if Is_Untagged_Derivation (Typ) and then not Is_Conc then
8507 Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
8508 Ref := Unchecked_Convert_To (Utyp, Ref);
8510 -- The following is to prevent problems with UC see 1.156 RH ???
8512 Set_Assignment_OK (Ref);
8513 end if;
8515 -- If the underlying_type is a subtype, then we are dealing with the
8516 -- completion of a private type. We need to access the base type and
8517 -- generate a conversion to it.
8519 if Present (Utyp) and then Utyp /= Base_Type (Utyp) then
8520 pragma Assert (Is_Private_Type (Typ));
8521 Utyp := Base_Type (Utyp);
8522 Ref := Unchecked_Convert_To (Utyp, Ref);
8523 end if;
8525 -- The underlying type may not be present due to a missing full view.
8526 -- In this case freezing did not take place and there is no suitable
8527 -- [Deep_]Initialize primitive to call.
8529 if No (Utyp) then
8530 return Empty;
8531 end if;
8533 -- Select the appropriate version of initialize
8535 if Has_Controlled_Component (Utyp) then
8536 Proc := TSS (Utyp, Deep_Name_Of (Initialize_Case));
8537 else
8538 Proc := Find_Prim_Op (Utyp, Name_Of (Initialize_Case));
8539 Check_Visibly_Controlled (Initialize_Case, Typ, Proc, Ref);
8540 end if;
8542 -- If initialization procedure for an array of controlled objects is
8543 -- trivial, do not generate a useless call to it.
8545 if (Is_Array_Type (Utyp) and then Is_Trivial_Subprogram (Proc))
8546 or else
8547 (not Comes_From_Source (Proc)
8548 and then Present (Alias (Proc))
8549 and then Is_Trivial_Subprogram (Alias (Proc)))
8550 then
8551 return Make_Null_Statement (Loc);
8552 end if;
8554 -- The object reference may need another conversion depending on the
8555 -- type of the formal and that of the actual.
8557 Ref := Convert_View (Proc, Ref);
8559 -- Generate:
8560 -- [Deep_]Initialize (Ref);
8562 return
8563 Make_Procedure_Call_Statement (Loc,
8564 Name => New_Occurrence_Of (Proc, Loc),
8565 Parameter_Associations => New_List (Ref));
8566 end Make_Init_Call;
8568 ------------------------------
8569 -- Make_Local_Deep_Finalize --
8570 ------------------------------
8572 function Make_Local_Deep_Finalize
8573 (Typ : Entity_Id;
8574 Nam : Entity_Id) return Node_Id
8576 Loc : constant Source_Ptr := Sloc (Typ);
8577 Formals : List_Id;
8579 begin
8580 Formals := New_List (
8582 -- V : in out Typ
8584 Make_Parameter_Specification (Loc,
8585 Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
8586 In_Present => True,
8587 Out_Present => True,
8588 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
8590 -- F : Boolean := True
8592 Make_Parameter_Specification (Loc,
8593 Defining_Identifier => Make_Defining_Identifier (Loc, Name_F),
8594 Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc),
8595 Expression => New_Occurrence_Of (Standard_True, Loc)));
8597 -- Add the necessary number of counters to represent the initialization
8598 -- state of an object.
8600 return
8601 Make_Subprogram_Body (Loc,
8602 Specification =>
8603 Make_Procedure_Specification (Loc,
8604 Defining_Unit_Name => Nam,
8605 Parameter_Specifications => Formals),
8607 Declarations => No_List,
8609 Handled_Statement_Sequence =>
8610 Make_Handled_Sequence_Of_Statements (Loc,
8611 Statements => Make_Deep_Record_Body (Finalize_Case, Typ, True)));
8612 end Make_Local_Deep_Finalize;
8614 ------------------------------------
8615 -- Make_Set_Finalize_Address_Call --
8616 ------------------------------------
8618 function Make_Set_Finalize_Address_Call
8619 (Loc : Source_Ptr;
8620 Ptr_Typ : Entity_Id) return Node_Id
8622 -- It is possible for Ptr_Typ to be a partial view, if the access type
8623 -- is a full view declared in the private part of a nested package, and
8624 -- the finalization actions take place when completing analysis of the
8625 -- enclosing unit. For this reason use Underlying_Type twice below.
8627 Desig_Typ : constant Entity_Id :=
8628 Available_View
8629 (Designated_Type (Underlying_Type (Ptr_Typ)));
8630 Fin_Addr : constant Entity_Id := Finalize_Address (Desig_Typ);
8631 Fin_Mas : constant Entity_Id :=
8632 Finalization_Master (Underlying_Type (Ptr_Typ));
8634 begin
8635 -- Both the finalization master and primitive Finalize_Address must be
8636 -- available.
8638 pragma Assert (Present (Fin_Addr) and Present (Fin_Mas));
8640 -- Generate:
8641 -- Set_Finalize_Address
8642 -- (<Ptr_Typ>FM, <Desig_Typ>FD'Unrestricted_Access);
8644 return
8645 Make_Procedure_Call_Statement (Loc,
8646 Name =>
8647 New_Occurrence_Of (RTE (RE_Set_Finalize_Address), Loc),
8648 Parameter_Associations => New_List (
8649 New_Occurrence_Of (Fin_Mas, Loc),
8651 Make_Attribute_Reference (Loc,
8652 Prefix => New_Occurrence_Of (Fin_Addr, Loc),
8653 Attribute_Name => Name_Unrestricted_Access)));
8654 end Make_Set_Finalize_Address_Call;
8656 --------------------------
8657 -- Make_Transient_Block --
8658 --------------------------
8660 function Make_Transient_Block
8661 (Loc : Source_Ptr;
8662 Action : Node_Id;
8663 Par : Node_Id) return Node_Id
8665 function Manages_Sec_Stack (Id : Entity_Id) return Boolean;
8666 -- Determine whether scoping entity Id manages the secondary stack
8668 -----------------------
8669 -- Manages_Sec_Stack --
8670 -----------------------
8672 function Manages_Sec_Stack (Id : Entity_Id) return Boolean is
8673 begin
8674 case Ekind (Id) is
8676 -- An exception handler with a choice parameter utilizes a dummy
8677 -- block to provide a declarative region. Such a block should not
8678 -- be considered because it never manifests in the tree and can
8679 -- never release the secondary stack.
8681 when E_Block =>
8682 return
8683 Uses_Sec_Stack (Id) and then not Is_Exception_Handler (Id);
8685 when E_Entry
8686 | E_Entry_Family
8687 | E_Function
8688 | E_Procedure
8690 return Uses_Sec_Stack (Id);
8692 when others =>
8693 return False;
8694 end case;
8695 end Manages_Sec_Stack;
8697 -- Local variables
8699 Decls : constant List_Id := New_List;
8700 Instrs : constant List_Id := New_List (Action);
8701 Trans_Id : constant Entity_Id := Current_Scope;
8703 Block : Node_Id;
8704 Insert : Node_Id;
8705 Scop : Entity_Id;
8707 -- Start of processing for Make_Transient_Block
8709 begin
8710 -- Even though the transient block is tasked with managing the secondary
8711 -- stack, the block may forgo this functionality depending on how the
8712 -- secondary stack is managed by enclosing scopes.
8714 if Manages_Sec_Stack (Trans_Id) then
8716 -- Determine whether an enclosing scope already manages the secondary
8717 -- stack.
8719 Scop := Scope (Trans_Id);
8720 while Present (Scop) loop
8722 -- It should not be possible to reach Standard without hitting one
8723 -- of the other cases first unless Standard was manually pushed.
8725 if Scop = Standard_Standard then
8726 exit;
8728 -- The transient block is within a function which returns on the
8729 -- secondary stack. Take a conservative approach and assume that
8730 -- the value on the secondary stack is part of the result. Note
8731 -- that it is not possible to detect this dependency without flow
8732 -- analysis which the compiler does not have. Letting the object
8733 -- live longer than the transient block will not leak any memory
8734 -- because the caller will reclaim the total storage used by the
8735 -- function.
8737 elsif Ekind (Scop) = E_Function
8738 and then Sec_Stack_Needed_For_Return (Scop)
8739 then
8740 Set_Uses_Sec_Stack (Trans_Id, False);
8741 exit;
8743 -- The transient block must manage the secondary stack when the
8744 -- block appears within a loop in order to reclaim the memory at
8745 -- each iteration.
8747 elsif Ekind (Scop) = E_Loop then
8748 exit;
8750 -- The transient block does not need to manage the secondary stack
8751 -- when there is an enclosing construct which already does that.
8752 -- This optimization saves on SS_Mark and SS_Release calls but may
8753 -- allow objects to live a little longer than required.
8755 -- The transient block must manage the secondary stack when switch
8756 -- -gnatd.s (strict management) is in effect.
8758 elsif Manages_Sec_Stack (Scop) and then not Debug_Flag_Dot_S then
8759 Set_Uses_Sec_Stack (Trans_Id, False);
8760 exit;
8762 -- Prevent the search from going too far because transient blocks
8763 -- are bounded by packages and subprogram scopes.
8765 elsif Ekind_In (Scop, E_Entry,
8766 E_Entry_Family,
8767 E_Function,
8768 E_Package,
8769 E_Procedure,
8770 E_Subprogram_Body)
8771 then
8772 exit;
8773 end if;
8775 Scop := Scope (Scop);
8776 end loop;
8777 end if;
8779 -- Create the transient block. Set the parent now since the block itself
8780 -- is not part of the tree. The current scope is the E_Block entity that
8781 -- has been pushed by Establish_Transient_Scope.
8783 pragma Assert (Ekind (Trans_Id) = E_Block);
8785 Block :=
8786 Make_Block_Statement (Loc,
8787 Identifier => New_Occurrence_Of (Trans_Id, Loc),
8788 Declarations => Decls,
8789 Handled_Statement_Sequence =>
8790 Make_Handled_Sequence_Of_Statements (Loc, Statements => Instrs),
8791 Has_Created_Identifier => True);
8792 Set_Parent (Block, Par);
8794 -- Insert actions stuck in the transient scopes as well as all freezing
8795 -- nodes needed by those actions. Do not insert cleanup actions here,
8796 -- they will be transferred to the newly created block.
8798 Insert_Actions_In_Scope_Around
8799 (Action, Clean => False, Manage_SS => False);
8801 Insert := Prev (Action);
8803 if Present (Insert) then
8804 Freeze_All (First_Entity (Trans_Id), Insert);
8805 end if;
8807 -- Transfer cleanup actions to the newly created block
8809 declare
8810 Cleanup_Actions : List_Id
8811 renames Scope_Stack.Table (Scope_Stack.Last).
8812 Actions_To_Be_Wrapped (Cleanup);
8813 begin
8814 Set_Cleanup_Actions (Block, Cleanup_Actions);
8815 Cleanup_Actions := No_List;
8816 end;
8818 -- When the transient scope was established, we pushed the entry for the
8819 -- transient scope onto the scope stack, so that the scope was active
8820 -- for the installation of finalizable entities etc. Now we must remove
8821 -- this entry, since we have constructed a proper block.
8823 Pop_Scope;
8825 return Block;
8826 end Make_Transient_Block;
8828 ------------------------
8829 -- Node_To_Be_Wrapped --
8830 ------------------------
8832 function Node_To_Be_Wrapped return Node_Id is
8833 begin
8834 return Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped;
8835 end Node_To_Be_Wrapped;
8837 ----------------------------
8838 -- Set_Node_To_Be_Wrapped --
8839 ----------------------------
8841 procedure Set_Node_To_Be_Wrapped (N : Node_Id) is
8842 begin
8843 Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped := N;
8844 end Set_Node_To_Be_Wrapped;
8846 ----------------------------
8847 -- Store_Actions_In_Scope --
8848 ----------------------------
8850 procedure Store_Actions_In_Scope (AK : Scope_Action_Kind; L : List_Id) is
8851 SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
8852 Actions : List_Id renames SE.Actions_To_Be_Wrapped (AK);
8854 begin
8855 if No (Actions) then
8856 Actions := L;
8858 if Is_List_Member (SE.Node_To_Be_Wrapped) then
8859 Set_Parent (L, Parent (SE.Node_To_Be_Wrapped));
8860 else
8861 Set_Parent (L, SE.Node_To_Be_Wrapped);
8862 end if;
8864 Analyze_List (L);
8866 elsif AK = Before then
8867 Insert_List_After_And_Analyze (Last (Actions), L);
8869 else
8870 Insert_List_Before_And_Analyze (First (Actions), L);
8871 end if;
8872 end Store_Actions_In_Scope;
8874 ----------------------------------
8875 -- Store_After_Actions_In_Scope --
8876 ----------------------------------
8878 procedure Store_After_Actions_In_Scope (L : List_Id) is
8879 begin
8880 Store_Actions_In_Scope (After, L);
8881 end Store_After_Actions_In_Scope;
8883 -----------------------------------
8884 -- Store_Before_Actions_In_Scope --
8885 -----------------------------------
8887 procedure Store_Before_Actions_In_Scope (L : List_Id) is
8888 begin
8889 Store_Actions_In_Scope (Before, L);
8890 end Store_Before_Actions_In_Scope;
8892 -----------------------------------
8893 -- Store_Cleanup_Actions_In_Scope --
8894 -----------------------------------
8896 procedure Store_Cleanup_Actions_In_Scope (L : List_Id) is
8897 begin
8898 Store_Actions_In_Scope (Cleanup, L);
8899 end Store_Cleanup_Actions_In_Scope;
8901 --------------------------------
8902 -- Wrap_Transient_Declaration --
8903 --------------------------------
8905 -- If a transient scope has been established during the processing of the
8906 -- Expression of an Object_Declaration, it is not possible to wrap the
8907 -- declaration into a transient block as usual case, otherwise the object
8908 -- would be itself declared in the wrong scope. Therefore, all entities (if
8909 -- any) defined in the transient block are moved to the proper enclosing
8910 -- scope. Furthermore, if they are controlled variables they are finalized
8911 -- right after the declaration. The finalization list of the transient
8912 -- scope is defined as a renaming of the enclosing one so during their
8913 -- initialization they will be attached to the proper finalization list.
8914 -- For instance, the following declaration :
8916 -- X : Typ := F (G (A), G (B));
8918 -- (where G(A) and G(B) return controlled values, expanded as _v1 and _v2)
8919 -- is expanded into :
8921 -- X : Typ := [ complex Expression-Action ];
8922 -- [Deep_]Finalize (_v1);
8923 -- [Deep_]Finalize (_v2);
8925 procedure Wrap_Transient_Declaration (N : Node_Id) is
8926 Curr_S : Entity_Id;
8927 Encl_S : Entity_Id;
8929 begin
8930 Curr_S := Current_Scope;
8931 Encl_S := Scope (Curr_S);
8933 -- Insert all actions including cleanup generated while analyzing or
8934 -- expanding the transient context back into the tree. Manage the
8935 -- secondary stack when the object declaration appears in a library
8936 -- level package [body].
8938 Insert_Actions_In_Scope_Around
8939 (N => N,
8940 Clean => True,
8941 Manage_SS =>
8942 Uses_Sec_Stack (Curr_S)
8943 and then Nkind (N) = N_Object_Declaration
8944 and then Ekind_In (Encl_S, E_Package, E_Package_Body)
8945 and then Is_Library_Level_Entity (Encl_S));
8946 Pop_Scope;
8948 -- Relocate local entities declared within the transient scope to the
8949 -- enclosing scope. This action sets their Is_Public flag accordingly.
8951 Transfer_Entities (Curr_S, Encl_S);
8953 -- Mark the enclosing dynamic scope to ensure that the secondary stack
8954 -- is properly released upon exiting the said scope.
8956 if Uses_Sec_Stack (Curr_S) then
8957 Curr_S := Enclosing_Dynamic_Scope (Curr_S);
8959 -- Do not mark a function that returns on the secondary stack as the
8960 -- reclamation is done by the caller.
8962 if Ekind (Curr_S) = E_Function
8963 and then Requires_Transient_Scope (Etype (Curr_S))
8964 then
8965 null;
8967 -- Otherwise mark the enclosing dynamic scope
8969 else
8970 Set_Uses_Sec_Stack (Curr_S);
8971 Check_Restriction (No_Secondary_Stack, N);
8972 end if;
8973 end if;
8974 end Wrap_Transient_Declaration;
8976 -------------------------------
8977 -- Wrap_Transient_Expression --
8978 -------------------------------
8980 procedure Wrap_Transient_Expression (N : Node_Id) is
8981 Loc : constant Source_Ptr := Sloc (N);
8982 Expr : Node_Id := Relocate_Node (N);
8983 Temp : constant Entity_Id := Make_Temporary (Loc, 'E', N);
8984 Typ : constant Entity_Id := Etype (N);
8986 begin
8987 -- Generate:
8989 -- Temp : Typ;
8990 -- declare
8991 -- M : constant Mark_Id := SS_Mark;
8992 -- procedure Finalizer is ... (See Build_Finalizer)
8994 -- begin
8995 -- Temp := <Expr>; -- general case
8996 -- Temp := (if <Expr> then True else False); -- boolean case
8998 -- at end
8999 -- Finalizer;
9000 -- end;
9002 -- A special case is made for Boolean expressions so that the back end
9003 -- knows to generate a conditional branch instruction, if running with
9004 -- -fpreserve-control-flow. This ensures that a control-flow change
9005 -- signaling the decision outcome occurs before the cleanup actions.
9007 if Opt.Suppress_Control_Flow_Optimizations
9008 and then Is_Boolean_Type (Typ)
9009 then
9010 Expr :=
9011 Make_If_Expression (Loc,
9012 Expressions => New_List (
9013 Expr,
9014 New_Occurrence_Of (Standard_True, Loc),
9015 New_Occurrence_Of (Standard_False, Loc)));
9016 end if;
9018 Insert_Actions (N, New_List (
9019 Make_Object_Declaration (Loc,
9020 Defining_Identifier => Temp,
9021 Object_Definition => New_Occurrence_Of (Typ, Loc)),
9023 Make_Transient_Block (Loc,
9024 Action =>
9025 Make_Assignment_Statement (Loc,
9026 Name => New_Occurrence_Of (Temp, Loc),
9027 Expression => Expr),
9028 Par => Parent (N))));
9030 Rewrite (N, New_Occurrence_Of (Temp, Loc));
9031 Analyze_And_Resolve (N, Typ);
9032 end Wrap_Transient_Expression;
9034 ------------------------------
9035 -- Wrap_Transient_Statement --
9036 ------------------------------
9038 procedure Wrap_Transient_Statement (N : Node_Id) is
9039 Loc : constant Source_Ptr := Sloc (N);
9040 New_Stmt : constant Node_Id := Relocate_Node (N);
9042 begin
9043 -- Generate:
9044 -- declare
9045 -- M : constant Mark_Id := SS_Mark;
9046 -- procedure Finalizer is ... (See Build_Finalizer)
9048 -- begin
9049 -- <New_Stmt>;
9051 -- at end
9052 -- Finalizer;
9053 -- end;
9055 Rewrite (N,
9056 Make_Transient_Block (Loc,
9057 Action => New_Stmt,
9058 Par => Parent (N)));
9060 -- With the scope stack back to normal, we can call analyze on the
9061 -- resulting block. At this point, the transient scope is being
9062 -- treated like a perfectly normal scope, so there is nothing
9063 -- special about it.
9065 -- Note: Wrap_Transient_Statement is called with the node already
9066 -- analyzed (i.e. Analyzed (N) is True). This is important, since
9067 -- otherwise we would get a recursive processing of the node when
9068 -- we do this Analyze call.
9070 Analyze (N);
9071 end Wrap_Transient_Statement;
9073 end Exp_Ch7;