OSDN Git Service

2007-08-16 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_util.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             E X P _ U T I L                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2007, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Debug;    use Debug;
30 with Einfo;    use Einfo;
31 with Elists;   use Elists;
32 with Errout;   use Errout;
33 with Exp_Aggr; use Exp_Aggr;
34 with Exp_Ch6;  use Exp_Ch6;
35 with Exp_Ch7;  use Exp_Ch7;
36 with Inline;   use Inline;
37 with Itypes;   use Itypes;
38 with Lib;      use Lib;
39 with Nlists;   use Nlists;
40 with Nmake;    use Nmake;
41 with Opt;      use Opt;
42 with Restrict; use Restrict;
43 with Rident;   use Rident;
44 with Sem;      use Sem;
45 with Sem_Ch8;  use Sem_Ch8;
46 with Sem_Eval; use Sem_Eval;
47 with Sem_Res;  use Sem_Res;
48 with Sem_Type; use Sem_Type;
49 with Sem_Util; use Sem_Util;
50 with Snames;   use Snames;
51 with Stand;    use Stand;
52 with Stringt;  use Stringt;
53 with Targparm; use Targparm;
54 with Tbuild;   use Tbuild;
55 with Ttypes;   use Ttypes;
56 with Uintp;    use Uintp;
57 with Urealp;   use Urealp;
58 with Validsw;  use Validsw;
59
60 package body Exp_Util is
61
62    -----------------------
63    -- Local Subprograms --
64    -----------------------
65
66    function Build_Task_Array_Image
67      (Loc    : Source_Ptr;
68       Id_Ref : Node_Id;
69       A_Type : Entity_Id;
70       Dyn    : Boolean := False) return Node_Id;
71    --  Build function to generate the image string for a task that is an
72    --  array component, concatenating the images of each index. To avoid
73    --  storage leaks, the string is built with successive slice assignments.
74    --  The flag Dyn indicates whether this is called for the initialization
75    --  procedure of an array of tasks, or for the name of a dynamically
76    --  created task that is assigned to an indexed component.
77
78    function Build_Task_Image_Function
79      (Loc   : Source_Ptr;
80       Decls : List_Id;
81       Stats : List_Id;
82       Res   : Entity_Id) return Node_Id;
83    --  Common processing for Task_Array_Image and Task_Record_Image.
84    --  Build function body that computes image.
85
86    procedure Build_Task_Image_Prefix
87       (Loc    : Source_Ptr;
88        Len    : out Entity_Id;
89        Res    : out Entity_Id;
90        Pos    : out Entity_Id;
91        Prefix : Entity_Id;
92        Sum    : Node_Id;
93        Decls  : List_Id;
94        Stats  : List_Id);
95    --  Common processing for Task_Array_Image and Task_Record_Image.
96    --  Create local variables and assign prefix of name to result string.
97
98    function Build_Task_Record_Image
99      (Loc    : Source_Ptr;
100       Id_Ref : Node_Id;
101       Dyn    : Boolean := False) return Node_Id;
102    --  Build function to generate the image string for a task that is a
103    --  record component. Concatenate name of variable with that of selector.
104    --  The flag Dyn indicates whether this is called for the initialization
105    --  procedure of record with task components, or for a dynamically
106    --  created task that is assigned to a selected component.
107
108    function Make_CW_Equivalent_Type
109      (T : Entity_Id;
110       E : Node_Id) return Entity_Id;
111    --  T is a class-wide type entity, E is the initial expression node that
112    --  constrains T in case such as: " X: T := E" or "new T'(E)"
113    --  This function returns the entity of the Equivalent type and inserts
114    --  on the fly the necessary declaration such as:
115    --
116    --    type anon is record
117    --       _parent : Root_Type (T); constrained with E discriminants (if any)
118    --       Extension : String (1 .. expr to match size of E);
119    --    end record;
120    --
121    --  This record is compatible with any object of the class of T thanks
122    --  to the first field and has the same size as E thanks to the second.
123
124    function Make_Literal_Range
125      (Loc         : Source_Ptr;
126       Literal_Typ : Entity_Id) return Node_Id;
127    --  Produce a Range node whose bounds are:
128    --    Low_Bound (Literal_Type) ..
129    --        Low_Bound (Literal_Type) + (Length (Literal_Typ) - 1)
130    --  this is used for expanding declarations like X : String := "sdfgdfg";
131    --
132    --  If the index type of the target array is not integer, we generate:
133    --     Low_Bound (Literal_Type) ..
134    --        Literal_Type'Val
135    --          (Literal_Type'Pos (Low_Bound (Literal_Type))
136    --             + (Length (Literal_Typ) -1))
137
138    function New_Class_Wide_Subtype
139      (CW_Typ : Entity_Id;
140       N      : Node_Id) return Entity_Id;
141    --  Create an implicit subtype of CW_Typ attached to node N
142
143    ----------------------
144    -- Adjust_Condition --
145    ----------------------
146
147    procedure Adjust_Condition (N : Node_Id) is
148    begin
149       if No (N) then
150          return;
151       end if;
152
153       declare
154          Loc : constant Source_Ptr := Sloc (N);
155          T   : constant Entity_Id  := Etype (N);
156          Ti  : Entity_Id;
157
158       begin
159          --  For now, we simply ignore a call where the argument has no
160          --  type (probably case of unanalyzed condition), or has a type
161          --  that is not Boolean. This is because this is a pretty marginal
162          --  piece of functionality, and violations of these rules are
163          --  likely to be truly marginal (how much code uses Fortran Logical
164          --  as the barrier to a protected entry?) and we do not want to
165          --  blow up existing programs. We can change this to an assertion
166          --  after 3.12a is released ???
167
168          if No (T) or else not Is_Boolean_Type (T) then
169             return;
170          end if;
171
172          --  Apply validity checking if needed
173
174          if Validity_Checks_On and Validity_Check_Tests then
175             Ensure_Valid (N);
176          end if;
177
178          --  Immediate return if standard boolean, the most common case,
179          --  where nothing needs to be done.
180
181          if Base_Type (T) = Standard_Boolean then
182             return;
183          end if;
184
185          --  Case of zero/non-zero semantics or non-standard enumeration
186          --  representation. In each case, we rewrite the node as:
187
188          --      ityp!(N) /= False'Enum_Rep
189
190          --  where ityp is an integer type with large enough size to hold
191          --  any value of type T.
192
193          if Nonzero_Is_True (T) or else Has_Non_Standard_Rep (T) then
194             if Esize (T) <= Esize (Standard_Integer) then
195                Ti := Standard_Integer;
196             else
197                Ti := Standard_Long_Long_Integer;
198             end if;
199
200             Rewrite (N,
201               Make_Op_Ne (Loc,
202                 Left_Opnd  => Unchecked_Convert_To (Ti, N),
203                 Right_Opnd =>
204                   Make_Attribute_Reference (Loc,
205                     Attribute_Name => Name_Enum_Rep,
206                     Prefix         =>
207                       New_Occurrence_Of (First_Literal (T), Loc))));
208             Analyze_And_Resolve (N, Standard_Boolean);
209
210          else
211             Rewrite (N, Convert_To (Standard_Boolean, N));
212             Analyze_And_Resolve (N, Standard_Boolean);
213          end if;
214       end;
215    end Adjust_Condition;
216
217    ------------------------
218    -- Adjust_Result_Type --
219    ------------------------
220
221    procedure Adjust_Result_Type (N : Node_Id; T : Entity_Id) is
222    begin
223       --  Ignore call if current type is not Standard.Boolean
224
225       if Etype (N) /= Standard_Boolean then
226          return;
227       end if;
228
229       --  If result is already of correct type, nothing to do. Note that
230       --  this will get the most common case where everything has a type
231       --  of Standard.Boolean.
232
233       if Base_Type (T) = Standard_Boolean then
234          return;
235
236       else
237          declare
238             KP : constant Node_Kind := Nkind (Parent (N));
239
240          begin
241             --  If result is to be used as a Condition in the syntax, no need
242             --  to convert it back, since if it was changed to Standard.Boolean
243             --  using Adjust_Condition, that is just fine for this usage.
244
245             if KP in N_Raise_xxx_Error or else KP in N_Has_Condition then
246                return;
247
248             --  If result is an operand of another logical operation, no need
249             --  to reset its type, since Standard.Boolean is just fine, and
250             --  such operations always do Adjust_Condition on their operands.
251
252             elsif KP in N_Op_Boolean
253               or else KP = N_And_Then
254               or else KP = N_Or_Else
255               or else KP = N_Op_Not
256             then
257                return;
258
259             --  Otherwise we perform a conversion from the current type,
260             --  which must be Standard.Boolean, to the desired type.
261
262             else
263                Set_Analyzed (N);
264                Rewrite (N, Convert_To (T, N));
265                Analyze_And_Resolve (N, T);
266             end if;
267          end;
268       end if;
269    end Adjust_Result_Type;
270
271    --------------------------
272    -- Append_Freeze_Action --
273    --------------------------
274
275    procedure Append_Freeze_Action (T : Entity_Id; N : Node_Id) is
276       Fnode : Node_Id;
277
278    begin
279       Ensure_Freeze_Node (T);
280       Fnode := Freeze_Node (T);
281
282       if No (Actions (Fnode)) then
283          Set_Actions (Fnode, New_List);
284       end if;
285
286       Append (N, Actions (Fnode));
287    end Append_Freeze_Action;
288
289    ---------------------------
290    -- Append_Freeze_Actions --
291    ---------------------------
292
293    procedure Append_Freeze_Actions (T : Entity_Id; L : List_Id) is
294       Fnode : constant Node_Id := Freeze_Node (T);
295
296    begin
297       if No (L) then
298          return;
299
300       else
301          if No (Actions (Fnode)) then
302             Set_Actions (Fnode, L);
303
304          else
305             Append_List (L, Actions (Fnode));
306          end if;
307
308       end if;
309    end Append_Freeze_Actions;
310
311    ------------------------
312    -- Build_Runtime_Call --
313    ------------------------
314
315    function Build_Runtime_Call (Loc : Source_Ptr; RE : RE_Id) return Node_Id is
316    begin
317       --  If entity is not available, we can skip making the call (this avoids
318       --  junk duplicated error messages in a number of cases).
319
320       if not RTE_Available (RE) then
321          return Make_Null_Statement (Loc);
322       else
323          return
324            Make_Procedure_Call_Statement (Loc,
325              Name => New_Reference_To (RTE (RE), Loc));
326       end if;
327    end Build_Runtime_Call;
328
329    ----------------------------
330    -- Build_Task_Array_Image --
331    ----------------------------
332
333    --  This function generates the body for a function that constructs the
334    --  image string for a task that is an array component. The function is
335    --  local to the init proc for the array type, and is called for each one
336    --  of the components. The constructed image has the form of an indexed
337    --  component, whose prefix is the outer variable of the array type.
338    --  The n-dimensional array type has known indices Index, Index2...
339    --  Id_Ref is an indexed component form created by the enclosing init proc.
340    --  Its successive indices are Val1, Val2,.. which are the loop variables
341    --  in the loops that call the individual task init proc on each component.
342
343    --  The generated function has the following structure:
344
345    --  function F return String is
346    --     Pref : string renames Task_Name;
347    --     T1   : String := Index1'Image (Val1);
348    --     ...
349    --     Tn   : String := indexn'image (Valn);
350    --     Len  : Integer := T1'Length + ... + Tn'Length + n + 1;
351    --     --  Len includes commas and the end parentheses.
352    --     Res  : String (1..Len);
353    --     Pos  : Integer := Pref'Length;
354    --
355    --  begin
356    --     Res (1 .. Pos) := Pref;
357    --     Pos := Pos + 1;
358    --     Res (Pos)    := '(';
359    --     Pos := Pos + 1;
360    --     Res (Pos .. Pos + T1'Length - 1) := T1;
361    --     Pos := Pos + T1'Length;
362    --     Res (Pos) := '.';
363    --     Pos := Pos + 1;
364    --     ...
365    --     Res (Pos .. Pos + Tn'Length - 1) := Tn;
366    --     Res (Len) := ')';
367    --
368    --     return Res;
369    --  end F;
370    --
371    --  Needless to say, multidimensional arrays of tasks are rare enough
372    --  that the bulkiness of this code is not really a concern.
373
374    function Build_Task_Array_Image
375      (Loc    : Source_Ptr;
376       Id_Ref : Node_Id;
377       A_Type : Entity_Id;
378       Dyn    : Boolean := False) return Node_Id
379    is
380       Dims : constant Nat := Number_Dimensions (A_Type);
381       --  Number of dimensions for array of tasks
382
383       Temps : array (1 .. Dims) of Entity_Id;
384       --  Array of temporaries to hold string for each index
385
386       Indx : Node_Id;
387       --  Index expression
388
389       Len : Entity_Id;
390       --  Total length of generated name
391
392       Pos : Entity_Id;
393       --  Running index for substring assignments
394
395       Pref : Entity_Id;
396       --  Name of enclosing variable, prefix of resulting name
397
398       Res : Entity_Id;
399       --  String to hold result
400
401       Val : Node_Id;
402       --  Value of successive indices
403
404       Sum : Node_Id;
405       --  Expression to compute total size of string
406
407       T : Entity_Id;
408       --  Entity for name at one index position
409
410       Decls : constant List_Id := New_List;
411       Stats : constant List_Id := New_List;
412
413    begin
414       Pref := Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
415
416       --  For a dynamic task, the name comes from the target variable.
417       --  For a static one it is a formal of the enclosing init proc.
418
419       if Dyn then
420          Get_Name_String (Chars (Entity (Prefix (Id_Ref))));
421          Append_To (Decls,
422            Make_Object_Declaration (Loc,
423              Defining_Identifier => Pref,
424              Object_Definition => New_Occurrence_Of (Standard_String, Loc),
425              Expression =>
426                Make_String_Literal (Loc,
427                  Strval => String_From_Name_Buffer)));
428
429       else
430          Append_To (Decls,
431            Make_Object_Renaming_Declaration (Loc,
432              Defining_Identifier => Pref,
433              Subtype_Mark        => New_Occurrence_Of (Standard_String, Loc),
434              Name                => Make_Identifier (Loc, Name_uTask_Name)));
435       end if;
436
437       Indx := First_Index (A_Type);
438       Val  := First (Expressions (Id_Ref));
439
440       for J in 1 .. Dims loop
441          T := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
442          Temps (J) := T;
443
444          Append_To (Decls,
445             Make_Object_Declaration (Loc,
446                Defining_Identifier => T,
447                Object_Definition => New_Occurrence_Of (Standard_String, Loc),
448                Expression =>
449                  Make_Attribute_Reference (Loc,
450                    Attribute_Name => Name_Image,
451                    Prefix =>
452                      New_Occurrence_Of (Etype (Indx), Loc),
453                    Expressions => New_List (
454                      New_Copy_Tree (Val)))));
455
456          Next_Index (Indx);
457          Next (Val);
458       end loop;
459
460       Sum := Make_Integer_Literal (Loc, Dims + 1);
461
462       Sum :=
463         Make_Op_Add (Loc,
464           Left_Opnd => Sum,
465           Right_Opnd =>
466            Make_Attribute_Reference (Loc,
467              Attribute_Name => Name_Length,
468              Prefix =>
469                New_Occurrence_Of (Pref, Loc),
470              Expressions => New_List (Make_Integer_Literal (Loc, 1))));
471
472       for J in 1 .. Dims loop
473          Sum :=
474             Make_Op_Add (Loc,
475              Left_Opnd => Sum,
476              Right_Opnd =>
477               Make_Attribute_Reference (Loc,
478                 Attribute_Name => Name_Length,
479                 Prefix =>
480                   New_Occurrence_Of (Temps (J), Loc),
481                 Expressions => New_List (Make_Integer_Literal (Loc, 1))));
482       end loop;
483
484       Build_Task_Image_Prefix (Loc, Len, Res, Pos, Pref, Sum, Decls, Stats);
485
486       Set_Character_Literal_Name (Char_Code (Character'Pos ('(')));
487
488       Append_To (Stats,
489          Make_Assignment_Statement (Loc,
490            Name => Make_Indexed_Component (Loc,
491               Prefix => New_Occurrence_Of (Res, Loc),
492               Expressions => New_List (New_Occurrence_Of (Pos, Loc))),
493            Expression =>
494              Make_Character_Literal (Loc,
495                Chars => Name_Find,
496                Char_Literal_Value =>
497                  UI_From_Int (Character'Pos ('(')))));
498
499       Append_To (Stats,
500          Make_Assignment_Statement (Loc,
501             Name => New_Occurrence_Of (Pos, Loc),
502             Expression =>
503               Make_Op_Add (Loc,
504                 Left_Opnd => New_Occurrence_Of (Pos, Loc),
505                 Right_Opnd => Make_Integer_Literal (Loc, 1))));
506
507       for J in 1 .. Dims loop
508
509          Append_To (Stats,
510             Make_Assignment_Statement (Loc,
511               Name => Make_Slice (Loc,
512                  Prefix => New_Occurrence_Of (Res, Loc),
513                  Discrete_Range  =>
514                    Make_Range (Loc,
515                       Low_Bound => New_Occurrence_Of  (Pos, Loc),
516                       High_Bound => Make_Op_Subtract (Loc,
517                         Left_Opnd =>
518                           Make_Op_Add (Loc,
519                             Left_Opnd => New_Occurrence_Of (Pos, Loc),
520                             Right_Opnd =>
521                               Make_Attribute_Reference (Loc,
522                                 Attribute_Name => Name_Length,
523                                 Prefix =>
524                                   New_Occurrence_Of (Temps (J), Loc),
525                                 Expressions =>
526                                   New_List (Make_Integer_Literal (Loc, 1)))),
527                          Right_Opnd => Make_Integer_Literal (Loc, 1)))),
528
529               Expression => New_Occurrence_Of (Temps (J), Loc)));
530
531          if J < Dims then
532             Append_To (Stats,
533                Make_Assignment_Statement (Loc,
534                   Name => New_Occurrence_Of (Pos, Loc),
535                   Expression =>
536                     Make_Op_Add (Loc,
537                       Left_Opnd => New_Occurrence_Of (Pos, Loc),
538                       Right_Opnd =>
539                         Make_Attribute_Reference (Loc,
540                           Attribute_Name => Name_Length,
541                             Prefix => New_Occurrence_Of (Temps (J), Loc),
542                             Expressions =>
543                               New_List (Make_Integer_Literal (Loc, 1))))));
544
545             Set_Character_Literal_Name (Char_Code (Character'Pos (',')));
546
547             Append_To (Stats,
548                Make_Assignment_Statement (Loc,
549                  Name => Make_Indexed_Component (Loc,
550                     Prefix => New_Occurrence_Of (Res, Loc),
551                     Expressions => New_List (New_Occurrence_Of (Pos, Loc))),
552                  Expression =>
553                    Make_Character_Literal (Loc,
554                      Chars => Name_Find,
555                      Char_Literal_Value =>
556                        UI_From_Int (Character'Pos (',')))));
557
558             Append_To (Stats,
559               Make_Assignment_Statement (Loc,
560                 Name => New_Occurrence_Of (Pos, Loc),
561                   Expression =>
562                     Make_Op_Add (Loc,
563                       Left_Opnd => New_Occurrence_Of (Pos, Loc),
564                       Right_Opnd => Make_Integer_Literal (Loc, 1))));
565          end if;
566       end loop;
567
568       Set_Character_Literal_Name (Char_Code (Character'Pos (')')));
569
570       Append_To (Stats,
571          Make_Assignment_Statement (Loc,
572            Name => Make_Indexed_Component (Loc,
573               Prefix => New_Occurrence_Of (Res, Loc),
574               Expressions => New_List (New_Occurrence_Of (Len, Loc))),
575            Expression =>
576              Make_Character_Literal (Loc,
577                Chars => Name_Find,
578                Char_Literal_Value =>
579                  UI_From_Int (Character'Pos (')')))));
580       return Build_Task_Image_Function (Loc, Decls, Stats, Res);
581    end Build_Task_Array_Image;
582
583    ----------------------------
584    -- Build_Task_Image_Decls --
585    ----------------------------
586
587    function Build_Task_Image_Decls
588      (Loc          : Source_Ptr;
589       Id_Ref       : Node_Id;
590       A_Type       : Entity_Id;
591       In_Init_Proc : Boolean := False) return List_Id
592    is
593       Decls  : constant List_Id   := New_List;
594       T_Id   : Entity_Id := Empty;
595       Decl   : Node_Id;
596       Expr   : Node_Id   := Empty;
597       Fun    : Node_Id   := Empty;
598       Is_Dyn : constant Boolean :=
599                  Nkind (Parent (Id_Ref)) = N_Assignment_Statement
600                    and then
601                  Nkind (Expression (Parent (Id_Ref))) = N_Allocator;
602
603    begin
604       --  If Discard_Names or No_Implicit_Heap_Allocations are in effect,
605       --  generate a dummy declaration only.
606
607       if Restriction_Active (No_Implicit_Heap_Allocations)
608         or else Global_Discard_Names
609       then
610          T_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('J'));
611          Name_Len := 0;
612
613          return
614            New_List (
615              Make_Object_Declaration (Loc,
616                Defining_Identifier => T_Id,
617                Object_Definition => New_Occurrence_Of (Standard_String, Loc),
618                Expression =>
619                  Make_String_Literal (Loc,
620                    Strval => String_From_Name_Buffer)));
621
622       else
623          if Nkind (Id_Ref) = N_Identifier
624            or else Nkind (Id_Ref) = N_Defining_Identifier
625          then
626             --  For a simple variable, the image of the task is built from
627             --  the name of the variable. To avoid possible conflict with
628             --  the anonymous type created for a single protected object,
629             --  add a numeric suffix.
630
631             T_Id :=
632               Make_Defining_Identifier (Loc,
633                 New_External_Name (Chars (Id_Ref), 'T', 1));
634
635             Get_Name_String (Chars (Id_Ref));
636
637             Expr :=
638               Make_String_Literal (Loc,
639                 Strval => String_From_Name_Buffer);
640
641          elsif Nkind (Id_Ref) = N_Selected_Component then
642             T_Id :=
643               Make_Defining_Identifier (Loc,
644                 New_External_Name (Chars (Selector_Name (Id_Ref)), 'T'));
645             Fun := Build_Task_Record_Image (Loc, Id_Ref, Is_Dyn);
646
647          elsif Nkind (Id_Ref) = N_Indexed_Component then
648             T_Id :=
649               Make_Defining_Identifier (Loc,
650                 New_External_Name (Chars (A_Type), 'N'));
651
652             Fun := Build_Task_Array_Image (Loc, Id_Ref, A_Type, Is_Dyn);
653          end if;
654       end if;
655
656       if Present (Fun) then
657          Append (Fun, Decls);
658          Expr := Make_Function_Call (Loc,
659            Name => New_Occurrence_Of (Defining_Entity (Fun), Loc));
660
661          if not In_Init_Proc and then VM_Target = No_VM then
662             Set_Uses_Sec_Stack (Defining_Entity (Fun));
663          end if;
664       end if;
665
666       Decl := Make_Object_Declaration (Loc,
667         Defining_Identifier => T_Id,
668         Object_Definition   => New_Occurrence_Of (Standard_String, Loc),
669         Constant_Present    => True,
670         Expression          => Expr);
671
672       Append (Decl, Decls);
673       return Decls;
674    end Build_Task_Image_Decls;
675
676    -------------------------------
677    -- Build_Task_Image_Function --
678    -------------------------------
679
680    function Build_Task_Image_Function
681      (Loc   : Source_Ptr;
682       Decls : List_Id;
683       Stats : List_Id;
684       Res   : Entity_Id) return Node_Id
685    is
686       Spec : Node_Id;
687
688    begin
689       Append_To (Stats,
690         Make_Simple_Return_Statement (Loc,
691           Expression => New_Occurrence_Of (Res, Loc)));
692
693       Spec := Make_Function_Specification (Loc,
694         Defining_Unit_Name =>
695           Make_Defining_Identifier (Loc, New_Internal_Name ('F')),
696         Result_Definition => New_Occurrence_Of (Standard_String, Loc));
697
698       --  Calls to 'Image use the secondary stack, which must be cleaned
699       --  up after the task name is built.
700
701       return Make_Subprogram_Body (Loc,
702          Specification => Spec,
703          Declarations => Decls,
704          Handled_Statement_Sequence =>
705            Make_Handled_Sequence_Of_Statements (Loc, Statements => Stats));
706    end Build_Task_Image_Function;
707
708    -----------------------------
709    -- Build_Task_Image_Prefix --
710    -----------------------------
711
712    procedure Build_Task_Image_Prefix
713       (Loc    : Source_Ptr;
714        Len    : out Entity_Id;
715        Res    : out Entity_Id;
716        Pos    : out Entity_Id;
717        Prefix : Entity_Id;
718        Sum    : Node_Id;
719        Decls  : List_Id;
720        Stats  : List_Id)
721    is
722    begin
723       Len := Make_Defining_Identifier (Loc, New_Internal_Name ('L'));
724
725       Append_To (Decls,
726         Make_Object_Declaration (Loc,
727           Defining_Identifier => Len,
728           Object_Definition => New_Occurrence_Of (Standard_Integer, Loc),
729           Expression        => Sum));
730
731       Res := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
732
733       Append_To (Decls,
734          Make_Object_Declaration (Loc,
735             Defining_Identifier => Res,
736             Object_Definition =>
737                Make_Subtype_Indication (Loc,
738                   Subtype_Mark => New_Occurrence_Of (Standard_String, Loc),
739                Constraint =>
740                  Make_Index_Or_Discriminant_Constraint (Loc,
741                    Constraints =>
742                      New_List (
743                        Make_Range (Loc,
744                          Low_Bound => Make_Integer_Literal (Loc, 1),
745                          High_Bound => New_Occurrence_Of (Len, Loc)))))));
746
747       Pos := Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
748
749       Append_To (Decls,
750          Make_Object_Declaration (Loc,
751             Defining_Identifier => Pos,
752             Object_Definition => New_Occurrence_Of (Standard_Integer, Loc)));
753
754       --  Pos := Prefix'Length;
755
756       Append_To (Stats,
757          Make_Assignment_Statement (Loc,
758             Name => New_Occurrence_Of (Pos, Loc),
759             Expression =>
760               Make_Attribute_Reference (Loc,
761                 Attribute_Name => Name_Length,
762                 Prefix => New_Occurrence_Of (Prefix, Loc),
763                 Expressions =>
764                     New_List (Make_Integer_Literal (Loc, 1)))));
765
766       --  Res (1 .. Pos) := Prefix;
767
768       Append_To (Stats,
769          Make_Assignment_Statement (Loc,
770            Name => Make_Slice (Loc,
771               Prefix => New_Occurrence_Of (Res, Loc),
772               Discrete_Range  =>
773                 Make_Range (Loc,
774                    Low_Bound => Make_Integer_Literal (Loc, 1),
775                    High_Bound => New_Occurrence_Of (Pos, Loc))),
776
777            Expression => New_Occurrence_Of (Prefix, Loc)));
778
779       Append_To (Stats,
780          Make_Assignment_Statement (Loc,
781             Name => New_Occurrence_Of (Pos, Loc),
782             Expression =>
783               Make_Op_Add (Loc,
784                 Left_Opnd => New_Occurrence_Of (Pos, Loc),
785                 Right_Opnd => Make_Integer_Literal (Loc, 1))));
786    end Build_Task_Image_Prefix;
787
788    -----------------------------
789    -- Build_Task_Record_Image --
790    -----------------------------
791
792    function Build_Task_Record_Image
793      (Loc    : Source_Ptr;
794       Id_Ref : Node_Id;
795       Dyn    : Boolean := False) return Node_Id
796    is
797       Len : Entity_Id;
798       --  Total length of generated name
799
800       Pos : Entity_Id;
801       --  Index into result
802
803       Res : Entity_Id;
804       --  String to hold result
805
806       Pref : Entity_Id;
807       --  Name of enclosing variable, prefix of resulting name
808
809       Sum : Node_Id;
810       --  Expression to compute total size of string
811
812       Sel : Entity_Id;
813       --  Entity for selector name
814
815       Decls : constant List_Id := New_List;
816       Stats : constant List_Id := New_List;
817
818    begin
819       Pref := Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
820
821       --  For a dynamic task, the name comes from the target variable.
822       --  For a static one it is a formal of the enclosing init proc.
823
824       if Dyn then
825          Get_Name_String (Chars (Entity (Prefix (Id_Ref))));
826          Append_To (Decls,
827            Make_Object_Declaration (Loc,
828              Defining_Identifier => Pref,
829              Object_Definition => New_Occurrence_Of (Standard_String, Loc),
830              Expression =>
831                Make_String_Literal (Loc,
832                  Strval => String_From_Name_Buffer)));
833
834       else
835          Append_To (Decls,
836            Make_Object_Renaming_Declaration (Loc,
837              Defining_Identifier => Pref,
838              Subtype_Mark        => New_Occurrence_Of (Standard_String, Loc),
839              Name                => Make_Identifier (Loc, Name_uTask_Name)));
840       end if;
841
842       Sel := Make_Defining_Identifier (Loc, New_Internal_Name ('S'));
843
844       Get_Name_String (Chars (Selector_Name (Id_Ref)));
845
846       Append_To (Decls,
847          Make_Object_Declaration (Loc,
848            Defining_Identifier => Sel,
849            Object_Definition => New_Occurrence_Of (Standard_String, Loc),
850            Expression =>
851              Make_String_Literal (Loc,
852                Strval => String_From_Name_Buffer)));
853
854       Sum := Make_Integer_Literal (Loc, Nat (Name_Len + 1));
855
856       Sum :=
857         Make_Op_Add (Loc,
858           Left_Opnd => Sum,
859           Right_Opnd =>
860            Make_Attribute_Reference (Loc,
861              Attribute_Name => Name_Length,
862              Prefix =>
863                New_Occurrence_Of (Pref, Loc),
864              Expressions => New_List (Make_Integer_Literal (Loc, 1))));
865
866       Build_Task_Image_Prefix (Loc, Len, Res, Pos, Pref, Sum, Decls, Stats);
867
868       Set_Character_Literal_Name (Char_Code (Character'Pos ('.')));
869
870       --  Res (Pos) := '.';
871
872       Append_To (Stats,
873          Make_Assignment_Statement (Loc,
874            Name => Make_Indexed_Component (Loc,
875               Prefix => New_Occurrence_Of (Res, Loc),
876               Expressions => New_List (New_Occurrence_Of (Pos, Loc))),
877            Expression =>
878              Make_Character_Literal (Loc,
879                Chars => Name_Find,
880                Char_Literal_Value =>
881                  UI_From_Int (Character'Pos ('.')))));
882
883       Append_To (Stats,
884         Make_Assignment_Statement (Loc,
885           Name => New_Occurrence_Of (Pos, Loc),
886           Expression =>
887             Make_Op_Add (Loc,
888               Left_Opnd => New_Occurrence_Of (Pos, Loc),
889               Right_Opnd => Make_Integer_Literal (Loc, 1))));
890
891       --  Res (Pos .. Len) := Selector;
892
893       Append_To (Stats,
894         Make_Assignment_Statement (Loc,
895           Name => Make_Slice (Loc,
896              Prefix => New_Occurrence_Of (Res, Loc),
897              Discrete_Range  =>
898                Make_Range (Loc,
899                  Low_Bound  => New_Occurrence_Of (Pos, Loc),
900                  High_Bound => New_Occurrence_Of (Len, Loc))),
901           Expression => New_Occurrence_Of (Sel, Loc)));
902
903       return Build_Task_Image_Function (Loc, Decls, Stats, Res);
904    end Build_Task_Record_Image;
905
906    ----------------------------------
907    -- Component_May_Be_Bit_Aligned --
908    ----------------------------------
909
910    function Component_May_Be_Bit_Aligned (Comp : Entity_Id) return Boolean is
911    begin
912       --  If no component clause, then everything is fine, since the
913       --  back end never bit-misaligns by default, even if there is
914       --  a pragma Packed for the record.
915
916       if No (Component_Clause (Comp)) then
917          return False;
918       end if;
919
920       --  It is only array and record types that cause trouble
921
922       if not Is_Record_Type (Etype (Comp))
923         and then not Is_Array_Type (Etype (Comp))
924       then
925          return False;
926
927       --  If we know that we have a small (64 bits or less) record
928       --  or bit-packed array, then everything is fine, since the
929       --  back end can handle these cases correctly.
930
931       elsif Esize (Comp) <= 64
932         and then (Is_Record_Type (Etype (Comp))
933                    or else Is_Bit_Packed_Array (Etype (Comp)))
934       then
935          return False;
936
937       --  Otherwise if the component is not byte aligned, we
938       --  know we have the nasty unaligned case.
939
940       elsif Normalized_First_Bit (Comp) /= Uint_0
941         or else Esize (Comp) mod System_Storage_Unit /= Uint_0
942       then
943          return True;
944
945       --  If we are large and byte aligned, then OK at this level
946
947       else
948          return False;
949       end if;
950    end Component_May_Be_Bit_Aligned;
951
952    -------------------------------
953    -- Convert_To_Actual_Subtype --
954    -------------------------------
955
956    procedure Convert_To_Actual_Subtype (Exp : Entity_Id) is
957       Act_ST : Entity_Id;
958
959    begin
960       Act_ST := Get_Actual_Subtype (Exp);
961
962       if Act_ST = Etype (Exp) then
963          return;
964
965       else
966          Rewrite (Exp,
967            Convert_To (Act_ST, Relocate_Node (Exp)));
968          Analyze_And_Resolve (Exp, Act_ST);
969       end if;
970    end Convert_To_Actual_Subtype;
971
972    -----------------------------------
973    -- Current_Sem_Unit_Declarations --
974    -----------------------------------
975
976    function Current_Sem_Unit_Declarations return List_Id is
977       U     : Node_Id := Unit (Cunit (Current_Sem_Unit));
978       Decls : List_Id;
979
980    begin
981       --  If the current unit is a package body, locate the visible
982       --  declarations of the package spec.
983
984       if Nkind (U) = N_Package_Body then
985          U := Unit (Library_Unit (Cunit (Current_Sem_Unit)));
986       end if;
987
988       if Nkind (U) = N_Package_Declaration then
989          U := Specification (U);
990          Decls := Visible_Declarations (U);
991
992          if No (Decls) then
993             Decls := New_List;
994             Set_Visible_Declarations (U, Decls);
995          end if;
996
997       else
998          Decls := Declarations (U);
999
1000          if No (Decls) then
1001             Decls := New_List;
1002             Set_Declarations (U, Decls);
1003          end if;
1004       end if;
1005
1006       return Decls;
1007    end Current_Sem_Unit_Declarations;
1008
1009    -----------------------
1010    -- Duplicate_Subexpr --
1011    -----------------------
1012
1013    function Duplicate_Subexpr
1014      (Exp      : Node_Id;
1015       Name_Req : Boolean := False) return Node_Id
1016    is
1017    begin
1018       Remove_Side_Effects (Exp, Name_Req);
1019       return New_Copy_Tree (Exp);
1020    end Duplicate_Subexpr;
1021
1022    ---------------------------------
1023    -- Duplicate_Subexpr_No_Checks --
1024    ---------------------------------
1025
1026    function Duplicate_Subexpr_No_Checks
1027      (Exp      : Node_Id;
1028       Name_Req : Boolean := False) return Node_Id
1029    is
1030       New_Exp : Node_Id;
1031
1032    begin
1033       Remove_Side_Effects (Exp, Name_Req);
1034       New_Exp := New_Copy_Tree (Exp);
1035       Remove_Checks (New_Exp);
1036       return New_Exp;
1037    end Duplicate_Subexpr_No_Checks;
1038
1039    -----------------------------------
1040    -- Duplicate_Subexpr_Move_Checks --
1041    -----------------------------------
1042
1043    function Duplicate_Subexpr_Move_Checks
1044      (Exp      : Node_Id;
1045       Name_Req : Boolean := False) return Node_Id
1046    is
1047       New_Exp : Node_Id;
1048
1049    begin
1050       Remove_Side_Effects (Exp, Name_Req);
1051       New_Exp := New_Copy_Tree (Exp);
1052       Remove_Checks (Exp);
1053       return New_Exp;
1054    end Duplicate_Subexpr_Move_Checks;
1055
1056    --------------------
1057    -- Ensure_Defined --
1058    --------------------
1059
1060    procedure Ensure_Defined (Typ : Entity_Id; N : Node_Id) is
1061       IR : Node_Id;
1062
1063    begin
1064       --  An itype reference must only be created if this is a local
1065       --  itype, so that gigi can elaborate it on the proper objstack.
1066
1067       if Is_Itype (Typ)
1068         and then Scope (Typ) = Current_Scope
1069       then
1070          IR := Make_Itype_Reference (Sloc (N));
1071          Set_Itype (IR, Typ);
1072          Insert_Action (N, IR);
1073       end if;
1074    end Ensure_Defined;
1075
1076    ---------------------
1077    -- Evolve_And_Then --
1078    ---------------------
1079
1080    procedure Evolve_And_Then (Cond : in out Node_Id; Cond1 : Node_Id) is
1081    begin
1082       if No (Cond) then
1083          Cond := Cond1;
1084       else
1085          Cond :=
1086            Make_And_Then (Sloc (Cond1),
1087              Left_Opnd  => Cond,
1088              Right_Opnd => Cond1);
1089       end if;
1090    end Evolve_And_Then;
1091
1092    --------------------
1093    -- Evolve_Or_Else --
1094    --------------------
1095
1096    procedure Evolve_Or_Else (Cond : in out Node_Id; Cond1 : Node_Id) is
1097    begin
1098       if No (Cond) then
1099          Cond := Cond1;
1100       else
1101          Cond :=
1102            Make_Or_Else (Sloc (Cond1),
1103              Left_Opnd  => Cond,
1104              Right_Opnd => Cond1);
1105       end if;
1106    end Evolve_Or_Else;
1107
1108    ------------------------------
1109    -- Expand_Subtype_From_Expr --
1110    ------------------------------
1111
1112    --  This function is applicable for both static and dynamic allocation of
1113    --  objects which are constrained by an initial expression. Basically it
1114    --  transforms an unconstrained subtype indication into a constrained one.
1115    --  The expression may also be transformed in certain cases in order to
1116    --  avoid multiple evaluation. In the static allocation case, the general
1117    --  scheme is:
1118
1119    --     Val : T := Expr;
1120
1121    --        is transformed into
1122
1123    --     Val : Constrained_Subtype_of_T := Maybe_Modified_Expr;
1124    --
1125    --  Here are the main cases :
1126    --
1127    --  <if Expr is a Slice>
1128    --    Val : T ([Index_Subtype (Expr)]) := Expr;
1129    --
1130    --  <elsif Expr is a String Literal>
1131    --    Val : T (T'First .. T'First + Length (string literal) - 1) := Expr;
1132    --
1133    --  <elsif Expr is Constrained>
1134    --    subtype T is Type_Of_Expr
1135    --    Val : T := Expr;
1136    --
1137    --  <elsif Expr is an entity_name>
1138    --    Val : T (constraints taken from Expr) := Expr;
1139    --
1140    --  <else>
1141    --    type Axxx is access all T;
1142    --    Rval : Axxx := Expr'ref;
1143    --    Val  : T (constraints taken from Rval) := Rval.all;
1144
1145    --    ??? note: when the Expression is allocated in the secondary stack
1146    --              we could use it directly instead of copying it by declaring
1147    --              Val : T (...) renames Rval.all
1148
1149    procedure Expand_Subtype_From_Expr
1150      (N             : Node_Id;
1151       Unc_Type      : Entity_Id;
1152       Subtype_Indic : Node_Id;
1153       Exp           : Node_Id)
1154    is
1155       Loc     : constant Source_Ptr := Sloc (N);
1156       Exp_Typ : constant Entity_Id  := Etype (Exp);
1157       T       : Entity_Id;
1158
1159    begin
1160       --  In general we cannot build the subtype if expansion is disabled,
1161       --  because internal entities may not have been defined. However, to
1162       --  avoid some cascaded errors, we try to continue when the expression
1163       --  is an array (or string), because it is safe to compute the bounds.
1164       --  It is in fact required to do so even in a generic context, because
1165       --  there may be constants that depend on bounds of string literal.
1166
1167       if not Expander_Active
1168         and then (No (Etype (Exp))
1169                    or else Base_Type (Etype (Exp)) /= Standard_String)
1170       then
1171          return;
1172       end if;
1173
1174       if Nkind (Exp) = N_Slice then
1175          declare
1176             Slice_Type : constant Entity_Id := Etype (First_Index (Exp_Typ));
1177
1178          begin
1179             Rewrite (Subtype_Indic,
1180               Make_Subtype_Indication (Loc,
1181                 Subtype_Mark => New_Reference_To (Unc_Type, Loc),
1182                 Constraint =>
1183                   Make_Index_Or_Discriminant_Constraint (Loc,
1184                     Constraints => New_List
1185                       (New_Reference_To (Slice_Type, Loc)))));
1186
1187             --  This subtype indication may be used later for contraint checks
1188             --  we better make sure that if a variable was used as a bound of
1189             --  of the original slice, its value is frozen.
1190
1191             Force_Evaluation (Low_Bound (Scalar_Range (Slice_Type)));
1192             Force_Evaluation (High_Bound (Scalar_Range (Slice_Type)));
1193          end;
1194
1195       elsif Ekind (Exp_Typ) = E_String_Literal_Subtype then
1196          Rewrite (Subtype_Indic,
1197            Make_Subtype_Indication (Loc,
1198              Subtype_Mark => New_Reference_To (Unc_Type, Loc),
1199              Constraint =>
1200                Make_Index_Or_Discriminant_Constraint (Loc,
1201                  Constraints => New_List (
1202                    Make_Literal_Range (Loc,
1203                      Literal_Typ => Exp_Typ)))));
1204
1205       elsif Is_Constrained (Exp_Typ)
1206         and then not Is_Class_Wide_Type (Unc_Type)
1207       then
1208          if Is_Itype (Exp_Typ) then
1209
1210             --  Within an initialization procedure, a selected component
1211             --  denotes a component of the enclosing record, and it appears
1212             --  as an actual in a call to its own initialization procedure.
1213             --  If this component depends on the outer discriminant, we must
1214             --  generate the proper actual subtype for it.
1215
1216             if Nkind (Exp) = N_Selected_Component
1217               and then Within_Init_Proc
1218             then
1219                declare
1220                   Decl : constant Node_Id :=
1221                            Build_Actual_Subtype_Of_Component (Exp_Typ, Exp);
1222                begin
1223                   if Present (Decl) then
1224                      Insert_Action (N, Decl);
1225                      T := Defining_Identifier (Decl);
1226                   else
1227                      T := Exp_Typ;
1228                   end if;
1229                end;
1230
1231             --  No need to generate a new one (new what???)
1232
1233             else
1234                T := Exp_Typ;
1235             end if;
1236
1237          else
1238             T :=
1239               Make_Defining_Identifier (Loc,
1240                 Chars => New_Internal_Name ('T'));
1241
1242             Insert_Action (N,
1243               Make_Subtype_Declaration (Loc,
1244                 Defining_Identifier => T,
1245                 Subtype_Indication  => New_Reference_To (Exp_Typ, Loc)));
1246
1247             --  This type is marked as an itype even though it has an
1248             --  explicit declaration because otherwise it can be marked
1249             --  with Is_Generic_Actual_Type and generate spurious errors.
1250             --  (see sem_ch8.Analyze_Package_Renaming and sem_type.covers)
1251
1252             Set_Is_Itype (T);
1253             Set_Associated_Node_For_Itype (T, Exp);
1254          end if;
1255
1256          Rewrite (Subtype_Indic, New_Reference_To (T, Loc));
1257
1258       --  nothing needs to be done for private types with unknown discriminants
1259       --  if the underlying type is not an unconstrained composite type.
1260
1261       elsif Is_Private_Type (Unc_Type)
1262         and then Has_Unknown_Discriminants (Unc_Type)
1263         and then (not Is_Composite_Type (Underlying_Type (Unc_Type))
1264                     or else Is_Constrained (Underlying_Type (Unc_Type)))
1265       then
1266          null;
1267
1268       --  Nothing to be done for derived types with unknown discriminants if
1269       --  the parent type also has unknown discriminants.
1270
1271       elsif Is_Record_Type (Unc_Type)
1272         and then not Is_Class_Wide_Type (Unc_Type)
1273         and then Has_Unknown_Discriminants (Unc_Type)
1274         and then Has_Unknown_Discriminants (Underlying_Type (Unc_Type))
1275       then
1276          null;
1277
1278       --  In Ada95, Nothing to be done if the type of the expression is
1279       --  limited, because in this case the expression cannot be copied,
1280       --  and its use can only be by reference.
1281
1282       --  In Ada2005, the context can be an object declaration whose expression
1283       --  is a function that returns in place. If the nominal subtype has
1284       --  unknown discriminants, the call still provides constraints on the
1285       --  object, and we have to create an actual subtype from it.
1286
1287       --  If the type is class-wide, the expression is dynamically tagged and
1288       --  we do not create an actual subtype either. Ditto for an interface.
1289
1290       elsif Is_Limited_Type (Exp_Typ)
1291         and then
1292          (Is_Class_Wide_Type (Exp_Typ)
1293            or else Is_Interface (Exp_Typ)
1294            or else not Has_Unknown_Discriminants (Exp_Typ)
1295            or else not Is_Composite_Type (Unc_Type))
1296       then
1297          null;
1298
1299       --  For limited interfaces, nothing to be done
1300
1301       --  This branch may be redundant once the limited interface issue is
1302       --  sorted out???
1303
1304       elsif Is_Interface (Exp_Typ)
1305         and then Is_Limited_Interface (Exp_Typ)
1306       then
1307          null;
1308
1309       --  For limited objects initialized with build in place function calls,
1310       --  nothing to be done; otherwise we prematurely introduce an N_Reference
1311       --  node in the expression initializing the object, which breaks the
1312       --  circuitry that detects and adds the additional arguments to the
1313       --  called function.
1314
1315       elsif Is_Build_In_Place_Function_Call (Exp) then
1316          null;
1317
1318       else
1319          Remove_Side_Effects (Exp);
1320          Rewrite (Subtype_Indic,
1321            Make_Subtype_From_Expr (Exp, Unc_Type));
1322       end if;
1323    end Expand_Subtype_From_Expr;
1324
1325    ------------------------
1326    -- Find_Interface_ADT --
1327    ------------------------
1328
1329    function Find_Interface_ADT
1330      (T     : Entity_Id;
1331       Iface : Entity_Id) return Entity_Id
1332    is
1333       ADT   : Elmt_Id;
1334       Found : Boolean   := False;
1335       Typ   : Entity_Id := T;
1336
1337       procedure Find_Secondary_Table (Typ : Entity_Id);
1338       --  Internal subprogram used to recursively climb to the ancestors
1339
1340       --------------------------
1341       -- Find_Secondary_Table --
1342       --------------------------
1343
1344       procedure Find_Secondary_Table (Typ : Entity_Id) is
1345          AI_Elmt : Elmt_Id;
1346          AI      : Node_Id;
1347
1348       begin
1349          pragma Assert (Typ /= Iface);
1350
1351          --  Climb to the ancestor (if any) handling synchronized interface
1352          --  derivations and private types
1353
1354          if Is_Concurrent_Record_Type (Typ) then
1355             declare
1356                Iface_List : constant List_Id := Abstract_Interface_List (Typ);
1357
1358             begin
1359                if Is_Non_Empty_List (Iface_List) then
1360                   Find_Secondary_Table (Etype (First (Iface_List)));
1361                end if;
1362             end;
1363
1364          elsif Present (Full_View (Etype (Typ))) then
1365             if Full_View (Etype (Typ)) /= Typ then
1366                Find_Secondary_Table (Full_View (Etype (Typ)));
1367             end if;
1368
1369          elsif Etype (Typ) /= Typ then
1370             Find_Secondary_Table (Etype (Typ));
1371          end if;
1372
1373          --  Traverse the list of interfaces implemented by the type
1374
1375          if not Found
1376            and then Present (Abstract_Interfaces (Typ))
1377            and then not Is_Empty_Elmt_List (Abstract_Interfaces (Typ))
1378          then
1379             AI_Elmt := First_Elmt (Abstract_Interfaces (Typ));
1380             while Present (AI_Elmt) loop
1381                AI := Node (AI_Elmt);
1382
1383                if AI = Iface or else Is_Ancestor (Iface, AI) then
1384                   Found := True;
1385                   return;
1386                end if;
1387
1388                Next_Elmt (ADT);
1389                Next_Elmt (AI_Elmt);
1390             end loop;
1391          end if;
1392       end Find_Secondary_Table;
1393
1394    --  Start of processing for Find_Interface_ADT
1395
1396    begin
1397       pragma Assert (Is_Interface (Iface));
1398
1399       --  Handle private types
1400
1401       if Has_Private_Declaration (Typ)
1402         and then Present (Full_View (Typ))
1403       then
1404          Typ := Full_View (Typ);
1405       end if;
1406
1407       --  Handle access types
1408
1409       if Is_Access_Type (Typ) then
1410          Typ := Directly_Designated_Type (Typ);
1411       end if;
1412
1413       --  Handle task and protected types implementing interfaces
1414
1415       if Is_Concurrent_Type (Typ) then
1416          Typ := Corresponding_Record_Type (Typ);
1417       end if;
1418
1419       pragma Assert
1420         (not Is_Class_Wide_Type (Typ)
1421           and then Ekind (Typ) /= E_Incomplete_Type);
1422
1423       ADT := Next_Elmt (First_Elmt (Access_Disp_Table (Typ)));
1424       pragma Assert (Present (Node (ADT)));
1425       Find_Secondary_Table (Typ);
1426       pragma Assert (Found);
1427       return Node (ADT);
1428    end Find_Interface_ADT;
1429
1430    ------------------------
1431    -- Find_Interface_Tag --
1432    ------------------------
1433
1434    function Find_Interface_Tag
1435      (T     : Entity_Id;
1436       Iface : Entity_Id) return Entity_Id
1437    is
1438       AI_Tag : Entity_Id;
1439       Found  : Boolean   := False;
1440       Typ    : Entity_Id := T;
1441
1442       Is_Primary_Tag : Boolean := False;
1443
1444       Is_Sync_Typ : Boolean := False;
1445       --  In case of non concurrent-record-types each parent-type has the
1446       --  tags associated with the interface types that are not implemented
1447       --  by the ancestors; concurrent-record-types have their whole list of
1448       --  interface tags (and this case requires some special management).
1449
1450       procedure Find_Tag (Typ : Entity_Id);
1451       --  Internal subprogram used to recursively climb to the ancestors
1452
1453       --------------
1454       -- Find_Tag --
1455       --------------
1456
1457       procedure Find_Tag (Typ : Entity_Id) is
1458          AI_Elmt : Elmt_Id;
1459          AI      : Node_Id;
1460
1461       begin
1462          --  Check if the interface is an immediate ancestor of the type and
1463          --  therefore shares the main tag.
1464
1465          if Typ = Iface then
1466             if Is_Sync_Typ then
1467                Is_Primary_Tag := True;
1468             else
1469                pragma Assert
1470                  (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1471                AI_Tag := First_Tag_Component (Typ);
1472             end if;
1473
1474             Found  := True;
1475             return;
1476          end if;
1477
1478          --  Handle synchronized interface derivations
1479
1480          if Is_Concurrent_Record_Type (Typ) then
1481             declare
1482                Iface_List : constant List_Id := Abstract_Interface_List (Typ);
1483             begin
1484                if Is_Non_Empty_List (Iface_List) then
1485                   Find_Tag (Etype (First (Iface_List)));
1486                end if;
1487             end;
1488
1489          --  Climb to the root type handling private types
1490
1491          elsif Present (Full_View (Etype (Typ))) then
1492             if Full_View (Etype (Typ)) /= Typ then
1493                Find_Tag (Full_View (Etype (Typ)));
1494             end if;
1495
1496          elsif Etype (Typ) /= Typ then
1497             Find_Tag (Etype (Typ));
1498          end if;
1499
1500          --  Traverse the list of interfaces implemented by the type
1501
1502          if not Found
1503            and then Present (Abstract_Interfaces (Typ))
1504            and then not (Is_Empty_Elmt_List (Abstract_Interfaces (Typ)))
1505          then
1506             --  Skip the tag associated with the primary table
1507
1508             if not Is_Sync_Typ then
1509                pragma Assert
1510                  (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1511                AI_Tag := Next_Tag_Component (First_Tag_Component (Typ));
1512                pragma Assert (Present (AI_Tag));
1513             end if;
1514
1515             AI_Elmt := First_Elmt (Abstract_Interfaces (Typ));
1516             while Present (AI_Elmt) loop
1517                AI := Node (AI_Elmt);
1518
1519                if AI = Iface or else Is_Ancestor (Iface, AI) then
1520                   Found := True;
1521                   return;
1522                end if;
1523
1524                AI_Tag := Next_Tag_Component (AI_Tag);
1525                Next_Elmt (AI_Elmt);
1526             end loop;
1527          end if;
1528       end Find_Tag;
1529
1530    --  Start of processing for Find_Interface_Tag
1531
1532    begin
1533       pragma Assert (Is_Interface (Iface));
1534
1535       --  Handle private types
1536
1537       if Has_Private_Declaration (Typ)
1538         and then Present (Full_View (Typ))
1539       then
1540          Typ := Full_View (Typ);
1541       end if;
1542
1543       --  Handle access types
1544
1545       if Is_Access_Type (Typ) then
1546          Typ := Directly_Designated_Type (Typ);
1547       end if;
1548
1549       --  Handle task and protected types implementing interfaces
1550
1551       if Is_Concurrent_Type (Typ) then
1552          Typ := Corresponding_Record_Type (Typ);
1553       end if;
1554
1555       if Is_Class_Wide_Type (Typ) then
1556          Typ := Etype (Typ);
1557       end if;
1558
1559       --  Handle entities from the limited view
1560
1561       if Ekind (Typ) = E_Incomplete_Type then
1562          pragma Assert (Present (Non_Limited_View (Typ)));
1563          Typ := Non_Limited_View (Typ);
1564       end if;
1565
1566       if not Is_Concurrent_Record_Type (Typ) then
1567          Find_Tag (Typ);
1568          pragma Assert (Found);
1569          return AI_Tag;
1570
1571       --  Concurrent record types
1572
1573       else
1574          Is_Sync_Typ := True;
1575          AI_Tag      := Next_Tag_Component (First_Tag_Component (Typ));
1576          Find_Tag (Typ);
1577          pragma Assert (Found);
1578
1579          if Is_Primary_Tag then
1580             return First_Tag_Component (Typ);
1581          else
1582             return AI_Tag;
1583          end if;
1584       end if;
1585    end Find_Interface_Tag;
1586
1587    --------------------
1588    -- Find_Interface --
1589    --------------------
1590
1591    function Find_Interface
1592      (T      : Entity_Id;
1593       Comp   : Entity_Id) return Entity_Id
1594    is
1595       AI_Tag : Entity_Id;
1596       Found  : Boolean := False;
1597       Iface  : Entity_Id;
1598       Typ    : Entity_Id := T;
1599
1600       Is_Sync_Typ : Boolean := False;
1601       --  In case of non concurrent-record-types each parent-type has the
1602       --  tags associated with the interface types that are not implemented
1603       --  by the ancestors; concurrent-record-types have their whole list of
1604       --  interface tags (and this case requires some special management).
1605
1606       procedure Find_Iface (Typ : Entity_Id);
1607       --  Internal subprogram used to recursively climb to the ancestors
1608
1609       ----------------
1610       -- Find_Iface --
1611       ----------------
1612
1613       procedure Find_Iface (Typ : Entity_Id) is
1614          AI_Elmt : Elmt_Id;
1615
1616       begin
1617          --  Climb to the root type
1618
1619          --  Handle sychronized interface derivations
1620
1621          if Is_Concurrent_Record_Type (Typ) then
1622             declare
1623                Iface_List : constant List_Id := Abstract_Interface_List (Typ);
1624             begin
1625                if Is_Non_Empty_List (Iface_List) then
1626                   Find_Iface (Etype (First (Iface_List)));
1627                end if;
1628             end;
1629
1630          --  Handle the common case
1631
1632          elsif Etype (Typ) /= Typ then
1633             pragma Assert (not Present (Full_View (Etype (Typ))));
1634             Find_Iface (Etype (Typ));
1635          end if;
1636
1637          --  Traverse the list of interfaces implemented by the type
1638
1639          if not Found
1640            and then Present (Abstract_Interfaces (Typ))
1641            and then not (Is_Empty_Elmt_List (Abstract_Interfaces (Typ)))
1642          then
1643             --  Skip the tag associated with the primary table
1644
1645             if not Is_Sync_Typ then
1646                pragma Assert
1647                  (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1648                AI_Tag := Next_Tag_Component (First_Tag_Component (Typ));
1649                pragma Assert (Present (AI_Tag));
1650             end if;
1651
1652             AI_Elmt := First_Elmt (Abstract_Interfaces (Typ));
1653             while Present (AI_Elmt) loop
1654                if AI_Tag = Comp then
1655                   Iface := Node (AI_Elmt);
1656                   Found := True;
1657                   return;
1658                end if;
1659
1660                AI_Tag := Next_Tag_Component (AI_Tag);
1661                Next_Elmt (AI_Elmt);
1662             end loop;
1663          end if;
1664       end Find_Iface;
1665
1666    --  Start of processing for Find_Interface
1667
1668    begin
1669       --  Handle private types
1670
1671       if Has_Private_Declaration (Typ)
1672         and then Present (Full_View (Typ))
1673       then
1674          Typ := Full_View (Typ);
1675       end if;
1676
1677       --  Handle access types
1678
1679       if Is_Access_Type (Typ) then
1680          Typ := Directly_Designated_Type (Typ);
1681       end if;
1682
1683       --  Handle task and protected types implementing interfaces
1684
1685       if Is_Concurrent_Type (Typ) then
1686          Typ := Corresponding_Record_Type (Typ);
1687       end if;
1688
1689       if Is_Class_Wide_Type (Typ) then
1690          Typ := Etype (Typ);
1691       end if;
1692
1693       --  Handle entities from the limited view
1694
1695       if Ekind (Typ) = E_Incomplete_Type then
1696          pragma Assert (Present (Non_Limited_View (Typ)));
1697          Typ := Non_Limited_View (Typ);
1698       end if;
1699
1700       if Is_Concurrent_Record_Type (Typ) then
1701          Is_Sync_Typ := True;
1702          AI_Tag      := Next_Tag_Component (First_Tag_Component (Typ));
1703       end if;
1704
1705       Find_Iface (Typ);
1706       pragma Assert (Found);
1707       return Iface;
1708    end Find_Interface;
1709
1710    ------------------
1711    -- Find_Prim_Op --
1712    ------------------
1713
1714    function Find_Prim_Op (T : Entity_Id; Name : Name_Id) return Entity_Id is
1715       Prim : Elmt_Id;
1716       Typ  : Entity_Id := T;
1717       Op   : Entity_Id;
1718
1719    begin
1720       if Is_Class_Wide_Type (Typ) then
1721          Typ := Root_Type (Typ);
1722       end if;
1723
1724       Typ := Underlying_Type (Typ);
1725
1726       --  Loop through primitive operations
1727
1728       Prim := First_Elmt (Primitive_Operations (Typ));
1729       while Present (Prim) loop
1730          Op := Node (Prim);
1731
1732          --  We can retrieve primitive operations by name if it is an internal
1733          --  name. For equality we must check that both of its operands have
1734          --  the same type, to avoid confusion with user-defined equalities
1735          --  than may have a non-symmetric signature.
1736
1737          exit when Chars (Op) = Name
1738            and then
1739              (Name /= Name_Op_Eq
1740                 or else Etype (First_Entity (Op)) = Etype (Last_Entity (Op)));
1741
1742          Next_Elmt (Prim);
1743          pragma Assert (Present (Prim));
1744       end loop;
1745
1746       return Node (Prim);
1747    end Find_Prim_Op;
1748
1749    ------------------
1750    -- Find_Prim_Op --
1751    ------------------
1752
1753    function Find_Prim_Op
1754      (T    : Entity_Id;
1755       Name : TSS_Name_Type) return Entity_Id
1756    is
1757       Prim : Elmt_Id;
1758       Typ  : Entity_Id := T;
1759
1760    begin
1761       if Is_Class_Wide_Type (Typ) then
1762          Typ := Root_Type (Typ);
1763       end if;
1764
1765       Typ := Underlying_Type (Typ);
1766
1767       Prim := First_Elmt (Primitive_Operations (Typ));
1768       while not Is_TSS (Node (Prim), Name) loop
1769          Next_Elmt (Prim);
1770          pragma Assert (Present (Prim));
1771       end loop;
1772
1773       return Node (Prim);
1774    end Find_Prim_Op;
1775
1776    ----------------------
1777    -- Force_Evaluation --
1778    ----------------------
1779
1780    procedure Force_Evaluation (Exp : Node_Id; Name_Req : Boolean := False) is
1781    begin
1782       Remove_Side_Effects (Exp, Name_Req, Variable_Ref => True);
1783    end Force_Evaluation;
1784
1785    ------------------------
1786    -- Generate_Poll_Call --
1787    ------------------------
1788
1789    procedure Generate_Poll_Call (N : Node_Id) is
1790    begin
1791       --  No poll call if polling not active
1792
1793       if not Polling_Required then
1794          return;
1795
1796       --  Otherwise generate require poll call
1797
1798       else
1799          Insert_Before_And_Analyze (N,
1800            Make_Procedure_Call_Statement (Sloc (N),
1801              Name => New_Occurrence_Of (RTE (RE_Poll), Sloc (N))));
1802       end if;
1803    end Generate_Poll_Call;
1804
1805    ---------------------------------
1806    -- Get_Current_Value_Condition --
1807    ---------------------------------
1808
1809    --  Note: the implementation of this procedure is very closely tied to the
1810    --  implementation of Set_Current_Value_Condition. In the Get procedure, we
1811    --  interpret Current_Value fields set by the Set procedure, so the two
1812    --  procedures need to be closely coordinated.
1813
1814    procedure Get_Current_Value_Condition
1815      (Var : Node_Id;
1816       Op  : out Node_Kind;
1817       Val : out Node_Id)
1818    is
1819       Loc : constant Source_Ptr := Sloc (Var);
1820       Ent : constant Entity_Id  := Entity (Var);
1821
1822       procedure Process_Current_Value_Condition
1823         (N : Node_Id;
1824          S : Boolean);
1825       --  N is an expression which holds either True (S = True) or False (S =
1826       --  False) in the condition. This procedure digs out the expression and
1827       --  if it refers to Ent, sets Op and Val appropriately.
1828
1829       -------------------------------------
1830       -- Process_Current_Value_Condition --
1831       -------------------------------------
1832
1833       procedure Process_Current_Value_Condition
1834         (N : Node_Id;
1835          S : Boolean)
1836       is
1837          Cond : Node_Id;
1838          Sens : Boolean;
1839
1840       begin
1841          Cond := N;
1842          Sens := S;
1843
1844          --  Deal with NOT operators, inverting sense
1845
1846          while Nkind (Cond) = N_Op_Not loop
1847             Cond := Right_Opnd (Cond);
1848             Sens := not Sens;
1849          end loop;
1850
1851          --  Deal with AND THEN and AND cases
1852
1853          if Nkind (Cond) = N_And_Then
1854            or else Nkind (Cond) = N_Op_And
1855          then
1856             --  Don't ever try to invert a condition that is of the form
1857             --  of an AND or AND THEN (since we are not doing sufficiently
1858             --  general processing to allow this).
1859
1860             if Sens = False then
1861                Op  := N_Empty;
1862                Val := Empty;
1863                return;
1864             end if;
1865
1866             --  Recursively process AND and AND THEN branches
1867
1868             Process_Current_Value_Condition (Left_Opnd (Cond), True);
1869
1870             if Op /= N_Empty then
1871                return;
1872             end if;
1873
1874             Process_Current_Value_Condition (Right_Opnd (Cond), True);
1875             return;
1876
1877          --  Case of relational operator
1878
1879          elsif Nkind (Cond) in N_Op_Compare then
1880             Op := Nkind (Cond);
1881
1882             --  Invert sense of test if inverted test
1883
1884             if Sens = False then
1885                case Op is
1886                   when N_Op_Eq => Op := N_Op_Ne;
1887                   when N_Op_Ne => Op := N_Op_Eq;
1888                   when N_Op_Lt => Op := N_Op_Ge;
1889                   when N_Op_Gt => Op := N_Op_Le;
1890                   when N_Op_Le => Op := N_Op_Gt;
1891                   when N_Op_Ge => Op := N_Op_Lt;
1892                   when others  => raise Program_Error;
1893                end case;
1894             end if;
1895
1896             --  Case of entity op value
1897
1898             if Is_Entity_Name (Left_Opnd (Cond))
1899               and then Ent = Entity (Left_Opnd (Cond))
1900               and then Compile_Time_Known_Value (Right_Opnd (Cond))
1901             then
1902                Val := Right_Opnd (Cond);
1903
1904             --  Case of value op entity
1905
1906             elsif Is_Entity_Name (Right_Opnd (Cond))
1907               and then Ent = Entity (Right_Opnd (Cond))
1908               and then Compile_Time_Known_Value (Left_Opnd (Cond))
1909             then
1910                Val := Left_Opnd (Cond);
1911
1912                --  We are effectively swapping operands
1913
1914                case Op is
1915                   when N_Op_Eq => null;
1916                   when N_Op_Ne => null;
1917                   when N_Op_Lt => Op := N_Op_Gt;
1918                   when N_Op_Gt => Op := N_Op_Lt;
1919                   when N_Op_Le => Op := N_Op_Ge;
1920                   when N_Op_Ge => Op := N_Op_Le;
1921                   when others  => raise Program_Error;
1922                end case;
1923
1924             else
1925                Op := N_Empty;
1926             end if;
1927
1928             return;
1929
1930             --  Case of Boolean variable reference, return as though the
1931             --  reference had said var = True.
1932
1933          else
1934             if Is_Entity_Name (Cond)
1935               and then Ent = Entity (Cond)
1936             then
1937                Val := New_Occurrence_Of (Standard_True, Sloc (Cond));
1938
1939                if Sens = False then
1940                   Op := N_Op_Ne;
1941                else
1942                   Op := N_Op_Eq;
1943                end if;
1944             end if;
1945          end if;
1946       end Process_Current_Value_Condition;
1947
1948    --  Start of processing for Get_Current_Value_Condition
1949
1950    begin
1951       Op  := N_Empty;
1952       Val := Empty;
1953
1954       --  Immediate return, nothing doing, if this is not an object
1955
1956       if Ekind (Ent) not in Object_Kind then
1957          return;
1958       end if;
1959
1960       --  Otherwise examine current value
1961
1962       declare
1963          CV   : constant Node_Id := Current_Value (Ent);
1964          Sens : Boolean;
1965          Stm  : Node_Id;
1966
1967       begin
1968          --  If statement. Condition is known true in THEN section, known False
1969          --  in any ELSIF or ELSE part, and unknown outside the IF statement.
1970
1971          if Nkind (CV) = N_If_Statement then
1972
1973             --  Before start of IF statement
1974
1975             if Loc < Sloc (CV) then
1976                return;
1977
1978                --  After end of IF statement
1979
1980             elsif Loc >= Sloc (CV) + Text_Ptr (UI_To_Int (End_Span (CV))) then
1981                return;
1982             end if;
1983
1984             --  At this stage we know that we are within the IF statement, but
1985             --  unfortunately, the tree does not record the SLOC of the ELSE so
1986             --  we cannot use a simple SLOC comparison to distinguish between
1987             --  the then/else statements, so we have to climb the tree.
1988
1989             declare
1990                N : Node_Id;
1991
1992             begin
1993                N := Parent (Var);
1994                while Parent (N) /= CV loop
1995                   N := Parent (N);
1996
1997                   --  If we fall off the top of the tree, then that's odd, but
1998                   --  perhaps it could occur in some error situation, and the
1999                   --  safest response is simply to assume that the outcome of
2000                   --  the condition is unknown. No point in bombing during an
2001                   --  attempt to optimize things.
2002
2003                   if No (N) then
2004                      return;
2005                   end if;
2006                end loop;
2007
2008                --  Now we have N pointing to a node whose parent is the IF
2009                --  statement in question, so now we can tell if we are within
2010                --  the THEN statements.
2011
2012                if Is_List_Member (N)
2013                  and then List_Containing (N) = Then_Statements (CV)
2014                then
2015                   Sens := True;
2016
2017                --  If the variable reference does not come from source, we
2018                --  cannot reliably tell whether it appears in the else part.
2019                --  In particular, if if appears in generated code for a node
2020                --  that requires finalization, it may be attached to a list
2021                --  that has not been yet inserted into the code. For now,
2022                --  treat it as unknown.
2023
2024                elsif not Comes_From_Source (N) then
2025                   return;
2026
2027                --  Otherwise we must be in ELSIF or ELSE part
2028
2029                else
2030                   Sens := False;
2031                end if;
2032             end;
2033
2034             --  ELSIF part. Condition is known true within the referenced
2035             --  ELSIF, known False in any subsequent ELSIF or ELSE part, and
2036             --  unknown before the ELSE part or after the IF statement.
2037
2038          elsif Nkind (CV) = N_Elsif_Part then
2039             Stm := Parent (CV);
2040
2041             --  Before start of ELSIF part
2042
2043             if Loc < Sloc (CV) then
2044                return;
2045
2046                --  After end of IF statement
2047
2048             elsif Loc >= Sloc (Stm) +
2049               Text_Ptr (UI_To_Int (End_Span (Stm)))
2050             then
2051                return;
2052             end if;
2053
2054             --  Again we lack the SLOC of the ELSE, so we need to climb the
2055             --  tree to see if we are within the ELSIF part in question.
2056
2057             declare
2058                N : Node_Id;
2059
2060             begin
2061                N := Parent (Var);
2062                while Parent (N) /= Stm loop
2063                   N := Parent (N);
2064
2065                   --  If we fall off the top of the tree, then that's odd, but
2066                   --  perhaps it could occur in some error situation, and the
2067                   --  safest response is simply to assume that the outcome of
2068                   --  the condition is unknown. No point in bombing during an
2069                   --  attempt to optimize things.
2070
2071                   if No (N) then
2072                      return;
2073                   end if;
2074                end loop;
2075
2076                --  Now we have N pointing to a node whose parent is the IF
2077                --  statement in question, so see if is the ELSIF part we want.
2078                --  the THEN statements.
2079
2080                if N = CV then
2081                   Sens := True;
2082
2083                   --  Otherwise we must be in susbequent ELSIF or ELSE part
2084
2085                else
2086                   Sens := False;
2087                end if;
2088             end;
2089
2090          --  Iteration scheme of while loop. The condition is known to be
2091          --  true within the body of the loop.
2092
2093          elsif Nkind (CV) = N_Iteration_Scheme then
2094             declare
2095                Loop_Stmt : constant Node_Id := Parent (CV);
2096
2097             begin
2098                --  Before start of body of loop
2099
2100                if Loc < Sloc (Loop_Stmt) then
2101                   return;
2102
2103                --  After end of LOOP statement
2104
2105                elsif Loc >= Sloc (End_Label (Loop_Stmt)) then
2106                   return;
2107
2108                --  We are within the body of the loop
2109
2110                else
2111                   Sens := True;
2112                end if;
2113             end;
2114
2115          --  All other cases of Current_Value settings
2116
2117          else
2118             return;
2119          end if;
2120
2121          --  If we fall through here, then we have a reportable condition, Sens
2122          --  is True if the condition is true and False if it needs inverting.
2123
2124          Process_Current_Value_Condition (Condition (CV), Sens);
2125       end;
2126    end Get_Current_Value_Condition;
2127
2128    ---------------------------------
2129    -- Has_Controlled_Coextensions --
2130    ---------------------------------
2131
2132    function Has_Controlled_Coextensions (Typ : Entity_Id) return Boolean is
2133       D_Typ : Entity_Id;
2134       Discr : Entity_Id;
2135
2136    begin
2137       --  Only consider record types
2138
2139       if Ekind (Typ) /= E_Record_Type
2140         and then Ekind (Typ) /= E_Record_Subtype
2141       then
2142          return False;
2143       end if;
2144
2145       if Has_Discriminants (Typ) then
2146          Discr := First_Discriminant (Typ);
2147          while Present (Discr) loop
2148             D_Typ := Etype (Discr);
2149
2150             if Ekind (D_Typ) = E_Anonymous_Access_Type
2151               and then
2152                 (Is_Controlled (Directly_Designated_Type (D_Typ))
2153                    or else
2154                  Is_Concurrent_Type (Directly_Designated_Type (D_Typ)))
2155             then
2156                return True;
2157             end if;
2158
2159             Next_Discriminant (Discr);
2160          end loop;
2161       end if;
2162
2163       return False;
2164    end Has_Controlled_Coextensions;
2165
2166    --------------------
2167    -- Homonym_Number --
2168    --------------------
2169
2170    function Homonym_Number (Subp : Entity_Id) return Nat is
2171       Count : Nat;
2172       Hom   : Entity_Id;
2173
2174    begin
2175       Count := 1;
2176       Hom := Homonym (Subp);
2177       while Present (Hom) loop
2178          if Scope (Hom) = Scope (Subp) then
2179             Count := Count + 1;
2180          end if;
2181
2182          Hom := Homonym (Hom);
2183       end loop;
2184
2185       return Count;
2186    end Homonym_Number;
2187
2188    ------------------------------
2189    -- In_Unconditional_Context --
2190    ------------------------------
2191
2192    function In_Unconditional_Context (Node : Node_Id) return Boolean is
2193       P : Node_Id;
2194
2195    begin
2196       P := Node;
2197       while Present (P) loop
2198          case Nkind (P) is
2199             when N_Subprogram_Body =>
2200                return True;
2201
2202             when N_If_Statement =>
2203                return False;
2204
2205             when N_Loop_Statement =>
2206                return False;
2207
2208             when N_Case_Statement =>
2209                return False;
2210
2211             when others =>
2212                P := Parent (P);
2213          end case;
2214       end loop;
2215
2216       return False;
2217    end In_Unconditional_Context;
2218
2219    -------------------
2220    -- Insert_Action --
2221    -------------------
2222
2223    procedure Insert_Action (Assoc_Node : Node_Id; Ins_Action : Node_Id) is
2224    begin
2225       if Present (Ins_Action) then
2226          Insert_Actions (Assoc_Node, New_List (Ins_Action));
2227       end if;
2228    end Insert_Action;
2229
2230    --  Version with check(s) suppressed
2231
2232    procedure Insert_Action
2233      (Assoc_Node : Node_Id; Ins_Action : Node_Id; Suppress : Check_Id)
2234    is
2235    begin
2236       Insert_Actions (Assoc_Node, New_List (Ins_Action), Suppress);
2237    end Insert_Action;
2238
2239    --------------------
2240    -- Insert_Actions --
2241    --------------------
2242
2243    procedure Insert_Actions (Assoc_Node : Node_Id; Ins_Actions : List_Id) is
2244       N : Node_Id;
2245       P : Node_Id;
2246
2247       Wrapped_Node : Node_Id := Empty;
2248
2249    begin
2250       if No (Ins_Actions) or else Is_Empty_List (Ins_Actions) then
2251          return;
2252       end if;
2253
2254       --  Ignore insert of actions from inside default expression in the
2255       --  special preliminary analyze mode. Any insertions at this point
2256       --  have no relevance, since we are only doing the analyze to freeze
2257       --  the types of any static expressions. See section "Handling of
2258       --  Default Expressions" in the spec of package Sem for further details.
2259
2260       if In_Default_Expression then
2261          return;
2262       end if;
2263
2264       --  If the action derives from stuff inside a record, then the actions
2265       --  are attached to the current scope, to be inserted and analyzed on
2266       --  exit from the scope. The reason for this is that we may also
2267       --  be generating freeze actions at the same time, and they must
2268       --  eventually be elaborated in the correct order.
2269
2270       if Is_Record_Type (Current_Scope)
2271         and then not Is_Frozen (Current_Scope)
2272       then
2273          if No (Scope_Stack.Table
2274            (Scope_Stack.Last).Pending_Freeze_Actions)
2275          then
2276             Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions :=
2277               Ins_Actions;
2278          else
2279             Append_List
2280               (Ins_Actions,
2281                Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions);
2282          end if;
2283
2284          return;
2285       end if;
2286
2287       --  We now intend to climb up the tree to find the right point to
2288       --  insert the actions. We start at Assoc_Node, unless this node is
2289       --  a subexpression in which case we start with its parent. We do this
2290       --  for two reasons. First it speeds things up. Second, if Assoc_Node
2291       --  is itself one of the special nodes like N_And_Then, then we assume
2292       --  that an initial request to insert actions for such a node does not
2293       --  expect the actions to get deposited in the node for later handling
2294       --  when the node is expanded, since clearly the node is being dealt
2295       --  with by the caller. Note that in the subexpression case, N is
2296       --  always the child we came from.
2297
2298       --  N_Raise_xxx_Error is an annoying special case, it is a statement
2299       --  if it has type Standard_Void_Type, and a subexpression otherwise.
2300       --  otherwise. Procedure attribute references are also statements.
2301
2302       if Nkind (Assoc_Node) in N_Subexpr
2303         and then (Nkind (Assoc_Node) in N_Raise_xxx_Error
2304                    or else Etype (Assoc_Node) /= Standard_Void_Type)
2305         and then (Nkind (Assoc_Node) /= N_Attribute_Reference
2306                    or else
2307                      not Is_Procedure_Attribute_Name
2308                            (Attribute_Name (Assoc_Node)))
2309       then
2310          P := Assoc_Node;             -- ??? does not agree with above!
2311          N := Parent (Assoc_Node);
2312
2313       --  Non-subexpression case. Note that N is initially Empty in this
2314       --  case (N is only guaranteed Non-Empty in the subexpr case).
2315
2316       else
2317          P := Assoc_Node;
2318          N := Empty;
2319       end if;
2320
2321       --  Capture root of the transient scope
2322
2323       if Scope_Is_Transient then
2324          Wrapped_Node := Node_To_Be_Wrapped;
2325       end if;
2326
2327       loop
2328          pragma Assert (Present (P));
2329
2330          case Nkind (P) is
2331
2332             --  Case of right operand of AND THEN or OR ELSE. Put the actions
2333             --  in the Actions field of the right operand. They will be moved
2334             --  out further when the AND THEN or OR ELSE operator is expanded.
2335             --  Nothing special needs to be done for the left operand since
2336             --  in that case the actions are executed unconditionally.
2337
2338             when N_And_Then | N_Or_Else =>
2339                if N = Right_Opnd (P) then
2340                   if Present (Actions (P)) then
2341                      Insert_List_After_And_Analyze
2342                       (Last (Actions (P)), Ins_Actions);
2343                   else
2344                      Set_Actions (P, Ins_Actions);
2345                      Analyze_List (Actions (P));
2346                   end if;
2347
2348                   return;
2349                end if;
2350
2351             --  Then or Else operand of conditional expression. Add actions to
2352             --  Then_Actions or Else_Actions field as appropriate. The actions
2353             --  will be moved further out when the conditional is expanded.
2354
2355             when N_Conditional_Expression =>
2356                declare
2357                   ThenX : constant Node_Id := Next (First (Expressions (P)));
2358                   ElseX : constant Node_Id := Next (ThenX);
2359
2360                begin
2361                   --  Actions belong to the then expression, temporarily
2362                   --  place them as Then_Actions of the conditional expr.
2363                   --  They will be moved to the proper place later when
2364                   --  the conditional expression is expanded.
2365
2366                   if N = ThenX then
2367                      if Present (Then_Actions (P)) then
2368                         Insert_List_After_And_Analyze
2369                           (Last (Then_Actions (P)), Ins_Actions);
2370                      else
2371                         Set_Then_Actions (P, Ins_Actions);
2372                         Analyze_List (Then_Actions (P));
2373                      end if;
2374
2375                      return;
2376
2377                   --  Actions belong to the else expression, temporarily
2378                   --  place them as Else_Actions of the conditional expr.
2379                   --  They will be moved to the proper place later when
2380                   --  the conditional expression is expanded.
2381
2382                   elsif N = ElseX then
2383                      if Present (Else_Actions (P)) then
2384                         Insert_List_After_And_Analyze
2385                           (Last (Else_Actions (P)), Ins_Actions);
2386                      else
2387                         Set_Else_Actions (P, Ins_Actions);
2388                         Analyze_List (Else_Actions (P));
2389                      end if;
2390
2391                      return;
2392
2393                   --  Actions belong to the condition. In this case they are
2394                   --  unconditionally executed, and so we can continue the
2395                   --  search for the proper insert point.
2396
2397                   else
2398                      null;
2399                   end if;
2400                end;
2401
2402             --  Case of appearing in the condition of a while expression or
2403             --  elsif. We insert the actions into the Condition_Actions field.
2404             --  They will be moved further out when the while loop or elsif
2405             --  is analyzed.
2406
2407             when N_Iteration_Scheme |
2408                  N_Elsif_Part
2409             =>
2410                if N = Condition (P) then
2411                   if Present (Condition_Actions (P)) then
2412                      Insert_List_After_And_Analyze
2413                        (Last (Condition_Actions (P)), Ins_Actions);
2414                   else
2415                      Set_Condition_Actions (P, Ins_Actions);
2416
2417                      --  Set the parent of the insert actions explicitly.
2418                      --  This is not a syntactic field, but we need the
2419                      --  parent field set, in particular so that freeze
2420                      --  can understand that it is dealing with condition
2421                      --  actions, and properly insert the freezing actions.
2422
2423                      Set_Parent (Ins_Actions, P);
2424                      Analyze_List (Condition_Actions (P));
2425                   end if;
2426
2427                   return;
2428                end if;
2429
2430             --  Statements, declarations, pragmas, representation clauses
2431
2432             when
2433                --  Statements
2434
2435                N_Procedure_Call_Statement               |
2436                N_Statement_Other_Than_Procedure_Call    |
2437
2438                --  Pragmas
2439
2440                N_Pragma                                 |
2441
2442                --  Representation_Clause
2443
2444                N_At_Clause                              |
2445                N_Attribute_Definition_Clause            |
2446                N_Enumeration_Representation_Clause      |
2447                N_Record_Representation_Clause           |
2448
2449                --  Declarations
2450
2451                N_Abstract_Subprogram_Declaration        |
2452                N_Entry_Body                             |
2453                N_Exception_Declaration                  |
2454                N_Exception_Renaming_Declaration         |
2455                N_Formal_Abstract_Subprogram_Declaration |
2456                N_Formal_Concrete_Subprogram_Declaration |
2457                N_Formal_Object_Declaration              |
2458                N_Formal_Type_Declaration                |
2459                N_Full_Type_Declaration                  |
2460                N_Function_Instantiation                 |
2461                N_Generic_Function_Renaming_Declaration  |
2462                N_Generic_Package_Declaration            |
2463                N_Generic_Package_Renaming_Declaration   |
2464                N_Generic_Procedure_Renaming_Declaration |
2465                N_Generic_Subprogram_Declaration         |
2466                N_Implicit_Label_Declaration             |
2467                N_Incomplete_Type_Declaration            |
2468                N_Number_Declaration                     |
2469                N_Object_Declaration                     |
2470                N_Object_Renaming_Declaration            |
2471                N_Package_Body                           |
2472                N_Package_Body_Stub                      |
2473                N_Package_Declaration                    |
2474                N_Package_Instantiation                  |
2475                N_Package_Renaming_Declaration           |
2476                N_Private_Extension_Declaration          |
2477                N_Private_Type_Declaration               |
2478                N_Procedure_Instantiation                |
2479                N_Protected_Body                         |
2480                N_Protected_Body_Stub                    |
2481                N_Protected_Type_Declaration             |
2482                N_Single_Task_Declaration                |
2483                N_Subprogram_Body                        |
2484                N_Subprogram_Body_Stub                   |
2485                N_Subprogram_Declaration                 |
2486                N_Subprogram_Renaming_Declaration        |
2487                N_Subtype_Declaration                    |
2488                N_Task_Body                              |
2489                N_Task_Body_Stub                         |
2490                N_Task_Type_Declaration                  |
2491
2492                --  Freeze entity behaves like a declaration or statement
2493
2494                N_Freeze_Entity
2495             =>
2496                --  Do not insert here if the item is not a list member (this
2497                --  happens for example with a triggering statement, and the
2498                --  proper approach is to insert before the entire select).
2499
2500                if not Is_List_Member (P) then
2501                   null;
2502
2503                --  Do not insert if parent of P is an N_Component_Association
2504                --  node (i.e. we are in the context of an N_Aggregate or
2505                --  N_Extension_Aggregate node. In this case we want to insert
2506                --  before the entire aggregate.
2507
2508                elsif Nkind (Parent (P)) = N_Component_Association then
2509                   null;
2510
2511                --  Do not insert if the parent of P is either an N_Variant
2512                --  node or an N_Record_Definition node, meaning in either
2513                --  case that P is a member of a component list, and that
2514                --  therefore the actions should be inserted outside the
2515                --  complete record declaration.
2516
2517                elsif Nkind (Parent (P)) = N_Variant
2518                  or else Nkind (Parent (P)) = N_Record_Definition
2519                then
2520                   null;
2521
2522                --  Do not insert freeze nodes within the loop generated for
2523                --  an aggregate, because they may be elaborated too late for
2524                --  subsequent use in the back end: within a package spec the
2525                --  loop is part of the elaboration procedure and is only
2526                --  elaborated during the second pass.
2527                --  If the loop comes from source, or the entity is local to
2528                --  the loop itself it must remain within.
2529
2530                elsif Nkind (Parent (P)) = N_Loop_Statement
2531                  and then not Comes_From_Source (Parent (P))
2532                  and then Nkind (First (Ins_Actions)) = N_Freeze_Entity
2533                  and then
2534                    Scope (Entity (First (Ins_Actions))) /= Current_Scope
2535                then
2536                   null;
2537
2538                --  Otherwise we can go ahead and do the insertion
2539
2540                elsif P = Wrapped_Node then
2541                   Store_Before_Actions_In_Scope (Ins_Actions);
2542                   return;
2543
2544                else
2545                   Insert_List_Before_And_Analyze (P, Ins_Actions);
2546                   return;
2547                end if;
2548
2549             --  A special case, N_Raise_xxx_Error can act either as a
2550             --  statement or a subexpression. We tell the difference
2551             --  by looking at the Etype. It is set to Standard_Void_Type
2552             --  in the statement case.
2553
2554             when
2555                N_Raise_xxx_Error =>
2556                   if Etype (P) = Standard_Void_Type then
2557                      if  P = Wrapped_Node then
2558                         Store_Before_Actions_In_Scope (Ins_Actions);
2559                      else
2560                         Insert_List_Before_And_Analyze (P, Ins_Actions);
2561                      end if;
2562
2563                      return;
2564
2565                   --  In the subexpression case, keep climbing
2566
2567                   else
2568                      null;
2569                   end if;
2570
2571             --  If a component association appears within a loop created for
2572             --  an array aggregate, attach the actions to the association so
2573             --  they can be subsequently inserted within the loop. For other
2574             --  component associations insert outside of the aggregate. For
2575             --  an association that will generate a loop, its Loop_Actions
2576             --  attribute is already initialized (see exp_aggr.adb).
2577
2578             --  The list of loop_actions can in turn generate additional ones,
2579             --  that are inserted before the associated node. If the associated
2580             --  node is outside the aggregate, the new actions are collected
2581             --  at the end of the loop actions, to respect the order in which
2582             --  they are to be elaborated.
2583
2584             when
2585                N_Component_Association =>
2586                   if Nkind (Parent (P)) = N_Aggregate
2587                     and then Present (Loop_Actions (P))
2588                   then
2589                      if Is_Empty_List (Loop_Actions (P)) then
2590                         Set_Loop_Actions (P, Ins_Actions);
2591                         Analyze_List (Ins_Actions);
2592
2593                      else
2594                         declare
2595                            Decl : Node_Id;
2596
2597                         begin
2598                            --  Check whether these actions were generated
2599                            --  by a declaration that is part of the loop_
2600                            --  actions for the component_association.
2601
2602                            Decl := Assoc_Node;
2603                            while Present (Decl) loop
2604                               exit when Parent (Decl) = P
2605                                 and then Is_List_Member (Decl)
2606                                 and then
2607                                   List_Containing (Decl) = Loop_Actions (P);
2608                               Decl := Parent (Decl);
2609                            end loop;
2610
2611                            if Present (Decl) then
2612                               Insert_List_Before_And_Analyze
2613                                 (Decl, Ins_Actions);
2614                            else
2615                               Insert_List_After_And_Analyze
2616                                 (Last (Loop_Actions (P)), Ins_Actions);
2617                            end if;
2618                         end;
2619                      end if;
2620
2621                      return;
2622
2623                   else
2624                      null;
2625                   end if;
2626
2627             --  Another special case, an attribute denoting a procedure call
2628
2629             when
2630                N_Attribute_Reference =>
2631                   if Is_Procedure_Attribute_Name (Attribute_Name (P)) then
2632                      if P = Wrapped_Node then
2633                         Store_Before_Actions_In_Scope (Ins_Actions);
2634                      else
2635                         Insert_List_Before_And_Analyze (P, Ins_Actions);
2636                      end if;
2637
2638                      return;
2639
2640                   --  In the subexpression case, keep climbing
2641
2642                   else
2643                      null;
2644                   end if;
2645
2646             --  For all other node types, keep climbing tree
2647
2648             when
2649                N_Abortable_Part                         |
2650                N_Accept_Alternative                     |
2651                N_Access_Definition                      |
2652                N_Access_Function_Definition             |
2653                N_Access_Procedure_Definition            |
2654                N_Access_To_Object_Definition            |
2655                N_Aggregate                              |
2656                N_Allocator                              |
2657                N_Case_Statement_Alternative             |
2658                N_Character_Literal                      |
2659                N_Compilation_Unit                       |
2660                N_Compilation_Unit_Aux                   |
2661                N_Component_Clause                       |
2662                N_Component_Declaration                  |
2663                N_Component_Definition                   |
2664                N_Component_List                         |
2665                N_Constrained_Array_Definition           |
2666                N_Decimal_Fixed_Point_Definition         |
2667                N_Defining_Character_Literal             |
2668                N_Defining_Identifier                    |
2669                N_Defining_Operator_Symbol               |
2670                N_Defining_Program_Unit_Name             |
2671                N_Delay_Alternative                      |
2672                N_Delta_Constraint                       |
2673                N_Derived_Type_Definition                |
2674                N_Designator                             |
2675                N_Digits_Constraint                      |
2676                N_Discriminant_Association               |
2677                N_Discriminant_Specification             |
2678                N_Empty                                  |
2679                N_Entry_Body_Formal_Part                 |
2680                N_Entry_Call_Alternative                 |
2681                N_Entry_Declaration                      |
2682                N_Entry_Index_Specification              |
2683                N_Enumeration_Type_Definition            |
2684                N_Error                                  |
2685                N_Exception_Handler                      |
2686                N_Expanded_Name                          |
2687                N_Explicit_Dereference                   |
2688                N_Extension_Aggregate                    |
2689                N_Floating_Point_Definition              |
2690                N_Formal_Decimal_Fixed_Point_Definition  |
2691                N_Formal_Derived_Type_Definition         |
2692                N_Formal_Discrete_Type_Definition        |
2693                N_Formal_Floating_Point_Definition       |
2694                N_Formal_Modular_Type_Definition         |
2695                N_Formal_Ordinary_Fixed_Point_Definition |
2696                N_Formal_Package_Declaration             |
2697                N_Formal_Private_Type_Definition         |
2698                N_Formal_Signed_Integer_Type_Definition  |
2699                N_Function_Call                          |
2700                N_Function_Specification                 |
2701                N_Generic_Association                    |
2702                N_Handled_Sequence_Of_Statements         |
2703                N_Identifier                             |
2704                N_In                                     |
2705                N_Index_Or_Discriminant_Constraint       |
2706                N_Indexed_Component                      |
2707                N_Integer_Literal                        |
2708                N_Itype_Reference                        |
2709                N_Label                                  |
2710                N_Loop_Parameter_Specification           |
2711                N_Mod_Clause                             |
2712                N_Modular_Type_Definition                |
2713                N_Not_In                                 |
2714                N_Null                                   |
2715                N_Op_Abs                                 |
2716                N_Op_Add                                 |
2717                N_Op_And                                 |
2718                N_Op_Concat                              |
2719                N_Op_Divide                              |
2720                N_Op_Eq                                  |
2721                N_Op_Expon                               |
2722                N_Op_Ge                                  |
2723                N_Op_Gt                                  |
2724                N_Op_Le                                  |
2725                N_Op_Lt                                  |
2726                N_Op_Minus                               |
2727                N_Op_Mod                                 |
2728                N_Op_Multiply                            |
2729                N_Op_Ne                                  |
2730                N_Op_Not                                 |
2731                N_Op_Or                                  |
2732                N_Op_Plus                                |
2733                N_Op_Rem                                 |
2734                N_Op_Rotate_Left                         |
2735                N_Op_Rotate_Right                        |
2736                N_Op_Shift_Left                          |
2737                N_Op_Shift_Right                         |
2738                N_Op_Shift_Right_Arithmetic              |
2739                N_Op_Subtract                            |
2740                N_Op_Xor                                 |
2741                N_Operator_Symbol                        |
2742                N_Ordinary_Fixed_Point_Definition        |
2743                N_Others_Choice                          |
2744                N_Package_Specification                  |
2745                N_Parameter_Association                  |
2746                N_Parameter_Specification                |
2747                N_Pop_Constraint_Error_Label             |
2748                N_Pop_Program_Error_Label                |
2749                N_Pop_Storage_Error_Label                |
2750                N_Pragma_Argument_Association            |
2751                N_Procedure_Specification                |
2752                N_Protected_Definition                   |
2753                N_Push_Constraint_Error_Label            |
2754                N_Push_Program_Error_Label               |
2755                N_Push_Storage_Error_Label               |
2756                N_Qualified_Expression                   |
2757                N_Range                                  |
2758                N_Range_Constraint                       |
2759                N_Real_Literal                           |
2760                N_Real_Range_Specification               |
2761                N_Record_Definition                      |
2762                N_Reference                              |
2763                N_Selected_Component                     |
2764                N_Signed_Integer_Type_Definition         |
2765                N_Single_Protected_Declaration           |
2766                N_Slice                                  |
2767                N_String_Literal                         |
2768                N_Subprogram_Info                        |
2769                N_Subtype_Indication                     |
2770                N_Subunit                                |
2771                N_Task_Definition                        |
2772                N_Terminate_Alternative                  |
2773                N_Triggering_Alternative                 |
2774                N_Type_Conversion                        |
2775                N_Unchecked_Expression                   |
2776                N_Unchecked_Type_Conversion              |
2777                N_Unconstrained_Array_Definition         |
2778                N_Unused_At_End                          |
2779                N_Unused_At_Start                        |
2780                N_Use_Package_Clause                     |
2781                N_Use_Type_Clause                        |
2782                N_Variant                                |
2783                N_Variant_Part                           |
2784                N_Validate_Unchecked_Conversion          |
2785                N_With_Clause
2786             =>
2787                null;
2788
2789          end case;
2790
2791          --  Make sure that inserted actions stay in the transient scope
2792
2793          if P = Wrapped_Node then
2794             Store_Before_Actions_In_Scope (Ins_Actions);
2795             return;
2796          end if;
2797
2798          --  If we fall through above tests, keep climbing tree
2799
2800          N := P;
2801
2802          if Nkind (Parent (N)) = N_Subunit then
2803
2804             --  This is the proper body corresponding to a stub. Insertion
2805             --  must be done at the point of the stub, which is in the decla-
2806             --  tive part of the parent unit.
2807
2808             P := Corresponding_Stub (Parent (N));
2809
2810          else
2811             P := Parent (N);
2812          end if;
2813       end loop;
2814    end Insert_Actions;
2815
2816    --  Version with check(s) suppressed
2817
2818    procedure Insert_Actions
2819      (Assoc_Node  : Node_Id;
2820       Ins_Actions : List_Id;
2821       Suppress    : Check_Id)
2822    is
2823    begin
2824       if Suppress = All_Checks then
2825          declare
2826             Svg : constant Suppress_Array := Scope_Suppress;
2827          begin
2828             Scope_Suppress := (others => True);
2829             Insert_Actions (Assoc_Node, Ins_Actions);
2830             Scope_Suppress := Svg;
2831          end;
2832
2833       else
2834          declare
2835             Svg : constant Boolean := Scope_Suppress (Suppress);
2836          begin
2837             Scope_Suppress (Suppress) := True;
2838             Insert_Actions (Assoc_Node, Ins_Actions);
2839             Scope_Suppress (Suppress) := Svg;
2840          end;
2841       end if;
2842    end Insert_Actions;
2843
2844    --------------------------
2845    -- Insert_Actions_After --
2846    --------------------------
2847
2848    procedure Insert_Actions_After
2849      (Assoc_Node  : Node_Id;
2850       Ins_Actions : List_Id)
2851    is
2852    begin
2853       if Scope_Is_Transient
2854         and then Assoc_Node = Node_To_Be_Wrapped
2855       then
2856          Store_After_Actions_In_Scope (Ins_Actions);
2857       else
2858          Insert_List_After_And_Analyze (Assoc_Node, Ins_Actions);
2859       end if;
2860    end Insert_Actions_After;
2861
2862    ---------------------------------
2863    -- Insert_Library_Level_Action --
2864    ---------------------------------
2865
2866    procedure Insert_Library_Level_Action (N : Node_Id) is
2867       Aux : constant Node_Id := Aux_Decls_Node (Cunit (Main_Unit));
2868
2869    begin
2870       Push_Scope (Cunit_Entity (Main_Unit));
2871       --  ??? should this be Current_Sem_Unit instead of Main_Unit?
2872
2873       if No (Actions (Aux)) then
2874          Set_Actions (Aux, New_List (N));
2875       else
2876          Append (N, Actions (Aux));
2877       end if;
2878
2879       Analyze (N);
2880       Pop_Scope;
2881    end Insert_Library_Level_Action;
2882
2883    ----------------------------------
2884    -- Insert_Library_Level_Actions --
2885    ----------------------------------
2886
2887    procedure Insert_Library_Level_Actions (L : List_Id) is
2888       Aux : constant Node_Id := Aux_Decls_Node (Cunit (Main_Unit));
2889
2890    begin
2891       if Is_Non_Empty_List (L) then
2892          Push_Scope (Cunit_Entity (Main_Unit));
2893          --  ??? should this be Current_Sem_Unit instead of Main_Unit?
2894
2895          if No (Actions (Aux)) then
2896             Set_Actions (Aux, L);
2897             Analyze_List (L);
2898          else
2899             Insert_List_After_And_Analyze (Last (Actions (Aux)), L);
2900          end if;
2901
2902          Pop_Scope;
2903       end if;
2904    end Insert_Library_Level_Actions;
2905
2906    ----------------------
2907    -- Inside_Init_Proc --
2908    ----------------------
2909
2910    function Inside_Init_Proc return Boolean is
2911       S : Entity_Id;
2912
2913    begin
2914       S := Current_Scope;
2915       while Present (S)
2916         and then S /= Standard_Standard
2917       loop
2918          if Is_Init_Proc (S) then
2919             return True;
2920          else
2921             S := Scope (S);
2922          end if;
2923       end loop;
2924
2925       return False;
2926    end Inside_Init_Proc;
2927
2928    ----------------------------
2929    -- Is_All_Null_Statements --
2930    ----------------------------
2931
2932    function Is_All_Null_Statements (L : List_Id) return Boolean is
2933       Stm : Node_Id;
2934
2935    begin
2936       Stm := First (L);
2937       while Present (Stm) loop
2938          if Nkind (Stm) /= N_Null_Statement then
2939             return False;
2940          end if;
2941
2942          Next (Stm);
2943       end loop;
2944
2945       return True;
2946    end Is_All_Null_Statements;
2947
2948    ----------------------------------
2949    -- Is_Library_Level_Tagged_Type --
2950    ----------------------------------
2951
2952    function Is_Library_Level_Tagged_Type (Typ : Entity_Id) return Boolean is
2953    begin
2954       return Is_Tagged_Type (Typ)
2955         and then Is_Library_Level_Entity (Typ);
2956    end Is_Library_Level_Tagged_Type;
2957
2958    -----------------------------------------
2959    -- Is_Predefined_Dispatching_Operation --
2960    -----------------------------------------
2961
2962    function Is_Predefined_Dispatching_Operation (E : Entity_Id) return Boolean
2963    is
2964       TSS_Name : TSS_Name_Type;
2965
2966    begin
2967       if not Is_Dispatching_Operation (E) then
2968          return False;
2969       end if;
2970
2971       Get_Name_String (Chars (E));
2972
2973       if Name_Len > TSS_Name_Type'Last then
2974          TSS_Name := TSS_Name_Type (Name_Buffer (Name_Len - TSS_Name'Length + 1
2975                                      .. Name_Len));
2976          if Chars (E)        = Name_uSize
2977            or else Chars (E) = Name_uAlignment
2978            or else TSS_Name  = TSS_Stream_Read
2979            or else TSS_Name  = TSS_Stream_Write
2980            or else TSS_Name  = TSS_Stream_Input
2981            or else TSS_Name  = TSS_Stream_Output
2982            or else
2983              (Chars (E) = Name_Op_Eq
2984                 and then Etype (First_Entity (E)) = Etype (Last_Entity (E)))
2985            or else Chars (E) = Name_uAssign
2986            or else TSS_Name  = TSS_Deep_Adjust
2987            or else TSS_Name  = TSS_Deep_Finalize
2988            or else (Ada_Version >= Ada_05
2989              and then (Chars (E) = Name_uDisp_Asynchronous_Select
2990                or else Chars (E) = Name_uDisp_Conditional_Select
2991                or else Chars (E) = Name_uDisp_Get_Prim_Op_Kind
2992                or else Chars (E) = Name_uDisp_Get_Task_Id
2993                or else Chars (E) = Name_uDisp_Timed_Select))
2994          then
2995             return True;
2996          end if;
2997       end if;
2998
2999       return False;
3000    end Is_Predefined_Dispatching_Operation;
3001
3002    ----------------------------------
3003    -- Is_Possibly_Unaligned_Object --
3004    ----------------------------------
3005
3006    function Is_Possibly_Unaligned_Object (N : Node_Id) return Boolean is
3007       T  : constant Entity_Id := Etype (N);
3008
3009    begin
3010       --  If renamed object, apply test to underlying object
3011
3012       if Is_Entity_Name (N)
3013         and then Is_Object (Entity (N))
3014         and then Present (Renamed_Object (Entity (N)))
3015       then
3016          return Is_Possibly_Unaligned_Object (Renamed_Object (Entity (N)));
3017       end if;
3018
3019       --  Tagged and controlled types and aliased types are always aligned,
3020       --  as are concurrent types.
3021
3022       if Is_Aliased (T)
3023         or else Has_Controlled_Component (T)
3024         or else Is_Concurrent_Type (T)
3025         or else Is_Tagged_Type (T)
3026         or else Is_Controlled (T)
3027       then
3028          return False;
3029       end if;
3030
3031       --  If this is an element of a packed array, may be unaligned
3032
3033       if Is_Ref_To_Bit_Packed_Array (N) then
3034          return True;
3035       end if;
3036
3037       --  Case of component reference
3038
3039       if Nkind (N) = N_Selected_Component then
3040          declare
3041             P : constant Node_Id   := Prefix (N);
3042             C : constant Entity_Id := Entity (Selector_Name (N));
3043             M : Nat;
3044             S : Nat;
3045
3046          begin
3047             --  If component reference is for an array with non-static bounds,
3048             --  then it is always aligned: we can only process unaligned
3049             --  arrays with static bounds (more accurately bounds known at
3050             --  compile time).
3051
3052             if Is_Array_Type (T)
3053               and then not Compile_Time_Known_Bounds (T)
3054             then
3055                return False;
3056             end if;
3057
3058             --  If component is aliased, it is definitely properly aligned
3059
3060             if Is_Aliased (C) then
3061                return False;
3062             end if;
3063
3064             --  If component is for a type implemented as a scalar, and the
3065             --  record is packed, and the component is other than the first
3066             --  component of the record, then the component may be unaligned.
3067
3068             if Is_Packed (Etype (P))
3069               and then Represented_As_Scalar (Etype (C))
3070               and then First_Entity (Scope (C)) /= C
3071             then
3072                return True;
3073             end if;
3074
3075             --  Compute maximum possible alignment for T
3076
3077             --  If alignment is known, then that settles things
3078
3079             if Known_Alignment (T) then
3080                M := UI_To_Int (Alignment (T));
3081
3082             --  If alignment is not known, tentatively set max alignment
3083
3084             else
3085                M := Ttypes.Maximum_Alignment;
3086
3087                --  We can reduce this if the Esize is known since the default
3088                --  alignment will never be more than the smallest power of 2
3089                --  that does not exceed this Esize value.
3090
3091                if Known_Esize (T) then
3092                   S := UI_To_Int (Esize (T));
3093
3094                   while (M / 2) >= S loop
3095                      M := M / 2;
3096                   end loop;
3097                end if;
3098             end if;
3099
3100             --  If the component reference is for a record that has a specified
3101             --  alignment, and we either know it is too small, or cannot tell,
3102             --  then the component may be unaligned
3103
3104             if Known_Alignment (Etype (P))
3105               and then Alignment (Etype (P)) < Ttypes.Maximum_Alignment
3106               and then M > Alignment (Etype (P))
3107             then
3108                return True;
3109             end if;
3110
3111             --  Case of component clause present which may specify an
3112             --  unaligned position.
3113
3114             if Present (Component_Clause (C)) then
3115
3116                --  Otherwise we can do a test to make sure that the actual
3117                --  start position in the record, and the length, are both
3118                --  consistent with the required alignment. If not, we know
3119                --  that we are unaligned.
3120
3121                declare
3122                   Align_In_Bits : constant Nat := M * System_Storage_Unit;
3123                begin
3124                   if Component_Bit_Offset (C) mod Align_In_Bits /= 0
3125                     or else Esize (C) mod Align_In_Bits /= 0
3126                   then
3127                      return True;
3128                   end if;
3129                end;
3130             end if;
3131
3132             --  Otherwise, for a component reference, test prefix
3133
3134             return Is_Possibly_Unaligned_Object (P);
3135          end;
3136
3137       --  If not a component reference, must be aligned
3138
3139       else
3140          return False;
3141       end if;
3142    end Is_Possibly_Unaligned_Object;
3143
3144    ---------------------------------
3145    -- Is_Possibly_Unaligned_Slice --
3146    ---------------------------------
3147
3148    function Is_Possibly_Unaligned_Slice (N : Node_Id) return Boolean is
3149    begin
3150       --  Go to renamed object
3151
3152       if Is_Entity_Name (N)
3153         and then Is_Object (Entity (N))
3154         and then Present (Renamed_Object (Entity (N)))
3155       then
3156          return Is_Possibly_Unaligned_Slice (Renamed_Object (Entity (N)));
3157       end if;
3158
3159       --  The reference must be a slice
3160
3161       if Nkind (N) /= N_Slice then
3162          return False;
3163       end if;
3164
3165       --  Always assume the worst for a nested record component with a
3166       --  component clause, which gigi/gcc does not appear to handle well.
3167       --  It is not clear why this special test is needed at all ???
3168
3169       if Nkind (Prefix (N)) = N_Selected_Component
3170         and then Nkind (Prefix (Prefix (N))) = N_Selected_Component
3171         and then
3172           Present (Component_Clause (Entity (Selector_Name (Prefix (N)))))
3173       then
3174          return True;
3175       end if;
3176
3177       --  We only need to worry if the target has strict alignment
3178
3179       if not Target_Strict_Alignment then
3180          return False;
3181       end if;
3182
3183       --  If it is a slice, then look at the array type being sliced
3184
3185       declare
3186          Sarr : constant Node_Id := Prefix (N);
3187          --  Prefix of the slice, i.e. the array being sliced
3188
3189          Styp : constant Entity_Id := Etype (Prefix (N));
3190          --  Type of the array being sliced
3191
3192          Pref : Node_Id;
3193          Ptyp : Entity_Id;
3194
3195       begin
3196          --  The problems arise if the array object that is being sliced
3197          --  is a component of a record or array, and we cannot guarantee
3198          --  the alignment of the array within its containing object.
3199
3200          --  To investigate this, we look at successive prefixes to see
3201          --  if we have a worrisome indexed or selected component.
3202
3203          Pref := Sarr;
3204          loop
3205             --  Case of array is part of an indexed component reference
3206
3207             if Nkind (Pref) = N_Indexed_Component then
3208                Ptyp := Etype (Prefix (Pref));
3209
3210                --  The only problematic case is when the array is packed,
3211                --  in which case we really know nothing about the alignment
3212                --  of individual components.
3213
3214                if Is_Bit_Packed_Array (Ptyp) then
3215                   return True;
3216                end if;
3217
3218             --  Case of array is part of a selected component reference
3219
3220             elsif Nkind (Pref) = N_Selected_Component then
3221                Ptyp := Etype (Prefix (Pref));
3222
3223                --  We are definitely in trouble if the record in question
3224                --  has an alignment, and either we know this alignment is
3225                --  inconsistent with the alignment of the slice, or we
3226                --  don't know what the alignment of the slice should be.
3227
3228                if Known_Alignment (Ptyp)
3229                  and then (Unknown_Alignment (Styp)
3230                              or else Alignment (Styp) > Alignment (Ptyp))
3231                then
3232                   return True;
3233                end if;
3234
3235                --  We are in potential trouble if the record type is packed.
3236                --  We could special case when we know that the array is the
3237                --  first component, but that's not such a simple case ???
3238
3239                if Is_Packed (Ptyp) then
3240                   return True;
3241                end if;
3242
3243                --  We are in trouble if there is a component clause, and
3244                --  either we do not know the alignment of the slice, or
3245                --  the alignment of the slice is inconsistent with the
3246                --  bit position specified by the component clause.
3247
3248                declare
3249                   Field : constant Entity_Id := Entity (Selector_Name (Pref));
3250                begin
3251                   if Present (Component_Clause (Field))
3252                     and then
3253                       (Unknown_Alignment (Styp)
3254                         or else
3255                          (Component_Bit_Offset (Field) mod
3256                            (System_Storage_Unit * Alignment (Styp))) /= 0)
3257                   then
3258                      return True;
3259                   end if;
3260                end;
3261
3262             --  For cases other than selected or indexed components we
3263             --  know we are OK, since no issues arise over alignment.
3264
3265             else
3266                return False;
3267             end if;
3268
3269             --  We processed an indexed component or selected component
3270             --  reference that looked safe, so keep checking prefixes.
3271
3272             Pref := Prefix (Pref);
3273          end loop;
3274       end;
3275    end Is_Possibly_Unaligned_Slice;
3276
3277    --------------------------------
3278    -- Is_Ref_To_Bit_Packed_Array --
3279    --------------------------------
3280
3281    function Is_Ref_To_Bit_Packed_Array (N : Node_Id) return Boolean is
3282       Result : Boolean;
3283       Expr   : Node_Id;
3284
3285    begin
3286       if Is_Entity_Name (N)
3287         and then Is_Object (Entity (N))
3288         and then Present (Renamed_Object (Entity (N)))
3289       then
3290          return Is_Ref_To_Bit_Packed_Array (Renamed_Object (Entity (N)));
3291       end if;
3292
3293       if Nkind (N) = N_Indexed_Component
3294            or else
3295          Nkind (N) = N_Selected_Component
3296       then
3297          if Is_Bit_Packed_Array (Etype (Prefix (N))) then
3298             Result := True;
3299          else
3300             Result := Is_Ref_To_Bit_Packed_Array (Prefix (N));
3301          end if;
3302
3303          if Result and then Nkind (N) = N_Indexed_Component then
3304             Expr := First (Expressions (N));
3305             while Present (Expr) loop
3306                Force_Evaluation (Expr);
3307                Next (Expr);
3308             end loop;
3309          end if;
3310
3311          return Result;
3312
3313       else
3314          return False;
3315       end if;
3316    end Is_Ref_To_Bit_Packed_Array;
3317
3318    --------------------------------
3319    -- Is_Ref_To_Bit_Packed_Slice --
3320    --------------------------------
3321
3322    function Is_Ref_To_Bit_Packed_Slice (N : Node_Id) return Boolean is
3323    begin
3324       if Nkind (N) = N_Type_Conversion then
3325          return Is_Ref_To_Bit_Packed_Slice (Expression (N));
3326
3327       elsif Is_Entity_Name (N)
3328         and then Is_Object (Entity (N))
3329         and then Present (Renamed_Object (Entity (N)))
3330       then
3331          return Is_Ref_To_Bit_Packed_Slice (Renamed_Object (Entity (N)));
3332
3333       elsif Nkind (N) = N_Slice
3334         and then Is_Bit_Packed_Array (Etype (Prefix (N)))
3335       then
3336          return True;
3337
3338       elsif Nkind (N) = N_Indexed_Component
3339            or else
3340          Nkind (N) = N_Selected_Component
3341       then
3342          return Is_Ref_To_Bit_Packed_Slice (Prefix (N));
3343
3344       else
3345          return False;
3346       end if;
3347    end Is_Ref_To_Bit_Packed_Slice;
3348
3349    -----------------------
3350    -- Is_Renamed_Object --
3351    -----------------------
3352
3353    function Is_Renamed_Object (N : Node_Id) return Boolean is
3354       Pnod : constant Node_Id   := Parent (N);
3355       Kind : constant Node_Kind := Nkind (Pnod);
3356
3357    begin
3358       if Kind = N_Object_Renaming_Declaration then
3359          return True;
3360
3361       elsif Kind = N_Indexed_Component
3362         or else Kind = N_Selected_Component
3363       then
3364          return Is_Renamed_Object (Pnod);
3365
3366       else
3367          return False;
3368       end if;
3369    end Is_Renamed_Object;
3370
3371    ----------------------------
3372    -- Is_Untagged_Derivation --
3373    ----------------------------
3374
3375    function Is_Untagged_Derivation (T : Entity_Id) return Boolean is
3376    begin
3377       return (not Is_Tagged_Type (T) and then Is_Derived_Type (T))
3378                or else
3379              (Is_Private_Type (T) and then Present (Full_View (T))
3380                and then not Is_Tagged_Type (Full_View (T))
3381                and then Is_Derived_Type (Full_View (T))
3382                and then Etype (Full_View (T)) /= T);
3383    end Is_Untagged_Derivation;
3384
3385    --------------------
3386    -- Kill_Dead_Code --
3387    --------------------
3388
3389    procedure Kill_Dead_Code (N : Node_Id; Warn : Boolean := False) is
3390    begin
3391       if Present (N) then
3392          Remove_Warning_Messages (N);
3393
3394          if Warn then
3395             Error_Msg_F
3396               ("?this code can never be executed and has been deleted!", N);
3397          end if;
3398
3399          --  Recurse into block statements and bodies to process declarations
3400          --  and statements
3401
3402          if Nkind (N) = N_Block_Statement
3403            or else Nkind (N) = N_Subprogram_Body
3404            or else Nkind (N) = N_Package_Body
3405          then
3406             Kill_Dead_Code
3407               (Declarations (N), False);
3408             Kill_Dead_Code
3409               (Statements (Handled_Statement_Sequence (N)));
3410
3411             if Nkind (N) = N_Subprogram_Body then
3412                Set_Is_Eliminated (Defining_Entity (N));
3413             end if;
3414
3415          elsif Nkind (N) = N_Package_Declaration then
3416             Kill_Dead_Code (Visible_Declarations (Specification (N)));
3417             Kill_Dead_Code (Private_Declarations (Specification (N)));
3418
3419             declare
3420                E : Entity_Id := First_Entity (Defining_Entity (N));
3421             begin
3422                while Present (E) loop
3423                   if Ekind (E) = E_Operator then
3424                      Set_Is_Eliminated (E);
3425                   end if;
3426
3427                   Next_Entity (E);
3428                end loop;
3429             end;
3430
3431          --  Recurse into composite statement to kill individual statements,
3432          --  in particular instantiations.
3433
3434          elsif Nkind (N) = N_If_Statement then
3435             Kill_Dead_Code (Then_Statements (N));
3436             Kill_Dead_Code (Elsif_Parts (N));
3437             Kill_Dead_Code (Else_Statements (N));
3438
3439          elsif Nkind (N) = N_Loop_Statement then
3440             Kill_Dead_Code (Statements (N));
3441
3442          elsif Nkind (N) = N_Case_Statement then
3443             declare
3444                Alt : Node_Id;
3445             begin
3446                Alt := First (Alternatives (N));
3447                while Present (Alt) loop
3448                   Kill_Dead_Code (Statements (Alt));
3449                   Next (Alt);
3450                end loop;
3451             end;
3452
3453          elsif Nkind (N) = N_Case_Statement_Alternative then
3454             Kill_Dead_Code (Statements (N));
3455
3456          --  Deal with dead instances caused by deleting instantiations
3457
3458          elsif Nkind (N) in N_Generic_Instantiation then
3459             Remove_Dead_Instance (N);
3460          end if;
3461
3462          Delete_Tree (N);
3463       end if;
3464    end Kill_Dead_Code;
3465
3466    --  Case where argument is a list of nodes to be killed
3467
3468    procedure Kill_Dead_Code (L : List_Id; Warn : Boolean := False) is
3469       N : Node_Id;
3470       W : Boolean;
3471    begin
3472       W := Warn;
3473       if Is_Non_Empty_List (L) then
3474          loop
3475             N := Remove_Head (L);
3476             exit when No (N);
3477             Kill_Dead_Code (N, W);
3478             W := False;
3479          end loop;
3480       end if;
3481    end Kill_Dead_Code;
3482
3483    ------------------------
3484    -- Known_Non_Negative --
3485    ------------------------
3486
3487    function Known_Non_Negative (Opnd : Node_Id) return Boolean is
3488    begin
3489       if Is_OK_Static_Expression (Opnd)
3490         and then Expr_Value (Opnd) >= 0
3491       then
3492          return True;
3493
3494       else
3495          declare
3496             Lo : constant Node_Id := Type_Low_Bound (Etype (Opnd));
3497
3498          begin
3499             return
3500               Is_OK_Static_Expression (Lo) and then Expr_Value (Lo) >= 0;
3501          end;
3502       end if;
3503    end Known_Non_Negative;
3504
3505    --------------------
3506    -- Known_Non_Null --
3507    --------------------
3508
3509    function Known_Non_Null (N : Node_Id) return Boolean is
3510    begin
3511       --  Checks for case where N is an entity reference
3512
3513       if Is_Entity_Name (N) and then Present (Entity (N)) then
3514          declare
3515             E   : constant Entity_Id := Entity (N);
3516             Op  : Node_Kind;
3517             Val : Node_Id;
3518
3519          begin
3520             --  First check if we are in decisive conditional
3521
3522             Get_Current_Value_Condition (N, Op, Val);
3523
3524             if Known_Null (Val) then
3525                if Op = N_Op_Eq then
3526                   return False;
3527                elsif Op = N_Op_Ne then
3528                   return True;
3529                end if;
3530             end if;
3531
3532             --  If OK to do replacement, test Is_Known_Non_Null flag
3533
3534             if OK_To_Do_Constant_Replacement (E) then
3535                return Is_Known_Non_Null (E);
3536
3537             --  Otherwise if not safe to do replacement, then say so
3538
3539             else
3540                return False;
3541             end if;
3542          end;
3543
3544       --  True if access attribute
3545
3546       elsif Nkind (N) = N_Attribute_Reference
3547         and then (Attribute_Name (N) = Name_Access
3548                     or else
3549                   Attribute_Name (N) = Name_Unchecked_Access
3550                     or else
3551                   Attribute_Name (N) = Name_Unrestricted_Access)
3552       then
3553          return True;
3554
3555       --  True if allocator
3556
3557       elsif Nkind (N) = N_Allocator then
3558          return True;
3559
3560       --  For a conversion, true if expression is known non-null
3561
3562       elsif Nkind (N) = N_Type_Conversion then
3563          return Known_Non_Null (Expression (N));
3564
3565       --  Above are all cases where the value could be determined to be
3566       --  non-null. In all other cases, we don't know, so return False.
3567
3568       else
3569          return False;
3570       end if;
3571    end Known_Non_Null;
3572
3573    ----------------
3574    -- Known_Null --
3575    ----------------
3576
3577    function Known_Null (N : Node_Id) return Boolean is
3578    begin
3579       --  Checks for case where N is an entity reference
3580
3581       if Is_Entity_Name (N) and then Present (Entity (N)) then
3582          declare
3583             E   : constant Entity_Id := Entity (N);
3584             Op  : Node_Kind;
3585             Val : Node_Id;
3586
3587          begin
3588             --  Constant null value is for sure null
3589
3590             if Ekind (E) = E_Constant
3591               and then Known_Null (Constant_Value (E))
3592             then
3593                return True;
3594             end if;
3595
3596             --  First check if we are in decisive conditional
3597
3598             Get_Current_Value_Condition (N, Op, Val);
3599
3600             if Known_Null (Val) then
3601                if Op = N_Op_Eq then
3602                   return True;
3603                elsif Op = N_Op_Ne then
3604                   return False;
3605                end if;
3606             end if;
3607
3608             --  If OK to do replacement, test Is_Known_Null flag
3609
3610             if OK_To_Do_Constant_Replacement (E) then
3611                return Is_Known_Null (E);
3612
3613             --  Otherwise if not safe to do replacement, then say so
3614
3615             else
3616                return False;
3617             end if;
3618          end;
3619
3620       --  True if explicit reference to null
3621
3622       elsif Nkind (N) = N_Null then
3623          return True;
3624
3625       --  For a conversion, true if expression is known null
3626
3627       elsif Nkind (N) = N_Type_Conversion then
3628          return Known_Null (Expression (N));
3629
3630       --  Above are all cases where the value could be determined to be null.
3631       --  In all other cases, we don't know, so return False.
3632
3633       else
3634          return False;
3635       end if;
3636    end Known_Null;
3637
3638    -----------------------------
3639    -- Make_CW_Equivalent_Type --
3640    -----------------------------
3641
3642    --  Create a record type used as an equivalent of any member
3643    --  of the class which takes its size from exp.
3644
3645    --  Generate the following code:
3646
3647    --   type Equiv_T is record
3648    --     _parent :  T (List of discriminant constaints taken from Exp);
3649    --     Ext__50 : Storage_Array (1 .. (Exp'size - Typ'object_size)/8);
3650    --   end Equiv_T;
3651    --
3652    --   ??? Note that this type does not guarantee same alignment as all
3653    --   derived types
3654
3655    function Make_CW_Equivalent_Type
3656      (T : Entity_Id;
3657       E : Node_Id) return Entity_Id
3658    is
3659       Loc         : constant Source_Ptr := Sloc (E);
3660       Root_Typ    : constant Entity_Id  := Root_Type (T);
3661       List_Def    : constant List_Id    := Empty_List;
3662       Comp_List   : constant List_Id    := New_List;
3663       Equiv_Type  : Entity_Id;
3664       Range_Type  : Entity_Id;
3665       Str_Type    : Entity_Id;
3666       Constr_Root : Entity_Id;
3667       Sizexpr     : Node_Id;
3668
3669    begin
3670       if not Has_Discriminants (Root_Typ) then
3671          Constr_Root := Root_Typ;
3672       else
3673          Constr_Root :=
3674            Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
3675
3676          --  subtype cstr__n is T (List of discr constraints taken from Exp)
3677
3678          Append_To (List_Def,
3679            Make_Subtype_Declaration (Loc,
3680              Defining_Identifier => Constr_Root,
3681                Subtype_Indication =>
3682                  Make_Subtype_From_Expr (E, Root_Typ)));
3683       end if;
3684
3685       --  Generate the range subtype declaration
3686
3687       Range_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('G'));
3688
3689       if not Is_Interface (Root_Typ) then
3690          --  subtype rg__xx is
3691          --    Storage_Offset range 1 .. (Expr'size - typ'size) / Storage_Unit
3692
3693          Sizexpr :=
3694            Make_Op_Subtract (Loc,
3695              Left_Opnd =>
3696                Make_Attribute_Reference (Loc,
3697                  Prefix =>
3698                    OK_Convert_To (T, Duplicate_Subexpr_No_Checks (E)),
3699                  Attribute_Name => Name_Size),
3700              Right_Opnd =>
3701                Make_Attribute_Reference (Loc,
3702                  Prefix => New_Reference_To (Constr_Root, Loc),
3703                  Attribute_Name => Name_Object_Size));
3704       else
3705          --  subtype rg__xx is
3706          --    Storage_Offset range 1 .. Expr'size / Storage_Unit
3707
3708          Sizexpr :=
3709            Make_Attribute_Reference (Loc,
3710              Prefix =>
3711                OK_Convert_To (T, Duplicate_Subexpr_No_Checks (E)),
3712              Attribute_Name => Name_Size);
3713       end if;
3714
3715       Set_Paren_Count (Sizexpr, 1);
3716
3717       Append_To (List_Def,
3718         Make_Subtype_Declaration (Loc,
3719           Defining_Identifier => Range_Type,
3720           Subtype_Indication =>
3721             Make_Subtype_Indication (Loc,
3722               Subtype_Mark => New_Reference_To (RTE (RE_Storage_Offset), Loc),
3723               Constraint => Make_Range_Constraint (Loc,
3724                 Range_Expression =>
3725                   Make_Range (Loc,
3726                     Low_Bound => Make_Integer_Literal (Loc, 1),
3727                     High_Bound =>
3728                       Make_Op_Divide (Loc,
3729                         Left_Opnd => Sizexpr,
3730                         Right_Opnd => Make_Integer_Literal (Loc,
3731                             Intval => System_Storage_Unit)))))));
3732
3733       --  subtype str__nn is Storage_Array (rg__x);
3734
3735       Str_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('S'));
3736       Append_To (List_Def,
3737         Make_Subtype_Declaration (Loc,
3738           Defining_Identifier => Str_Type,
3739           Subtype_Indication =>
3740             Make_Subtype_Indication (Loc,
3741               Subtype_Mark => New_Reference_To (RTE (RE_Storage_Array), Loc),
3742               Constraint =>
3743                 Make_Index_Or_Discriminant_Constraint (Loc,
3744                   Constraints =>
3745                     New_List (New_Reference_To (Range_Type, Loc))))));
3746
3747       --  type Equiv_T is record
3748       --    [ _parent : Tnn; ]
3749       --    E : Str_Type;
3750       --  end Equiv_T;
3751
3752       Equiv_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
3753
3754       --  When the target requires front-end layout, it's necessary to allow
3755       --  the equivalent type to be frozen so that layout can occur (when the
3756       --  associated class-wide subtype is frozen, the equivalent type will
3757       --  be frozen, see freeze.adb). For other targets, Gigi wants to have
3758       --  the equivalent type marked as frozen and deals with this type itself.
3759       --  In the Gigi case this will also avoid the generation of an init
3760       --  procedure for the type.
3761
3762       if not Frontend_Layout_On_Target then
3763          Set_Is_Frozen (Equiv_Type);
3764       end if;
3765
3766       Set_Ekind (Equiv_Type, E_Record_Type);
3767       Set_Parent_Subtype (Equiv_Type, Constr_Root);
3768
3769       if not Is_Interface (Root_Typ) then
3770          Append_To (Comp_List,
3771            Make_Component_Declaration (Loc,
3772              Defining_Identifier =>
3773                Make_Defining_Identifier (Loc, Name_uParent),
3774              Component_Definition =>
3775                Make_Component_Definition (Loc,
3776                  Aliased_Present    => False,
3777                  Subtype_Indication => New_Reference_To (Constr_Root, Loc))));
3778       end if;
3779
3780       Append_To (Comp_List,
3781         Make_Component_Declaration (Loc,
3782           Defining_Identifier =>
3783             Make_Defining_Identifier (Loc,
3784               Chars => New_Internal_Name ('C')),
3785           Component_Definition =>
3786             Make_Component_Definition (Loc,
3787               Aliased_Present    => False,
3788               Subtype_Indication => New_Reference_To (Str_Type, Loc))));
3789
3790       Append_To (List_Def,
3791         Make_Full_Type_Declaration (Loc,
3792           Defining_Identifier => Equiv_Type,
3793           Type_Definition =>
3794             Make_Record_Definition (Loc,
3795               Component_List =>
3796                 Make_Component_List (Loc,
3797                   Component_Items => Comp_List,
3798                   Variant_Part    => Empty))));
3799
3800       --  Suppress all checks during the analysis of the expanded code
3801       --  to avoid the generation of spurious warnings under ZFP run-time.
3802
3803       Insert_Actions (E, List_Def, Suppress => All_Checks);
3804       return Equiv_Type;
3805    end Make_CW_Equivalent_Type;
3806
3807    ------------------------
3808    -- Make_Literal_Range --
3809    ------------------------
3810
3811    function Make_Literal_Range
3812      (Loc         : Source_Ptr;
3813       Literal_Typ : Entity_Id) return Node_Id
3814    is
3815       Lo          : constant Node_Id :=
3816                       New_Copy_Tree (String_Literal_Low_Bound (Literal_Typ));
3817       Index       : constant Entity_Id := Etype (Lo);
3818
3819       Hi          : Node_Id;
3820       Length_Expr : constant Node_Id :=
3821                       Make_Op_Subtract (Loc,
3822                         Left_Opnd =>
3823                           Make_Integer_Literal (Loc,
3824                             Intval => String_Literal_Length (Literal_Typ)),
3825                         Right_Opnd =>
3826                           Make_Integer_Literal (Loc, 1));
3827
3828    begin
3829       Set_Analyzed (Lo, False);
3830
3831          if Is_Integer_Type (Index) then
3832             Hi :=
3833               Make_Op_Add (Loc,
3834                 Left_Opnd  => New_Copy_Tree (Lo),
3835                 Right_Opnd => Length_Expr);
3836          else
3837             Hi :=
3838               Make_Attribute_Reference (Loc,
3839                 Attribute_Name => Name_Val,
3840                 Prefix => New_Occurrence_Of (Index, Loc),
3841                 Expressions => New_List (
3842                  Make_Op_Add (Loc,
3843                    Left_Opnd =>
3844                      Make_Attribute_Reference (Loc,
3845                        Attribute_Name => Name_Pos,
3846                        Prefix => New_Occurrence_Of (Index, Loc),
3847                        Expressions => New_List (New_Copy_Tree (Lo))),
3848                   Right_Opnd => Length_Expr)));
3849          end if;
3850
3851          return
3852            Make_Range (Loc,
3853              Low_Bound  => Lo,
3854              High_Bound => Hi);
3855    end Make_Literal_Range;
3856
3857    ----------------------------
3858    -- Make_Subtype_From_Expr --
3859    ----------------------------
3860
3861    --  1. If Expr is an uncontrained array expression, creates
3862    --    Unc_Type(Expr'first(1)..Expr'Last(1),..., Expr'first(n)..Expr'last(n))
3863
3864    --  2. If Expr is a unconstrained discriminated type expression, creates
3865    --    Unc_Type(Expr.Discr1, ... , Expr.Discr_n)
3866
3867    --  3. If Expr is class-wide, creates an implicit class wide subtype
3868
3869    function Make_Subtype_From_Expr
3870      (E       : Node_Id;
3871       Unc_Typ : Entity_Id) return Node_Id
3872    is
3873       Loc         : constant Source_Ptr := Sloc (E);
3874       List_Constr : constant List_Id    := New_List;
3875       D           : Entity_Id;
3876
3877       Full_Subtyp  : Entity_Id;
3878       Priv_Subtyp  : Entity_Id;
3879       Utyp         : Entity_Id;
3880       Full_Exp     : Node_Id;
3881
3882    begin
3883       if Is_Private_Type (Unc_Typ)
3884         and then Has_Unknown_Discriminants (Unc_Typ)
3885       then
3886          --  Prepare the subtype completion, Go to base type to
3887          --  find underlying type, because the type may be a generic
3888          --  actual or an explicit subtype.
3889
3890          Utyp        := Underlying_Type (Base_Type (Unc_Typ));
3891          Full_Subtyp := Make_Defining_Identifier (Loc,
3892                           New_Internal_Name ('C'));
3893          Full_Exp    :=
3894            Unchecked_Convert_To
3895              (Utyp, Duplicate_Subexpr_No_Checks (E));
3896          Set_Parent (Full_Exp, Parent (E));
3897
3898          Priv_Subtyp :=
3899            Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
3900
3901          Insert_Action (E,
3902            Make_Subtype_Declaration (Loc,
3903              Defining_Identifier => Full_Subtyp,
3904              Subtype_Indication  => Make_Subtype_From_Expr (Full_Exp, Utyp)));
3905
3906          --  Define the dummy private subtype
3907
3908          Set_Ekind          (Priv_Subtyp, Subtype_Kind (Ekind (Unc_Typ)));
3909          Set_Etype          (Priv_Subtyp, Base_Type (Unc_Typ));
3910          Set_Scope          (Priv_Subtyp, Full_Subtyp);
3911          Set_Is_Constrained (Priv_Subtyp);
3912          Set_Is_Tagged_Type (Priv_Subtyp, Is_Tagged_Type (Unc_Typ));
3913          Set_Is_Itype       (Priv_Subtyp);
3914          Set_Associated_Node_For_Itype (Priv_Subtyp, E);
3915
3916          if Is_Tagged_Type  (Priv_Subtyp) then
3917             Set_Class_Wide_Type
3918               (Base_Type (Priv_Subtyp), Class_Wide_Type (Unc_Typ));
3919             Set_Primitive_Operations (Priv_Subtyp,
3920               Primitive_Operations (Unc_Typ));
3921          end if;
3922
3923          Set_Full_View (Priv_Subtyp, Full_Subtyp);
3924
3925          return New_Reference_To (Priv_Subtyp, Loc);
3926
3927       elsif Is_Array_Type (Unc_Typ) then
3928          for J in 1 .. Number_Dimensions (Unc_Typ) loop
3929             Append_To (List_Constr,
3930               Make_Range (Loc,
3931                 Low_Bound =>
3932                   Make_Attribute_Reference (Loc,
3933                     Prefix => Duplicate_Subexpr_No_Checks (E),
3934                     Attribute_Name => Name_First,
3935                     Expressions => New_List (
3936                       Make_Integer_Literal (Loc, J))),
3937
3938                 High_Bound =>
3939                   Make_Attribute_Reference (Loc,
3940                     Prefix         => Duplicate_Subexpr_No_Checks (E),
3941                     Attribute_Name => Name_Last,
3942                     Expressions    => New_List (
3943                       Make_Integer_Literal (Loc, J)))));
3944          end loop;
3945
3946       elsif Is_Class_Wide_Type (Unc_Typ) then
3947          declare
3948             CW_Subtype : Entity_Id;
3949             EQ_Typ     : Entity_Id := Empty;
3950
3951          begin
3952             --  A class-wide equivalent type is not needed when VM_Target
3953             --  because the VM back-ends handle the class-wide object
3954             --  initialization itself (and doesn't need or want the
3955             --  additional intermediate type to handle the assignment).
3956
3957             if Expander_Active and then VM_Target = No_VM then
3958                EQ_Typ := Make_CW_Equivalent_Type (Unc_Typ, E);
3959             end if;
3960
3961             CW_Subtype := New_Class_Wide_Subtype (Unc_Typ, E);
3962             Set_Equivalent_Type (CW_Subtype, EQ_Typ);
3963
3964             if Present (EQ_Typ) then
3965                Set_Is_Class_Wide_Equivalent_Type (EQ_Typ);
3966             end if;
3967
3968             Set_Cloned_Subtype (CW_Subtype, Base_Type (Unc_Typ));
3969
3970             return New_Occurrence_Of (CW_Subtype, Loc);
3971          end;
3972
3973       --  Indefinite record type with discriminants
3974
3975       else
3976          D := First_Discriminant (Unc_Typ);
3977          while Present (D) loop
3978             Append_To (List_Constr,
3979               Make_Selected_Component (Loc,
3980                 Prefix        => Duplicate_Subexpr_No_Checks (E),
3981                 Selector_Name => New_Reference_To (D, Loc)));
3982
3983             Next_Discriminant (D);
3984          end loop;
3985       end if;
3986
3987       return
3988         Make_Subtype_Indication (Loc,
3989           Subtype_Mark => New_Reference_To (Unc_Typ, Loc),
3990           Constraint   =>
3991             Make_Index_Or_Discriminant_Constraint (Loc,
3992               Constraints => List_Constr));
3993    end Make_Subtype_From_Expr;
3994
3995    -----------------------------
3996    -- May_Generate_Large_Temp --
3997    -----------------------------
3998
3999    --  At the current time, the only types that we return False for (i.e.
4000    --  where we decide we know they cannot generate large temps) are ones
4001    --  where we know the size is 256 bits or less at compile time, and we
4002    --  are still not doing a thorough job on arrays and records ???
4003
4004    function May_Generate_Large_Temp (Typ : Entity_Id) return Boolean is
4005    begin
4006       if not Size_Known_At_Compile_Time (Typ) then
4007          return False;
4008
4009       elsif Esize (Typ) /= 0 and then Esize (Typ) <= 256 then
4010          return False;
4011
4012       elsif Is_Array_Type (Typ)
4013         and then Present (Packed_Array_Type (Typ))
4014       then
4015          return May_Generate_Large_Temp (Packed_Array_Type (Typ));
4016
4017       --  We could do more here to find other small types ???
4018
4019       else
4020          return True;
4021       end if;
4022    end May_Generate_Large_Temp;
4023
4024    ----------------------------
4025    -- New_Class_Wide_Subtype --
4026    ----------------------------
4027
4028    function New_Class_Wide_Subtype
4029      (CW_Typ : Entity_Id;
4030       N      : Node_Id) return Entity_Id
4031    is
4032       Res       : constant Entity_Id := Create_Itype (E_Void, N);
4033       Res_Name  : constant Name_Id   := Chars (Res);
4034       Res_Scope : constant Entity_Id := Scope (Res);
4035
4036    begin
4037       Copy_Node (CW_Typ, Res);
4038       Set_Comes_From_Source (Res, False);
4039       Set_Sloc (Res, Sloc (N));
4040       Set_Is_Itype (Res);
4041       Set_Associated_Node_For_Itype (Res, N);
4042       Set_Is_Public (Res, False);   --  By default, may be changed below.
4043       Set_Public_Status (Res);
4044       Set_Chars (Res, Res_Name);
4045       Set_Scope (Res, Res_Scope);
4046       Set_Ekind (Res, E_Class_Wide_Subtype);
4047       Set_Next_Entity (Res, Empty);
4048       Set_Etype (Res, Base_Type (CW_Typ));
4049
4050       --  For targets where front-end layout is required, reset the Is_Frozen
4051       --  status of the subtype to False (it can be implicitly set to true
4052       --  from the copy of the class-wide type). For other targets, Gigi
4053       --  doesn't want the class-wide subtype to go through the freezing
4054       --  process (though it's unclear why that causes problems and it would
4055       --  be nice to allow freezing to occur normally for all targets ???).
4056
4057       if Frontend_Layout_On_Target then
4058          Set_Is_Frozen (Res, False);
4059       end if;
4060
4061       Set_Freeze_Node (Res, Empty);
4062       return (Res);
4063    end New_Class_Wide_Subtype;
4064
4065    --------------------------------
4066    -- Non_Limited_Designated_Type --
4067    ---------------------------------
4068
4069    function Non_Limited_Designated_Type (T : Entity_Id) return Entity_Id is
4070       Desig : constant Entity_Id := Designated_Type (T);
4071    begin
4072       if Ekind (Desig) = E_Incomplete_Type
4073         and then Present (Non_Limited_View (Desig))
4074       then
4075          return Non_Limited_View (Desig);
4076       else
4077          return Desig;
4078       end if;
4079    end Non_Limited_Designated_Type;
4080
4081    -----------------------------------
4082    -- OK_To_Do_Constant_Replacement --
4083    -----------------------------------
4084
4085    function OK_To_Do_Constant_Replacement (E : Entity_Id) return Boolean is
4086       ES : constant Entity_Id := Scope (E);
4087       CS : Entity_Id;
4088
4089    begin
4090       --  Do not replace statically allocated objects, because they may be
4091       --  modified outside the current scope.
4092
4093       if Is_Statically_Allocated (E) then
4094          return False;
4095
4096       --  Do not replace aliased or volatile objects, since we don't know what
4097       --  else might change the value.
4098
4099       elsif Is_Aliased (E) or else Treat_As_Volatile (E) then
4100          return False;
4101
4102       --  Debug flag -gnatdM disconnects this optimization
4103
4104       elsif Debug_Flag_MM then
4105          return False;
4106
4107       --  Otherwise check scopes
4108
4109       else
4110          CS := Current_Scope;
4111
4112          loop
4113             --  If we are in right scope, replacement is safe
4114
4115             if CS = ES then
4116                return True;
4117
4118             --  Packages do not affect the determination of safety
4119
4120             elsif Ekind (CS) = E_Package then
4121                exit when CS = Standard_Standard;
4122                CS := Scope (CS);
4123
4124             --  Blocks do not affect the determination of safety
4125
4126             elsif Ekind (CS) = E_Block then
4127                CS := Scope (CS);
4128
4129             --  Loops do not affect the determination of safety. Note that we
4130             --  kill all current values on entry to a loop, so we are just
4131             --  talking about processing within a loop here.
4132
4133             elsif Ekind (CS) = E_Loop then
4134                CS := Scope (CS);
4135
4136             --  Otherwise, the reference is dubious, and we cannot be sure that
4137             --  it is safe to do the replacement.
4138
4139             else
4140                exit;
4141             end if;
4142          end loop;
4143
4144          return False;
4145       end if;
4146    end OK_To_Do_Constant_Replacement;
4147
4148    ------------------------------------
4149    -- Possible_Bit_Aligned_Component --
4150    ------------------------------------
4151
4152    function Possible_Bit_Aligned_Component (N : Node_Id) return Boolean is
4153    begin
4154       case Nkind (N) is
4155
4156          --  Case of indexed component
4157
4158          when N_Indexed_Component =>
4159             declare
4160                P    : constant Node_Id   := Prefix (N);
4161                Ptyp : constant Entity_Id := Etype (P);
4162
4163             begin
4164                --  If we know the component size and it is less than 64, then
4165                --  we are definitely OK. The back end always does assignment
4166                --  of misaligned small objects correctly.
4167
4168                if Known_Static_Component_Size (Ptyp)
4169                  and then Component_Size (Ptyp) <= 64
4170                then
4171                   return False;
4172
4173                --  Otherwise, we need to test the prefix, to see if we are
4174                --  indexing from a possibly unaligned component.
4175
4176                else
4177                   return Possible_Bit_Aligned_Component (P);
4178                end if;
4179             end;
4180
4181          --  Case of selected component
4182
4183          when N_Selected_Component =>
4184             declare
4185                P    : constant Node_Id   := Prefix (N);
4186                Comp : constant Entity_Id := Entity (Selector_Name (N));
4187
4188             begin
4189                --  If there is no component clause, then we are in the clear
4190                --  since the back end will never misalign a large component
4191                --  unless it is forced to do so. In the clear means we need
4192                --  only the recursive test on the prefix.
4193
4194                if Component_May_Be_Bit_Aligned (Comp) then
4195                   return True;
4196                else
4197                   return Possible_Bit_Aligned_Component (P);
4198                end if;
4199             end;
4200
4201          --  If we have neither a record nor array component, it means that we
4202          --  have fallen off the top testing prefixes recursively, and we now
4203          --  have a stand alone object, where we don't have a problem.
4204
4205          when others =>
4206             return False;
4207
4208       end case;
4209    end Possible_Bit_Aligned_Component;
4210
4211    -------------------------
4212    -- Remove_Side_Effects --
4213    -------------------------
4214
4215    procedure Remove_Side_Effects
4216      (Exp          : Node_Id;
4217       Name_Req     : Boolean := False;
4218       Variable_Ref : Boolean := False)
4219    is
4220       Loc          : constant Source_Ptr     := Sloc (Exp);
4221       Exp_Type     : constant Entity_Id      := Etype (Exp);
4222       Svg_Suppress : constant Suppress_Array := Scope_Suppress;
4223       Def_Id       : Entity_Id;
4224       Ref_Type     : Entity_Id;
4225       Res          : Node_Id;
4226       Ptr_Typ_Decl : Node_Id;
4227       New_Exp      : Node_Id;
4228       E            : Node_Id;
4229
4230       function Side_Effect_Free (N : Node_Id) return Boolean;
4231       --  Determines if the tree N represents an expression that is known not
4232       --  to have side effects, and for which no processing is required.
4233
4234       function Side_Effect_Free (L : List_Id) return Boolean;
4235       --  Determines if all elements of the list L are side effect free
4236
4237       function Safe_Prefixed_Reference (N : Node_Id) return Boolean;
4238       --  The argument N is a construct where the Prefix is dereferenced if it
4239       --  is an access type and the result is a variable. The call returns True
4240       --  if the construct is side effect free (not considering side effects in
4241       --  other than the prefix which are to be tested by the caller).
4242
4243       function Within_In_Parameter (N : Node_Id) return Boolean;
4244       --  Determines if N is a subcomponent of a composite in-parameter. If so,
4245       --  N is not side-effect free when the actual is global and modifiable
4246       --  indirectly from within a subprogram, because it may be passed by
4247       --  reference. The front-end must be conservative here and assume that
4248       --  this may happen with any array or record type. On the other hand, we
4249       --  cannot create temporaries for all expressions for which this
4250       --  condition is true, for various reasons that might require clearing up
4251       --  ??? For example, descriminant references that appear out of place, or
4252       --  spurious type errors with class-wide expressions. As a result, we
4253       --  limit the transformation to loop bounds, which is so far the only
4254       --  case that requires it.
4255
4256       -----------------------------
4257       -- Safe_Prefixed_Reference --
4258       -----------------------------
4259
4260       function Safe_Prefixed_Reference (N : Node_Id) return Boolean is
4261       begin
4262          --  If prefix is not side effect free, definitely not safe
4263
4264          if not Side_Effect_Free (Prefix (N)) then
4265             return False;
4266
4267          --  If the prefix is of an access type that is not access-to-constant,
4268          --  then this construct is a variable reference, which means it is to
4269          --  be considered to have side effects if Variable_Ref is set True
4270          --  Exception is an access to an entity that is a constant or an
4271          --  in-parameter which does not come from source, and is the result
4272          --  of a previous removal of side-effects.
4273
4274          elsif Is_Access_Type (Etype (Prefix (N)))
4275            and then not Is_Access_Constant (Etype (Prefix (N)))
4276            and then Variable_Ref
4277          then
4278             if not Is_Entity_Name (Prefix (N)) then
4279                return False;
4280             else
4281                return Ekind (Entity (Prefix (N))) = E_Constant
4282                  or else Ekind (Entity (Prefix (N))) = E_In_Parameter;
4283             end if;
4284
4285          --  The following test is the simplest way of solving a complex
4286          --  problem uncovered by BB08-010: Side effect on loop bound that
4287          --  is a subcomponent of a global variable:
4288          --    If a loop bound is a subcomponent of a global variable, a
4289          --    modification of that variable within the loop may incorrectly
4290          --    affect the execution of the loop.
4291
4292          elsif not
4293            (Nkind (Parent (Parent (N))) /= N_Loop_Parameter_Specification
4294               or else not Within_In_Parameter (Prefix (N)))
4295          then
4296             return False;
4297
4298          --  All other cases are side effect free
4299
4300          else
4301             return True;
4302          end if;
4303       end Safe_Prefixed_Reference;
4304
4305       ----------------------
4306       -- Side_Effect_Free --
4307       ----------------------
4308
4309       function Side_Effect_Free (N : Node_Id) return Boolean is
4310       begin
4311          --  Note on checks that could raise Constraint_Error. Strictly, if
4312          --  we take advantage of 11.6, these checks do not count as side
4313          --  effects. However, we would just as soon consider that they are
4314          --  side effects, since the backend CSE does not work very well on
4315          --  expressions which can raise Constraint_Error. On the other
4316          --  hand, if we do not consider them to be side effect free, then
4317          --  we get some awkward expansions in -gnato mode, resulting in
4318          --  code insertions at a point where we do not have a clear model
4319          --  for performing the insertions. See 4908-002/comment for details.
4320
4321          --  Special handling for entity names
4322
4323          if Is_Entity_Name (N) then
4324
4325             --  If the entity is a constant, it is definitely side effect
4326             --  free. Note that the test of Is_Variable (N) below might
4327             --  be expected to catch this case, but it does not, because
4328             --  this test goes to the original tree, and we may have
4329             --  already rewritten a variable node with a constant as
4330             --  a result of an earlier Force_Evaluation call.
4331
4332             if Ekind (Entity (N)) = E_Constant
4333               or else Ekind (Entity (N)) = E_In_Parameter
4334             then
4335                return True;
4336
4337             --  Functions are not side effect free
4338
4339             elsif Ekind (Entity (N)) = E_Function then
4340                return False;
4341
4342             --  Variables are considered to be a side effect if Variable_Ref
4343             --  is set or if we have a volatile variable and Name_Req is off.
4344             --  If Name_Req is True then we can't help returning a name which
4345             --  effectively allows multiple references in any case.
4346
4347             elsif Is_Variable (N) then
4348                return not Variable_Ref
4349                  and then (not Treat_As_Volatile (Entity (N))
4350                              or else Name_Req);
4351
4352             --  Any other entity (e.g. a subtype name) is definitely side
4353             --  effect free.
4354
4355             else
4356                return True;
4357             end if;
4358
4359          --  A value known at compile time is always side effect free
4360
4361          elsif Compile_Time_Known_Value (N) then
4362             return True;
4363
4364          --  A variable renaming is not side-effet free, because the
4365          --  renaming will function like a macro in the front-end in
4366          --  some cases, and an assignment can modify the the component
4367          --  designated by N, so we need to create a temporary for it.
4368
4369          elsif Is_Entity_Name (Original_Node (N))
4370            and then Is_Renaming_Of_Object (Entity (Original_Node (N)))
4371            and then Ekind (Entity (Original_Node (N))) /= E_Constant
4372          then
4373             return False;
4374          end if;
4375
4376          --  For other than entity names and compile time known values,
4377          --  check the node kind for special processing.
4378
4379          case Nkind (N) is
4380
4381             --  An attribute reference is side effect free if its expressions
4382             --  are side effect free and its prefix is side effect free or
4383             --  is an entity reference.
4384
4385             --  Is this right? what about x'first where x is a variable???
4386
4387             when N_Attribute_Reference =>
4388                return Side_Effect_Free (Expressions (N))
4389                  and then Attribute_Name (N) /= Name_Input
4390                  and then (Is_Entity_Name (Prefix (N))
4391                             or else Side_Effect_Free (Prefix (N)));
4392
4393             --  A binary operator is side effect free if and both operands
4394             --  are side effect free. For this purpose binary operators
4395             --  include membership tests and short circuit forms
4396
4397             when N_Binary_Op       |
4398                  N_Membership_Test |
4399                  N_And_Then        |
4400                  N_Or_Else         =>
4401                return Side_Effect_Free (Left_Opnd  (N))
4402                  and then Side_Effect_Free (Right_Opnd (N));
4403
4404             --  An explicit dereference is side effect free only if it is
4405             --  a side effect free prefixed reference.
4406
4407             when N_Explicit_Dereference =>
4408                return Safe_Prefixed_Reference (N);
4409
4410             --  A call to _rep_to_pos is side effect free, since we generate
4411             --  this pure function call ourselves. Moreover it is critically
4412             --  important to make this exception, since otherwise we can
4413             --  have discriminants in array components which don't look
4414             --  side effect free in the case of an array whose index type
4415             --  is an enumeration type with an enumeration rep clause.
4416
4417             --  All other function calls are not side effect free
4418
4419             when N_Function_Call =>
4420                return Nkind (Name (N)) = N_Identifier
4421                  and then Is_TSS (Name (N), TSS_Rep_To_Pos)
4422                  and then
4423                    Side_Effect_Free (First (Parameter_Associations (N)));
4424
4425             --  An indexed component is side effect free if it is a side
4426             --  effect free prefixed reference and all the indexing
4427             --  expressions are side effect free.
4428
4429             when N_Indexed_Component =>
4430                return Side_Effect_Free (Expressions (N))
4431                  and then Safe_Prefixed_Reference (N);
4432
4433             --  A type qualification is side effect free if the expression
4434             --  is side effect free.
4435
4436             when N_Qualified_Expression =>
4437                return Side_Effect_Free (Expression (N));
4438
4439             --  A selected component is side effect free only if it is a
4440             --  side effect free prefixed reference. If it designates a
4441             --  component with a rep. clause it must be treated has having
4442             --  a potential side effect, because it may be modified through
4443             --  a renaming, and a subsequent use of the renaming as a macro
4444             --  will yield the wrong value. This complex interaction between
4445             --  renaming and removing side effects is a reminder that the
4446             --  latter has become a headache to maintain, and that it should
4447             --  be removed in favor of the gcc mechanism to capture values ???
4448
4449             when N_Selected_Component =>
4450                if Nkind (Parent (N)) = N_Explicit_Dereference
4451                  and then Has_Non_Standard_Rep (Designated_Type (Etype (N)))
4452                then
4453                   return False;
4454                else
4455                   return Safe_Prefixed_Reference (N);
4456                end if;
4457
4458             --  A range is side effect free if the bounds are side effect free
4459
4460             when N_Range =>
4461                return Side_Effect_Free (Low_Bound (N))
4462                  and then Side_Effect_Free (High_Bound (N));
4463
4464             --  A slice is side effect free if it is a side effect free
4465             --  prefixed reference and the bounds are side effect free.
4466
4467             when N_Slice =>
4468                return Side_Effect_Free (Discrete_Range (N))
4469                  and then Safe_Prefixed_Reference (N);
4470
4471             --  A type conversion is side effect free if the expression to be
4472             --  converted is side effect free.
4473
4474             when N_Type_Conversion =>
4475                return Side_Effect_Free (Expression (N));
4476
4477             --  A unary operator is side effect free if the operand
4478             --  is side effect free.
4479
4480             when N_Unary_Op =>
4481                return Side_Effect_Free (Right_Opnd (N));
4482
4483             --  An unchecked type conversion is side effect free only if it
4484             --  is safe and its argument is side effect free.
4485
4486             when N_Unchecked_Type_Conversion =>
4487                return Safe_Unchecked_Type_Conversion (N)
4488                  and then Side_Effect_Free (Expression (N));
4489
4490             --  An unchecked expression is side effect free if its expression
4491             --  is side effect free.
4492
4493             when N_Unchecked_Expression =>
4494                return Side_Effect_Free (Expression (N));
4495
4496             --  A literal is side effect free
4497
4498             when N_Character_Literal    |
4499                  N_Integer_Literal      |
4500                  N_Real_Literal         |
4501                  N_String_Literal       =>
4502                return True;
4503
4504             --  We consider that anything else has side effects. This is a bit
4505             --  crude, but we are pretty close for most common cases, and we
4506             --  are certainly correct (i.e. we never return True when the
4507             --  answer should be False).
4508
4509             when others =>
4510                return False;
4511          end case;
4512       end Side_Effect_Free;
4513
4514       --  A list is side effect free if all elements of the list are
4515       --  side effect free.
4516
4517       function Side_Effect_Free (L : List_Id) return Boolean is
4518          N : Node_Id;
4519
4520       begin
4521          if L = No_List or else L = Error_List then
4522             return True;
4523
4524          else
4525             N := First (L);
4526             while Present (N) loop
4527                if not Side_Effect_Free (N) then
4528                   return False;
4529                else
4530                   Next (N);
4531                end if;
4532             end loop;
4533
4534             return True;
4535          end if;
4536       end Side_Effect_Free;
4537
4538       -------------------------
4539       -- Within_In_Parameter --
4540       -------------------------
4541
4542       function Within_In_Parameter (N : Node_Id) return Boolean is
4543       begin
4544          if not Comes_From_Source (N) then
4545             return False;
4546
4547          elsif Is_Entity_Name (N) then
4548             return Ekind (Entity (N)) = E_In_Parameter;
4549
4550          elsif Nkind (N) = N_Indexed_Component
4551            or else Nkind (N) = N_Selected_Component
4552          then
4553             return Within_In_Parameter (Prefix (N));
4554          else
4555
4556             return False;
4557          end if;
4558       end Within_In_Parameter;
4559
4560    --  Start of processing for Remove_Side_Effects
4561
4562    begin
4563       --  If we are side effect free already or expansion is disabled,
4564       --  there is nothing to do.
4565
4566       if Side_Effect_Free (Exp) or else not Expander_Active then
4567          return;
4568       end if;
4569
4570       --  All this must not have any checks
4571
4572       Scope_Suppress := (others => True);
4573
4574       --  If it is a scalar type and we need to capture the value, just make
4575       --  a copy. Likewise for a function or operator call. And if we have a
4576       --  volatile variable and Nam_Req is not set (see comments above for
4577       --  Side_Effect_Free).
4578
4579       if Is_Elementary_Type (Exp_Type)
4580         and then (Variable_Ref
4581                    or else Nkind (Exp) = N_Function_Call
4582                    or else Nkind (Exp) in N_Op
4583                    or else (not Name_Req
4584                              and then Is_Entity_Name (Exp)
4585                              and then Treat_As_Volatile (Entity (Exp))))
4586       then
4587          Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4588          Set_Etype (Def_Id, Exp_Type);
4589          Res := New_Reference_To (Def_Id, Loc);
4590
4591          E :=
4592            Make_Object_Declaration (Loc,
4593              Defining_Identifier => Def_Id,
4594              Object_Definition   => New_Reference_To (Exp_Type, Loc),
4595              Constant_Present    => True,
4596              Expression          => Relocate_Node (Exp));
4597
4598          Set_Assignment_OK (E);
4599          Insert_Action (Exp, E);
4600
4601       --  If the expression has the form v.all then we can just capture
4602       --  the pointer, and then do an explicit dereference on the result.
4603
4604       elsif Nkind (Exp) = N_Explicit_Dereference then
4605          Def_Id :=
4606            Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4607          Res :=
4608            Make_Explicit_Dereference (Loc, New_Reference_To (Def_Id, Loc));
4609
4610          Insert_Action (Exp,
4611            Make_Object_Declaration (Loc,
4612              Defining_Identifier => Def_Id,
4613              Object_Definition   =>
4614                New_Reference_To (Etype (Prefix (Exp)), Loc),
4615              Constant_Present    => True,
4616              Expression          => Relocate_Node (Prefix (Exp))));
4617
4618       --  Similar processing for an unchecked conversion of an expression
4619       --  of the form v.all, where we want the same kind of treatment.
4620
4621       elsif Nkind (Exp) = N_Unchecked_Type_Conversion
4622         and then Nkind (Expression (Exp)) = N_Explicit_Dereference
4623       then
4624          Remove_Side_Effects (Expression (Exp), Name_Req, Variable_Ref);
4625          Scope_Suppress := Svg_Suppress;
4626          return;
4627
4628       --  If this is a type conversion, leave the type conversion and remove
4629       --  the side effects in the expression. This is important in several
4630       --  circumstances: for change of representations, and also when this
4631       --  is a view conversion to a smaller object, where gigi can end up
4632       --  creating its own temporary of the wrong size.
4633
4634       elsif Nkind (Exp) = N_Type_Conversion then
4635          Remove_Side_Effects (Expression (Exp), Name_Req, Variable_Ref);
4636          Scope_Suppress := Svg_Suppress;
4637          return;
4638
4639       --  If this is an unchecked conversion that Gigi can't handle, make
4640       --  a copy or a use a renaming to capture the value.
4641
4642       elsif Nkind (Exp) = N_Unchecked_Type_Conversion
4643         and then not Safe_Unchecked_Type_Conversion (Exp)
4644       then
4645          if CW_Or_Controlled_Type (Exp_Type) then
4646
4647             --  Use a renaming to capture the expression, rather than create
4648             --  a controlled temporary.
4649
4650             Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4651             Res := New_Reference_To (Def_Id, Loc);
4652
4653             Insert_Action (Exp,
4654               Make_Object_Renaming_Declaration (Loc,
4655                 Defining_Identifier => Def_Id,
4656                 Subtype_Mark        => New_Reference_To (Exp_Type, Loc),
4657                 Name                => Relocate_Node (Exp)));
4658
4659          else
4660             Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4661             Set_Etype (Def_Id, Exp_Type);
4662             Res := New_Reference_To (Def_Id, Loc);
4663
4664             E :=
4665               Make_Object_Declaration (Loc,
4666                 Defining_Identifier => Def_Id,
4667                 Object_Definition   => New_Reference_To (Exp_Type, Loc),
4668                 Constant_Present    => not Is_Variable (Exp),
4669                 Expression          => Relocate_Node (Exp));
4670
4671             Set_Assignment_OK (E);
4672             Insert_Action (Exp, E);
4673          end if;
4674
4675       --  For expressions that denote objects, we can use a renaming scheme.
4676       --  We skip using this if we have a volatile variable and we do not
4677       --  have Nam_Req set true (see comments above for Side_Effect_Free).
4678
4679       elsif Is_Object_Reference (Exp)
4680         and then Nkind (Exp) /= N_Function_Call
4681         and then (Name_Req
4682                    or else not Is_Entity_Name (Exp)
4683                    or else not Treat_As_Volatile (Entity (Exp)))
4684       then
4685          Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4686
4687          if Nkind (Exp) = N_Selected_Component
4688            and then Nkind (Prefix (Exp)) = N_Function_Call
4689            and then Is_Array_Type (Exp_Type)
4690          then
4691             --  Avoid generating a variable-sized temporary, by generating
4692             --  the renaming declaration just for the function call. The
4693             --  transformation could be refined to apply only when the array
4694             --  component is constrained by a discriminant???
4695
4696             Res :=
4697               Make_Selected_Component (Loc,
4698                 Prefix => New_Occurrence_Of (Def_Id, Loc),
4699                 Selector_Name => Selector_Name (Exp));
4700
4701             Insert_Action (Exp,
4702               Make_Object_Renaming_Declaration (Loc,
4703                 Defining_Identifier => Def_Id,
4704                 Subtype_Mark        =>
4705                   New_Reference_To (Base_Type (Etype (Prefix (Exp))), Loc),
4706                 Name                => Relocate_Node (Prefix (Exp))));
4707
4708          else
4709             Res := New_Reference_To (Def_Id, Loc);
4710
4711             Insert_Action (Exp,
4712               Make_Object_Renaming_Declaration (Loc,
4713                 Defining_Identifier => Def_Id,
4714                 Subtype_Mark        => New_Reference_To (Exp_Type, Loc),
4715                 Name                => Relocate_Node (Exp)));
4716
4717          end if;
4718
4719          --  If this is a packed reference, or a selected component with a
4720          --  non-standard representation, a reference to the temporary will
4721          --  be replaced by a copy of the original expression (see
4722          --  exp_ch2.Expand_Renaming). Otherwise the temporary must be
4723          --  elaborated by gigi, and is of course not to be replaced in-line
4724          --  by the expression it renames, which would defeat the purpose of
4725          --  removing the side-effect.
4726
4727          if (Nkind (Exp) = N_Selected_Component
4728               or else Nkind (Exp) = N_Indexed_Component)
4729            and then Has_Non_Standard_Rep (Etype (Prefix (Exp)))
4730          then
4731             null;
4732          else
4733             Set_Is_Renaming_Of_Object (Def_Id, False);
4734          end if;
4735
4736       --  Otherwise we generate a reference to the value
4737
4738       else
4739          Ref_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
4740
4741          Ptr_Typ_Decl :=
4742            Make_Full_Type_Declaration (Loc,
4743              Defining_Identifier => Ref_Type,
4744              Type_Definition =>
4745                Make_Access_To_Object_Definition (Loc,
4746                  All_Present => True,
4747                  Subtype_Indication =>
4748                    New_Reference_To (Exp_Type, Loc)));
4749
4750          E := Exp;
4751          Insert_Action (Exp, Ptr_Typ_Decl);
4752
4753          Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4754          Set_Etype (Def_Id, Exp_Type);
4755
4756          Res :=
4757            Make_Explicit_Dereference (Loc,
4758              Prefix => New_Reference_To (Def_Id, Loc));
4759
4760          if Nkind (E) = N_Explicit_Dereference then
4761             New_Exp := Relocate_Node (Prefix (E));
4762          else
4763             E := Relocate_Node (E);
4764             New_Exp := Make_Reference (Loc, E);
4765          end if;
4766
4767          if Is_Delayed_Aggregate (E) then
4768
4769             --  The expansion of nested aggregates is delayed until the
4770             --  enclosing aggregate is expanded. As aggregates are often
4771             --  qualified, the predicate applies to qualified expressions
4772             --  as well, indicating that the enclosing aggregate has not
4773             --  been expanded yet. At this point the aggregate is part of
4774             --  a stand-alone declaration, and must be fully expanded.
4775
4776             if Nkind (E) = N_Qualified_Expression then
4777                Set_Expansion_Delayed (Expression (E), False);
4778                Set_Analyzed (Expression (E), False);
4779             else
4780                Set_Expansion_Delayed (E, False);
4781             end if;
4782
4783             Set_Analyzed (E, False);
4784          end if;
4785
4786          Insert_Action (Exp,
4787            Make_Object_Declaration (Loc,
4788              Defining_Identifier => Def_Id,
4789              Object_Definition   => New_Reference_To (Ref_Type, Loc),
4790              Expression          => New_Exp));
4791       end if;
4792
4793       --  Preserve the Assignment_OK flag in all copies, since at least
4794       --  one copy may be used in a context where this flag must be set
4795       --  (otherwise why would the flag be set in the first place).
4796
4797       Set_Assignment_OK (Res, Assignment_OK (Exp));
4798
4799       --  Finally rewrite the original expression and we are done
4800
4801       Rewrite (Exp, Res);
4802       Analyze_And_Resolve (Exp, Exp_Type);
4803       Scope_Suppress := Svg_Suppress;
4804    end Remove_Side_Effects;
4805
4806    ---------------------------
4807    -- Represented_As_Scalar --
4808    ---------------------------
4809
4810    function Represented_As_Scalar (T : Entity_Id) return Boolean is
4811       UT : constant Entity_Id := Underlying_Type (T);
4812    begin
4813       return Is_Scalar_Type (UT)
4814         or else (Is_Bit_Packed_Array (UT)
4815                    and then Is_Scalar_Type (Packed_Array_Type (UT)));
4816    end Represented_As_Scalar;
4817
4818    ------------------------------------
4819    -- Safe_Unchecked_Type_Conversion --
4820    ------------------------------------
4821
4822    --  Note: this function knows quite a bit about the exact requirements
4823    --  of Gigi with respect to unchecked type conversions, and its code
4824    --  must be coordinated with any changes in Gigi in this area.
4825
4826    --  The above requirements should be documented in Sinfo ???
4827
4828    function Safe_Unchecked_Type_Conversion (Exp : Node_Id) return Boolean is
4829       Otyp   : Entity_Id;
4830       Ityp   : Entity_Id;
4831       Oalign : Uint;
4832       Ialign : Uint;
4833       Pexp   : constant Node_Id := Parent (Exp);
4834
4835    begin
4836       --  If the expression is the RHS of an assignment or object declaration
4837       --   we are always OK because there will always be a target.
4838
4839       --  Object renaming declarations, (generated for view conversions of
4840       --  actuals in inlined calls), like object declarations, provide an
4841       --  explicit type, and are safe as well.
4842
4843       if (Nkind (Pexp) = N_Assignment_Statement
4844            and then Expression (Pexp) = Exp)
4845         or else Nkind (Pexp) = N_Object_Declaration
4846         or else Nkind (Pexp) = N_Object_Renaming_Declaration
4847       then
4848          return True;
4849
4850       --  If the expression is the prefix of an N_Selected_Component
4851       --  we should also be OK because GCC knows to look inside the
4852       --  conversion except if the type is discriminated. We assume
4853       --  that we are OK anyway if the type is not set yet or if it is
4854       --  controlled since we can't afford to introduce a temporary in
4855       --  this case.
4856
4857       elsif Nkind (Pexp) = N_Selected_Component
4858          and then Prefix (Pexp) = Exp
4859       then
4860          if No (Etype (Pexp)) then
4861             return True;
4862          else
4863             return
4864               not Has_Discriminants (Etype (Pexp))
4865                 or else Is_Constrained (Etype (Pexp));
4866          end if;
4867       end if;
4868
4869       --  Set the output type, this comes from Etype if it is set, otherwise
4870       --  we take it from the subtype mark, which we assume was already
4871       --  fully analyzed.
4872
4873       if Present (Etype (Exp)) then
4874          Otyp := Etype (Exp);
4875       else
4876          Otyp := Entity (Subtype_Mark (Exp));
4877       end if;
4878
4879       --  The input type always comes from the expression, and we assume
4880       --  this is indeed always analyzed, so we can simply get the Etype.
4881
4882       Ityp := Etype (Expression (Exp));
4883
4884       --  Initialize alignments to unknown so far
4885
4886       Oalign := No_Uint;
4887       Ialign := No_Uint;
4888
4889       --  Replace a concurrent type by its corresponding record type
4890       --  and each type by its underlying type and do the tests on those.
4891       --  The original type may be a private type whose completion is a
4892       --  concurrent type, so find the underlying type first.
4893
4894       if Present (Underlying_Type (Otyp)) then
4895          Otyp := Underlying_Type (Otyp);
4896       end if;
4897
4898       if Present (Underlying_Type (Ityp)) then
4899          Ityp := Underlying_Type (Ityp);
4900       end if;
4901
4902       if Is_Concurrent_Type (Otyp) then
4903          Otyp := Corresponding_Record_Type (Otyp);
4904       end if;
4905
4906       if Is_Concurrent_Type (Ityp) then
4907          Ityp := Corresponding_Record_Type (Ityp);
4908       end if;
4909
4910       --  If the base types are the same, we know there is no problem since
4911       --  this conversion will be a noop.
4912
4913       if Implementation_Base_Type (Otyp) = Implementation_Base_Type (Ityp) then
4914          return True;
4915
4916       --  Same if this is an upwards conversion of an untagged type, and there
4917       --  are no constraints involved (could be more general???)
4918
4919       elsif Etype (Ityp) = Otyp
4920         and then not Is_Tagged_Type (Ityp)
4921         and then not Has_Discriminants (Ityp)
4922         and then No (First_Rep_Item (Base_Type (Ityp)))
4923       then
4924          return True;
4925
4926       --  If the size of output type is known at compile time, there is
4927       --  never a problem.  Note that unconstrained records are considered
4928       --  to be of known size, but we can't consider them that way here,
4929       --  because we are talking about the actual size of the object.
4930
4931       --  We also make sure that in addition to the size being known, we do
4932       --  not have a case which might generate an embarrassingly large temp
4933       --  in stack checking mode.
4934
4935       elsif Size_Known_At_Compile_Time (Otyp)
4936         and then
4937           (not Stack_Checking_Enabled
4938              or else not May_Generate_Large_Temp (Otyp))
4939         and then not (Is_Record_Type (Otyp) and then not Is_Constrained (Otyp))
4940       then
4941          return True;
4942
4943       --  If either type is tagged, then we know the alignment is OK so
4944       --  Gigi will be able to use pointer punning.
4945
4946       elsif Is_Tagged_Type (Otyp) or else Is_Tagged_Type (Ityp) then
4947          return True;
4948
4949       --  If either type is a limited record type, we cannot do a copy, so
4950       --  say safe since there's nothing else we can do.
4951
4952       elsif Is_Limited_Record (Otyp) or else Is_Limited_Record (Ityp) then
4953          return True;
4954
4955       --  Conversions to and from packed array types are always ignored and
4956       --  hence are safe.
4957
4958       elsif Is_Packed_Array_Type (Otyp)
4959         or else Is_Packed_Array_Type (Ityp)
4960       then
4961          return True;
4962       end if;
4963
4964       --  The only other cases known to be safe is if the input type's
4965       --  alignment is known to be at least the maximum alignment for the
4966       --  target or if both alignments are known and the output type's
4967       --  alignment is no stricter than the input's.  We can use the alignment
4968       --  of the component type of an array if a type is an unpacked
4969       --  array type.
4970
4971       if Present (Alignment_Clause (Otyp)) then
4972          Oalign := Expr_Value (Expression (Alignment_Clause (Otyp)));
4973
4974       elsif Is_Array_Type (Otyp)
4975         and then Present (Alignment_Clause (Component_Type (Otyp)))
4976       then
4977          Oalign := Expr_Value (Expression (Alignment_Clause
4978                                            (Component_Type (Otyp))));
4979       end if;
4980
4981       if Present (Alignment_Clause (Ityp)) then
4982          Ialign := Expr_Value (Expression (Alignment_Clause (Ityp)));
4983
4984       elsif Is_Array_Type (Ityp)
4985         and then Present (Alignment_Clause (Component_Type (Ityp)))
4986       then
4987          Ialign := Expr_Value (Expression (Alignment_Clause
4988                                            (Component_Type (Ityp))));
4989       end if;
4990
4991       if Ialign /= No_Uint and then Ialign > Maximum_Alignment then
4992          return True;
4993
4994       elsif Ialign /= No_Uint and then Oalign /= No_Uint
4995         and then Ialign <= Oalign
4996       then
4997          return True;
4998
4999       --   Otherwise, Gigi cannot handle this and we must make a temporary
5000
5001       else
5002          return False;
5003       end if;
5004    end Safe_Unchecked_Type_Conversion;
5005
5006    ---------------------------------
5007    -- Set_Current_Value_Condition --
5008    ---------------------------------
5009
5010    --  Note: the implementation of this procedure is very closely tied to the
5011    --  implementation of Get_Current_Value_Condition. Here we set required
5012    --  Current_Value fields, and in Get_Current_Value_Condition, we interpret
5013    --  them, so they must have a consistent view.
5014
5015    procedure Set_Current_Value_Condition (Cnode : Node_Id) is
5016
5017       procedure Set_Entity_Current_Value (N : Node_Id);
5018       --  If N is an entity reference, where the entity is of an appropriate
5019       --  kind, then set the current value of this entity to Cnode, unless
5020       --  there is already a definite value set there.
5021
5022       procedure Set_Expression_Current_Value (N : Node_Id);
5023       --  If N is of an appropriate form, sets an appropriate entry in current
5024       --  value fields of relevant entities. Multiple entities can be affected
5025       --  in the case of an AND or AND THEN.
5026
5027       ------------------------------
5028       -- Set_Entity_Current_Value --
5029       ------------------------------
5030
5031       procedure Set_Entity_Current_Value (N : Node_Id) is
5032       begin
5033          if Is_Entity_Name (N) then
5034             declare
5035                Ent : constant Entity_Id := Entity (N);
5036
5037             begin
5038                --  Don't capture if not safe to do so
5039
5040                if not Safe_To_Capture_Value (N, Ent, Cond => True) then
5041                   return;
5042                end if;
5043
5044                --  Here we have a case where the Current_Value field may
5045                --  need to be set. We set it if it is not already set to a
5046                --  compile time expression value.
5047
5048                --  Note that this represents a decision that one condition
5049                --  blots out another previous one. That's certainly right
5050                --  if they occur at the same level. If the second one is
5051                --  nested, then the decision is neither right nor wrong (it
5052                --  would be equally OK to leave the outer one in place, or
5053                --  take the new inner one. Really we should record both, but
5054                --  our data structures are not that elaborate.
5055
5056                if Nkind (Current_Value (Ent)) not in N_Subexpr then
5057                   Set_Current_Value (Ent, Cnode);
5058                end if;
5059             end;
5060          end if;
5061       end Set_Entity_Current_Value;
5062
5063       ----------------------------------
5064       -- Set_Expression_Current_Value --
5065       ----------------------------------
5066
5067       procedure Set_Expression_Current_Value (N : Node_Id) is
5068          Cond : Node_Id;
5069
5070       begin
5071          Cond := N;
5072
5073          --  Loop to deal with (ignore for now) any NOT operators present. The
5074          --  presence of NOT operators will be handled properly when we call
5075          --  Get_Current_Value_Condition.
5076
5077          while Nkind (Cond) = N_Op_Not loop
5078             Cond := Right_Opnd (Cond);
5079          end loop;
5080
5081          --  For an AND or AND THEN, recursively process operands
5082
5083          if Nkind (Cond) = N_Op_And or else Nkind (Cond) = N_And_Then then
5084             Set_Expression_Current_Value (Left_Opnd (Cond));
5085             Set_Expression_Current_Value (Right_Opnd (Cond));
5086             return;
5087          end if;
5088
5089          --  Check possible relational operator
5090
5091          if Nkind (Cond) in N_Op_Compare then
5092             if Compile_Time_Known_Value (Right_Opnd (Cond)) then
5093                Set_Entity_Current_Value (Left_Opnd (Cond));
5094             elsif Compile_Time_Known_Value (Left_Opnd (Cond)) then
5095                Set_Entity_Current_Value (Right_Opnd (Cond));
5096             end if;
5097
5098             --  Check possible boolean variable reference
5099
5100          else
5101             Set_Entity_Current_Value (Cond);
5102          end if;
5103       end Set_Expression_Current_Value;
5104
5105    --  Start of processing for Set_Current_Value_Condition
5106
5107    begin
5108       Set_Expression_Current_Value (Condition (Cnode));
5109    end Set_Current_Value_Condition;
5110
5111    --------------------------
5112    -- Set_Elaboration_Flag --
5113    --------------------------
5114
5115    procedure Set_Elaboration_Flag (N : Node_Id; Spec_Id : Entity_Id) is
5116       Loc : constant Source_Ptr := Sloc (N);
5117       Ent : constant Entity_Id  := Elaboration_Entity (Spec_Id);
5118       Asn : Node_Id;
5119
5120    begin
5121       if Present (Ent) then
5122
5123          --  Nothing to do if at the compilation unit level, because in this
5124          --  case the flag is set by the binder generated elaboration routine.
5125
5126          if Nkind (Parent (N)) = N_Compilation_Unit then
5127             null;
5128
5129          --  Here we do need to generate an assignment statement
5130
5131          else
5132             Check_Restriction (No_Elaboration_Code, N);
5133             Asn :=
5134               Make_Assignment_Statement (Loc,
5135                 Name       => New_Occurrence_Of (Ent, Loc),
5136                 Expression => New_Occurrence_Of (Standard_True, Loc));
5137
5138             if Nkind (Parent (N)) = N_Subunit then
5139                Insert_After (Corresponding_Stub (Parent (N)), Asn);
5140             else
5141                Insert_After (N, Asn);
5142             end if;
5143
5144             Analyze (Asn);
5145
5146             --  Kill current value indication. This is necessary because
5147             --  the tests of this flag are inserted out of sequence and must
5148             --  not pick up bogus indications of the wrong constant value.
5149
5150             Set_Current_Value (Ent, Empty);
5151          end if;
5152       end if;
5153    end Set_Elaboration_Flag;
5154
5155    ----------------------------
5156    -- Set_Renamed_Subprogram --
5157    ----------------------------
5158
5159    procedure Set_Renamed_Subprogram (N : Node_Id; E : Entity_Id) is
5160    begin
5161       --  If input node is an identifier, we can just reset it
5162
5163       if Nkind (N) = N_Identifier then
5164          Set_Chars  (N, Chars (E));
5165          Set_Entity (N, E);
5166
5167          --  Otherwise we have to do a rewrite, preserving Comes_From_Source
5168
5169       else
5170          declare
5171             CS : constant Boolean := Comes_From_Source (N);
5172          begin
5173             Rewrite (N, Make_Identifier (Sloc (N), Chars => Chars (E)));
5174             Set_Entity (N, E);
5175             Set_Comes_From_Source (N, CS);
5176             Set_Analyzed (N, True);
5177          end;
5178       end if;
5179    end Set_Renamed_Subprogram;
5180
5181    --------------------------
5182    -- Target_Has_Fixed_Ops --
5183    --------------------------
5184
5185    Integer_Sized_Small : Ureal;
5186    --  Set to 2.0 ** -(Integer'Size - 1) the first time that this
5187    --  function is called (we don't want to compute it more than once!)
5188
5189    Long_Integer_Sized_Small : Ureal;
5190    --  Set to 2.0 ** -(Long_Integer'Size - 1) the first time that this
5191    --  functoin is called (we don't want to compute it more than once)
5192
5193    First_Time_For_THFO : Boolean := True;
5194    --  Set to False after first call (if Fractional_Fixed_Ops_On_Target)
5195
5196    function Target_Has_Fixed_Ops
5197      (Left_Typ   : Entity_Id;
5198       Right_Typ  : Entity_Id;
5199       Result_Typ : Entity_Id) return Boolean
5200    is
5201       function Is_Fractional_Type (Typ : Entity_Id) return Boolean;
5202       --  Return True if the given type is a fixed-point type with a small
5203       --  value equal to 2 ** (-(T'Object_Size - 1)) and whose values have
5204       --  an absolute value less than 1.0. This is currently limited
5205       --  to fixed-point types that map to Integer or Long_Integer.
5206
5207       ------------------------
5208       -- Is_Fractional_Type --
5209       ------------------------
5210
5211       function Is_Fractional_Type (Typ : Entity_Id) return Boolean is
5212       begin
5213          if Esize (Typ) = Standard_Integer_Size then
5214             return Small_Value (Typ) = Integer_Sized_Small;
5215
5216          elsif Esize (Typ) = Standard_Long_Integer_Size then
5217             return Small_Value (Typ) = Long_Integer_Sized_Small;
5218
5219          else
5220             return False;
5221          end if;
5222       end Is_Fractional_Type;
5223
5224    --  Start of processing for Target_Has_Fixed_Ops
5225
5226    begin
5227       --  Return False if Fractional_Fixed_Ops_On_Target is false
5228
5229       if not Fractional_Fixed_Ops_On_Target then
5230          return False;
5231       end if;
5232
5233       --  Here the target has Fractional_Fixed_Ops, if first time, compute
5234       --  standard constants used by Is_Fractional_Type.
5235
5236       if First_Time_For_THFO then
5237          First_Time_For_THFO := False;
5238
5239          Integer_Sized_Small :=
5240            UR_From_Components
5241              (Num   => Uint_1,
5242               Den   => UI_From_Int (Standard_Integer_Size - 1),
5243               Rbase => 2);
5244
5245          Long_Integer_Sized_Small :=
5246            UR_From_Components
5247              (Num   => Uint_1,
5248               Den   => UI_From_Int (Standard_Long_Integer_Size - 1),
5249               Rbase => 2);
5250       end if;
5251
5252       --  Return True if target supports fixed-by-fixed multiply/divide
5253       --  for fractional fixed-point types (see Is_Fractional_Type) and
5254       --  the operand and result types are equivalent fractional types.
5255
5256       return Is_Fractional_Type (Base_Type (Left_Typ))
5257         and then Is_Fractional_Type (Base_Type (Right_Typ))
5258         and then Is_Fractional_Type (Base_Type (Result_Typ))
5259         and then Esize (Left_Typ) = Esize (Right_Typ)
5260         and then Esize (Left_Typ) = Esize (Result_Typ);
5261    end Target_Has_Fixed_Ops;
5262
5263    ------------------------------------------
5264    -- Type_May_Have_Bit_Aligned_Components --
5265    ------------------------------------------
5266
5267    function Type_May_Have_Bit_Aligned_Components
5268      (Typ : Entity_Id) return Boolean
5269    is
5270    begin
5271       --  Array type, check component type
5272
5273       if Is_Array_Type (Typ) then
5274          return
5275            Type_May_Have_Bit_Aligned_Components (Component_Type (Typ));
5276
5277       --  Record type, check components
5278
5279       elsif Is_Record_Type (Typ) then
5280          declare
5281             E : Entity_Id;
5282
5283          begin
5284             E := First_Component_Or_Discriminant (Typ);
5285             while Present (E) loop
5286                if Component_May_Be_Bit_Aligned (E)
5287                  or else Type_May_Have_Bit_Aligned_Components (Etype (E))
5288                then
5289                   return True;
5290                end if;
5291
5292                Next_Component_Or_Discriminant (E);
5293             end loop;
5294
5295             return False;
5296          end;
5297
5298       --  Type other than array or record is always OK
5299
5300       else
5301          return False;
5302       end if;
5303    end Type_May_Have_Bit_Aligned_Components;
5304
5305    ----------------------------
5306    -- Wrap_Cleanup_Procedure --
5307    ----------------------------
5308
5309    procedure Wrap_Cleanup_Procedure (N : Node_Id) is
5310       Loc   : constant Source_Ptr := Sloc (N);
5311       Stseq : constant Node_Id    := Handled_Statement_Sequence (N);
5312       Stmts : constant List_Id    := Statements (Stseq);
5313
5314    begin
5315       if Abort_Allowed then
5316          Prepend_To (Stmts, Build_Runtime_Call (Loc, RE_Abort_Defer));
5317          Append_To  (Stmts, Build_Runtime_Call (Loc, RE_Abort_Undefer));
5318       end if;
5319    end Wrap_Cleanup_Procedure;
5320
5321 end Exp_Util;