OSDN Git Service

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