OSDN Git Service

PR 33870
[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 Entity_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 (AI_Elmt);
1389             end loop;
1390          end if;
1391       end Find_Secondary_Table;
1392
1393    --  Start of processing for Find_Interface_ADT
1394
1395    begin
1396       pragma Assert (Is_Interface (Iface));
1397
1398       --  Handle private types
1399
1400       if Has_Private_Declaration (Typ)
1401         and then Present (Full_View (Typ))
1402       then
1403          Typ := Full_View (Typ);
1404       end if;
1405
1406       --  Handle access types
1407
1408       if Is_Access_Type (Typ) then
1409          Typ := Directly_Designated_Type (Typ);
1410       end if;
1411
1412       --  Handle task and protected types implementing interfaces
1413
1414       if Is_Concurrent_Type (Typ) then
1415          Typ := Corresponding_Record_Type (Typ);
1416       end if;
1417
1418       pragma Assert
1419         (not Is_Class_Wide_Type (Typ)
1420           and then Ekind (Typ) /= E_Incomplete_Type);
1421
1422       ADT := Next_Elmt (First_Elmt (Access_Disp_Table (Typ)));
1423       pragma Assert (Present (Node (ADT)));
1424       Find_Secondary_Table (Typ);
1425       pragma Assert (Found);
1426       return Node (ADT);
1427    end Find_Interface_ADT;
1428
1429    ------------------------
1430    -- Find_Interface_Tag --
1431    ------------------------
1432
1433    function Find_Interface_Tag
1434      (T     : Entity_Id;
1435       Iface : Entity_Id) return Entity_Id
1436    is
1437       AI_Tag : Entity_Id;
1438       Found  : Boolean   := False;
1439       Typ    : Entity_Id := T;
1440
1441       Is_Primary_Tag : Boolean := False;
1442
1443       Is_Sync_Typ : Boolean := False;
1444       --  In case of non concurrent-record-types each parent-type has the
1445       --  tags associated with the interface types that are not implemented
1446       --  by the ancestors; concurrent-record-types have their whole list of
1447       --  interface tags (and this case requires some special management).
1448
1449       procedure Find_Tag (Typ : Entity_Id);
1450       --  Internal subprogram used to recursively climb to the ancestors
1451
1452       --------------
1453       -- Find_Tag --
1454       --------------
1455
1456       procedure Find_Tag (Typ : Entity_Id) is
1457          AI_Elmt : Elmt_Id;
1458          AI      : Node_Id;
1459
1460       begin
1461          --  Check if the interface is an immediate ancestor of the type and
1462          --  therefore shares the main tag.
1463
1464          if Typ = Iface then
1465             if Is_Sync_Typ then
1466                Is_Primary_Tag := True;
1467             else
1468                pragma Assert
1469                  (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1470                AI_Tag := First_Tag_Component (Typ);
1471             end if;
1472
1473             Found  := True;
1474             return;
1475          end if;
1476
1477          --  Handle synchronized interface derivations
1478
1479          if Is_Concurrent_Record_Type (Typ) then
1480             declare
1481                Iface_List : constant List_Id := Abstract_Interface_List (Typ);
1482             begin
1483                if Is_Non_Empty_List (Iface_List) then
1484                   Find_Tag (Etype (First (Iface_List)));
1485                end if;
1486             end;
1487
1488          --  Climb to the root type handling private types
1489
1490          elsif Present (Full_View (Etype (Typ))) then
1491             if Full_View (Etype (Typ)) /= Typ then
1492                Find_Tag (Full_View (Etype (Typ)));
1493             end if;
1494
1495          elsif Etype (Typ) /= Typ then
1496             Find_Tag (Etype (Typ));
1497          end if;
1498
1499          --  Traverse the list of interfaces implemented by the type
1500
1501          if not Found
1502            and then Present (Abstract_Interfaces (Typ))
1503            and then not (Is_Empty_Elmt_List (Abstract_Interfaces (Typ)))
1504          then
1505             --  Skip the tag associated with the primary table
1506
1507             if not Is_Sync_Typ then
1508                pragma Assert
1509                  (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1510                AI_Tag := Next_Tag_Component (First_Tag_Component (Typ));
1511                pragma Assert (Present (AI_Tag));
1512             end if;
1513
1514             AI_Elmt := First_Elmt (Abstract_Interfaces (Typ));
1515             while Present (AI_Elmt) loop
1516                AI := Node (AI_Elmt);
1517
1518                if AI = Iface or else Is_Ancestor (Iface, AI) then
1519                   Found := True;
1520                   return;
1521                end if;
1522
1523                AI_Tag := Next_Tag_Component (AI_Tag);
1524                Next_Elmt (AI_Elmt);
1525             end loop;
1526          end if;
1527       end Find_Tag;
1528
1529    --  Start of processing for Find_Interface_Tag
1530
1531    begin
1532       pragma Assert (Is_Interface (Iface));
1533
1534       --  Handle private types
1535
1536       if Has_Private_Declaration (Typ)
1537         and then Present (Full_View (Typ))
1538       then
1539          Typ := Full_View (Typ);
1540       end if;
1541
1542       --  Handle access types
1543
1544       if Is_Access_Type (Typ) then
1545          Typ := Directly_Designated_Type (Typ);
1546       end if;
1547
1548       --  Handle task and protected types implementing interfaces
1549
1550       if Is_Concurrent_Type (Typ) then
1551          Typ := Corresponding_Record_Type (Typ);
1552       end if;
1553
1554       if Is_Class_Wide_Type (Typ) then
1555          Typ := Etype (Typ);
1556       end if;
1557
1558       --  Handle entities from the limited view
1559
1560       if Ekind (Typ) = E_Incomplete_Type then
1561          pragma Assert (Present (Non_Limited_View (Typ)));
1562          Typ := Non_Limited_View (Typ);
1563       end if;
1564
1565       if not Is_Concurrent_Record_Type (Typ) then
1566          Find_Tag (Typ);
1567          pragma Assert (Found);
1568          return AI_Tag;
1569
1570       --  Concurrent record types
1571
1572       else
1573          Is_Sync_Typ := True;
1574          AI_Tag      := Next_Tag_Component (First_Tag_Component (Typ));
1575          Find_Tag (Typ);
1576          pragma Assert (Found);
1577
1578          if Is_Primary_Tag then
1579             return First_Tag_Component (Typ);
1580          else
1581             return AI_Tag;
1582          end if;
1583       end if;
1584    end Find_Interface_Tag;
1585
1586    --------------------
1587    -- Find_Interface --
1588    --------------------
1589
1590    function Find_Interface
1591      (T      : Entity_Id;
1592       Comp   : Entity_Id) return Entity_Id
1593    is
1594       AI_Tag : Entity_Id;
1595       Found  : Boolean := False;
1596       Iface  : Entity_Id;
1597       Typ    : Entity_Id := T;
1598
1599       Is_Sync_Typ : Boolean := False;
1600       --  In case of non concurrent-record-types each parent-type has the
1601       --  tags associated with the interface types that are not implemented
1602       --  by the ancestors; concurrent-record-types have their whole list of
1603       --  interface tags (and this case requires some special management).
1604
1605       procedure Find_Iface (Typ : Entity_Id);
1606       --  Internal subprogram used to recursively climb to the ancestors
1607
1608       ----------------
1609       -- Find_Iface --
1610       ----------------
1611
1612       procedure Find_Iface (Typ : Entity_Id) is
1613          AI_Elmt : Elmt_Id;
1614
1615       begin
1616          --  Climb to the root type
1617
1618          --  Handle sychronized interface derivations
1619
1620          if Is_Concurrent_Record_Type (Typ) then
1621             declare
1622                Iface_List : constant List_Id := Abstract_Interface_List (Typ);
1623             begin
1624                if Is_Non_Empty_List (Iface_List) then
1625                   Find_Iface (Etype (First (Iface_List)));
1626                end if;
1627             end;
1628
1629          --  Handle the common case
1630
1631          elsif Etype (Typ) /= Typ then
1632             pragma Assert (not Present (Full_View (Etype (Typ))));
1633             Find_Iface (Etype (Typ));
1634          end if;
1635
1636          --  Traverse the list of interfaces implemented by the type
1637
1638          if not Found
1639            and then Present (Abstract_Interfaces (Typ))
1640            and then not (Is_Empty_Elmt_List (Abstract_Interfaces (Typ)))
1641          then
1642             --  Skip the tag associated with the primary table
1643
1644             if not Is_Sync_Typ then
1645                pragma Assert
1646                  (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1647                AI_Tag := Next_Tag_Component (First_Tag_Component (Typ));
1648                pragma Assert (Present (AI_Tag));
1649             end if;
1650
1651             AI_Elmt := First_Elmt (Abstract_Interfaces (Typ));
1652             while Present (AI_Elmt) loop
1653                if AI_Tag = Comp then
1654                   Iface := Node (AI_Elmt);
1655                   Found := True;
1656                   return;
1657                end if;
1658
1659                AI_Tag := Next_Tag_Component (AI_Tag);
1660                Next_Elmt (AI_Elmt);
1661             end loop;
1662          end if;
1663       end Find_Iface;
1664
1665    --  Start of processing for Find_Interface
1666
1667    begin
1668       --  Handle private types
1669
1670       if Has_Private_Declaration (Typ)
1671         and then Present (Full_View (Typ))
1672       then
1673          Typ := Full_View (Typ);
1674       end if;
1675
1676       --  Handle access types
1677
1678       if Is_Access_Type (Typ) then
1679          Typ := Directly_Designated_Type (Typ);
1680       end if;
1681
1682       --  Handle task and protected types implementing interfaces
1683
1684       if Is_Concurrent_Type (Typ) then
1685          Typ := Corresponding_Record_Type (Typ);
1686       end if;
1687
1688       if Is_Class_Wide_Type (Typ) then
1689          Typ := Etype (Typ);
1690       end if;
1691
1692       --  Handle entities from the limited view
1693
1694       if Ekind (Typ) = E_Incomplete_Type then
1695          pragma Assert (Present (Non_Limited_View (Typ)));
1696          Typ := Non_Limited_View (Typ);
1697       end if;
1698
1699       if Is_Concurrent_Record_Type (Typ) then
1700          Is_Sync_Typ := True;
1701          AI_Tag      := Next_Tag_Component (First_Tag_Component (Typ));
1702       end if;
1703
1704       Find_Iface (Typ);
1705       pragma Assert (Found);
1706       return Iface;
1707    end Find_Interface;
1708
1709    ------------------
1710    -- Find_Prim_Op --
1711    ------------------
1712
1713    function Find_Prim_Op (T : Entity_Id; Name : Name_Id) return Entity_Id is
1714       Prim : Elmt_Id;
1715       Typ  : Entity_Id := T;
1716       Op   : Entity_Id;
1717
1718    begin
1719       if Is_Class_Wide_Type (Typ) then
1720          Typ := Root_Type (Typ);
1721       end if;
1722
1723       Typ := Underlying_Type (Typ);
1724
1725       --  Loop through primitive operations
1726
1727       Prim := First_Elmt (Primitive_Operations (Typ));
1728       while Present (Prim) loop
1729          Op := Node (Prim);
1730
1731          --  We can retrieve primitive operations by name if it is an internal
1732          --  name. For equality we must check that both of its operands have
1733          --  the same type, to avoid confusion with user-defined equalities
1734          --  than may have a non-symmetric signature.
1735
1736          exit when Chars (Op) = Name
1737            and then
1738              (Name /= Name_Op_Eq
1739                 or else Etype (First_Entity (Op)) = Etype (Last_Entity (Op)));
1740
1741          Next_Elmt (Prim);
1742          pragma Assert (Present (Prim));
1743       end loop;
1744
1745       return Node (Prim);
1746    end Find_Prim_Op;
1747
1748    ------------------
1749    -- Find_Prim_Op --
1750    ------------------
1751
1752    function Find_Prim_Op
1753      (T    : Entity_Id;
1754       Name : TSS_Name_Type) return Entity_Id
1755    is
1756       Prim : Elmt_Id;
1757       Typ  : Entity_Id := T;
1758
1759    begin
1760       if Is_Class_Wide_Type (Typ) then
1761          Typ := Root_Type (Typ);
1762       end if;
1763
1764       Typ := Underlying_Type (Typ);
1765
1766       Prim := First_Elmt (Primitive_Operations (Typ));
1767       while not Is_TSS (Node (Prim), Name) loop
1768          Next_Elmt (Prim);
1769          pragma Assert (Present (Prim));
1770       end loop;
1771
1772       return Node (Prim);
1773    end Find_Prim_Op;
1774
1775    ----------------------
1776    -- Force_Evaluation --
1777    ----------------------
1778
1779    procedure Force_Evaluation (Exp : Node_Id; Name_Req : Boolean := False) is
1780    begin
1781       Remove_Side_Effects (Exp, Name_Req, Variable_Ref => True);
1782    end Force_Evaluation;
1783
1784    ------------------------
1785    -- Generate_Poll_Call --
1786    ------------------------
1787
1788    procedure Generate_Poll_Call (N : Node_Id) is
1789    begin
1790       --  No poll call if polling not active
1791
1792       if not Polling_Required then
1793          return;
1794
1795       --  Otherwise generate require poll call
1796
1797       else
1798          Insert_Before_And_Analyze (N,
1799            Make_Procedure_Call_Statement (Sloc (N),
1800              Name => New_Occurrence_Of (RTE (RE_Poll), Sloc (N))));
1801       end if;
1802    end Generate_Poll_Call;
1803
1804    ---------------------------------
1805    -- Get_Current_Value_Condition --
1806    ---------------------------------
1807
1808    --  Note: the implementation of this procedure is very closely tied to the
1809    --  implementation of Set_Current_Value_Condition. In the Get procedure, we
1810    --  interpret Current_Value fields set by the Set procedure, so the two
1811    --  procedures need to be closely coordinated.
1812
1813    procedure Get_Current_Value_Condition
1814      (Var : Node_Id;
1815       Op  : out Node_Kind;
1816       Val : out Node_Id)
1817    is
1818       Loc : constant Source_Ptr := Sloc (Var);
1819       Ent : constant Entity_Id  := Entity (Var);
1820
1821       procedure Process_Current_Value_Condition
1822         (N : Node_Id;
1823          S : Boolean);
1824       --  N is an expression which holds either True (S = True) or False (S =
1825       --  False) in the condition. This procedure digs out the expression and
1826       --  if it refers to Ent, sets Op and Val appropriately.
1827
1828       -------------------------------------
1829       -- Process_Current_Value_Condition --
1830       -------------------------------------
1831
1832       procedure Process_Current_Value_Condition
1833         (N : Node_Id;
1834          S : Boolean)
1835       is
1836          Cond : Node_Id;
1837          Sens : Boolean;
1838
1839       begin
1840          Cond := N;
1841          Sens := S;
1842
1843          --  Deal with NOT operators, inverting sense
1844
1845          while Nkind (Cond) = N_Op_Not loop
1846             Cond := Right_Opnd (Cond);
1847             Sens := not Sens;
1848          end loop;
1849
1850          --  Deal with AND THEN and AND cases
1851
1852          if Nkind (Cond) = N_And_Then
1853            or else Nkind (Cond) = N_Op_And
1854          then
1855             --  Don't ever try to invert a condition that is of the form
1856             --  of an AND or AND THEN (since we are not doing sufficiently
1857             --  general processing to allow this).
1858
1859             if Sens = False then
1860                Op  := N_Empty;
1861                Val := Empty;
1862                return;
1863             end if;
1864
1865             --  Recursively process AND and AND THEN branches
1866
1867             Process_Current_Value_Condition (Left_Opnd (Cond), True);
1868
1869             if Op /= N_Empty then
1870                return;
1871             end if;
1872
1873             Process_Current_Value_Condition (Right_Opnd (Cond), True);
1874             return;
1875
1876          --  Case of relational operator
1877
1878          elsif Nkind (Cond) in N_Op_Compare then
1879             Op := Nkind (Cond);
1880
1881             --  Invert sense of test if inverted test
1882
1883             if Sens = False then
1884                case Op is
1885                   when N_Op_Eq => Op := N_Op_Ne;
1886                   when N_Op_Ne => Op := N_Op_Eq;
1887                   when N_Op_Lt => Op := N_Op_Ge;
1888                   when N_Op_Gt => Op := N_Op_Le;
1889                   when N_Op_Le => Op := N_Op_Gt;
1890                   when N_Op_Ge => Op := N_Op_Lt;
1891                   when others  => raise Program_Error;
1892                end case;
1893             end if;
1894
1895             --  Case of entity op value
1896
1897             if Is_Entity_Name (Left_Opnd (Cond))
1898               and then Ent = Entity (Left_Opnd (Cond))
1899               and then Compile_Time_Known_Value (Right_Opnd (Cond))
1900             then
1901                Val := Right_Opnd (Cond);
1902
1903             --  Case of value op entity
1904
1905             elsif Is_Entity_Name (Right_Opnd (Cond))
1906               and then Ent = Entity (Right_Opnd (Cond))
1907               and then Compile_Time_Known_Value (Left_Opnd (Cond))
1908             then
1909                Val := Left_Opnd (Cond);
1910
1911                --  We are effectively swapping operands
1912
1913                case Op is
1914                   when N_Op_Eq => null;
1915                   when N_Op_Ne => null;
1916                   when N_Op_Lt => Op := N_Op_Gt;
1917                   when N_Op_Gt => Op := N_Op_Lt;
1918                   when N_Op_Le => Op := N_Op_Ge;
1919                   when N_Op_Ge => Op := N_Op_Le;
1920                   when others  => raise Program_Error;
1921                end case;
1922
1923             else
1924                Op := N_Empty;
1925             end if;
1926
1927             return;
1928
1929             --  Case of Boolean variable reference, return as though the
1930             --  reference had said var = True.
1931
1932          else
1933             if Is_Entity_Name (Cond)
1934               and then Ent = Entity (Cond)
1935             then
1936                Val := New_Occurrence_Of (Standard_True, Sloc (Cond));
1937
1938                if Sens = False then
1939                   Op := N_Op_Ne;
1940                else
1941                   Op := N_Op_Eq;
1942                end if;
1943             end if;
1944          end if;
1945       end Process_Current_Value_Condition;
1946
1947    --  Start of processing for Get_Current_Value_Condition
1948
1949    begin
1950       Op  := N_Empty;
1951       Val := Empty;
1952
1953       --  Immediate return, nothing doing, if this is not an object
1954
1955       if Ekind (Ent) not in Object_Kind then
1956          return;
1957       end if;
1958
1959       --  Otherwise examine current value
1960
1961       declare
1962          CV   : constant Node_Id := Current_Value (Ent);
1963          Sens : Boolean;
1964          Stm  : Node_Id;
1965
1966       begin
1967          --  If statement. Condition is known true in THEN section, known False
1968          --  in any ELSIF or ELSE part, and unknown outside the IF statement.
1969
1970          if Nkind (CV) = N_If_Statement then
1971
1972             --  Before start of IF statement
1973
1974             if Loc < Sloc (CV) then
1975                return;
1976
1977                --  After end of IF statement
1978
1979             elsif Loc >= Sloc (CV) + Text_Ptr (UI_To_Int (End_Span (CV))) then
1980                return;
1981             end if;
1982
1983             --  At this stage we know that we are within the IF statement, but
1984             --  unfortunately, the tree does not record the SLOC of the ELSE so
1985             --  we cannot use a simple SLOC comparison to distinguish between
1986             --  the then/else statements, so we have to climb the tree.
1987
1988             declare
1989                N : Node_Id;
1990
1991             begin
1992                N := Parent (Var);
1993                while Parent (N) /= CV loop
1994                   N := Parent (N);
1995
1996                   --  If we fall off the top of the tree, then that's odd, but
1997                   --  perhaps it could occur in some error situation, and the
1998                   --  safest response is simply to assume that the outcome of
1999                   --  the condition is unknown. No point in bombing during an
2000                   --  attempt to optimize things.
2001
2002                   if No (N) then
2003                      return;
2004                   end if;
2005                end loop;
2006
2007                --  Now we have N pointing to a node whose parent is the IF
2008                --  statement in question, so now we can tell if we are within
2009                --  the THEN statements.
2010
2011                if Is_List_Member (N)
2012                  and then List_Containing (N) = Then_Statements (CV)
2013                then
2014                   Sens := True;
2015
2016                --  If the variable reference does not come from source, we
2017                --  cannot reliably tell whether it appears in the else part.
2018                --  In particular, if if appears in generated code for a node
2019                --  that requires finalization, it may be attached to a list
2020                --  that has not been yet inserted into the code. For now,
2021                --  treat it as unknown.
2022
2023                elsif not Comes_From_Source (N) then
2024                   return;
2025
2026                --  Otherwise we must be in ELSIF or ELSE part
2027
2028                else
2029                   Sens := False;
2030                end if;
2031             end;
2032
2033             --  ELSIF part. Condition is known true within the referenced
2034             --  ELSIF, known False in any subsequent ELSIF or ELSE part, and
2035             --  unknown before the ELSE part or after the IF statement.
2036
2037          elsif Nkind (CV) = N_Elsif_Part then
2038             Stm := Parent (CV);
2039
2040             --  Before start of ELSIF part
2041
2042             if Loc < Sloc (CV) then
2043                return;
2044
2045                --  After end of IF statement
2046
2047             elsif Loc >= Sloc (Stm) +
2048               Text_Ptr (UI_To_Int (End_Span (Stm)))
2049             then
2050                return;
2051             end if;
2052
2053             --  Again we lack the SLOC of the ELSE, so we need to climb the
2054             --  tree to see if we are within the ELSIF part in question.
2055
2056             declare
2057                N : Node_Id;
2058
2059             begin
2060                N := Parent (Var);
2061                while Parent (N) /= Stm loop
2062                   N := Parent (N);
2063
2064                   --  If we fall off the top of the tree, then that's odd, but
2065                   --  perhaps it could occur in some error situation, and the
2066                   --  safest response is simply to assume that the outcome of
2067                   --  the condition is unknown. No point in bombing during an
2068                   --  attempt to optimize things.
2069
2070                   if No (N) then
2071                      return;
2072                   end if;
2073                end loop;
2074
2075                --  Now we have N pointing to a node whose parent is the IF
2076                --  statement in question, so see if is the ELSIF part we want.
2077                --  the THEN statements.
2078
2079                if N = CV then
2080                   Sens := True;
2081
2082                   --  Otherwise we must be in susbequent ELSIF or ELSE part
2083
2084                else
2085                   Sens := False;
2086                end if;
2087             end;
2088
2089          --  Iteration scheme of while loop. The condition is known to be
2090          --  true within the body of the loop.
2091
2092          elsif Nkind (CV) = N_Iteration_Scheme then
2093             declare
2094                Loop_Stmt : constant Node_Id := Parent (CV);
2095
2096             begin
2097                --  Before start of body of loop
2098
2099                if Loc < Sloc (Loop_Stmt) then
2100                   return;
2101
2102                --  After end of LOOP statement
2103
2104                elsif Loc >= Sloc (End_Label (Loop_Stmt)) then
2105                   return;
2106
2107                --  We are within the body of the loop
2108
2109                else
2110                   Sens := True;
2111                end if;
2112             end;
2113
2114          --  All other cases of Current_Value settings
2115
2116          else
2117             return;
2118          end if;
2119
2120          --  If we fall through here, then we have a reportable condition, Sens
2121          --  is True if the condition is true and False if it needs inverting.
2122
2123          Process_Current_Value_Condition (Condition (CV), Sens);
2124       end;
2125    end Get_Current_Value_Condition;
2126
2127    ---------------------------------
2128    -- Has_Controlled_Coextensions --
2129    ---------------------------------
2130
2131    function Has_Controlled_Coextensions (Typ : Entity_Id) return Boolean is
2132       D_Typ : Entity_Id;
2133       Discr : Entity_Id;
2134
2135    begin
2136       --  Only consider record types
2137
2138       if Ekind (Typ) /= E_Record_Type
2139         and then Ekind (Typ) /= E_Record_Subtype
2140       then
2141          return False;
2142       end if;
2143
2144       if Has_Discriminants (Typ) then
2145          Discr := First_Discriminant (Typ);
2146          while Present (Discr) loop
2147             D_Typ := Etype (Discr);
2148
2149             if Ekind (D_Typ) = E_Anonymous_Access_Type
2150               and then
2151                 (Is_Controlled (Directly_Designated_Type (D_Typ))
2152                    or else
2153                  Is_Concurrent_Type (Directly_Designated_Type (D_Typ)))
2154             then
2155                return True;
2156             end if;
2157
2158             Next_Discriminant (Discr);
2159          end loop;
2160       end if;
2161
2162       return False;
2163    end Has_Controlled_Coextensions;
2164
2165    --------------------
2166    -- Homonym_Number --
2167    --------------------
2168
2169    function Homonym_Number (Subp : Entity_Id) return Nat is
2170       Count : Nat;
2171       Hom   : Entity_Id;
2172
2173    begin
2174       Count := 1;
2175       Hom := Homonym (Subp);
2176       while Present (Hom) loop
2177          if Scope (Hom) = Scope (Subp) then
2178             Count := Count + 1;
2179          end if;
2180
2181          Hom := Homonym (Hom);
2182       end loop;
2183
2184       return Count;
2185    end Homonym_Number;
2186
2187    ------------------------------
2188    -- In_Unconditional_Context --
2189    ------------------------------
2190
2191    function In_Unconditional_Context (Node : Node_Id) return Boolean is
2192       P : Node_Id;
2193
2194    begin
2195       P := Node;
2196       while Present (P) loop
2197          case Nkind (P) is
2198             when N_Subprogram_Body =>
2199                return True;
2200
2201             when N_If_Statement =>
2202                return False;
2203
2204             when N_Loop_Statement =>
2205                return False;
2206
2207             when N_Case_Statement =>
2208                return False;
2209
2210             when others =>
2211                P := Parent (P);
2212          end case;
2213       end loop;
2214
2215       return False;
2216    end In_Unconditional_Context;
2217
2218    -------------------
2219    -- Insert_Action --
2220    -------------------
2221
2222    procedure Insert_Action (Assoc_Node : Node_Id; Ins_Action : Node_Id) is
2223    begin
2224       if Present (Ins_Action) then
2225          Insert_Actions (Assoc_Node, New_List (Ins_Action));
2226       end if;
2227    end Insert_Action;
2228
2229    --  Version with check(s) suppressed
2230
2231    procedure Insert_Action
2232      (Assoc_Node : Node_Id; Ins_Action : Node_Id; Suppress : Check_Id)
2233    is
2234    begin
2235       Insert_Actions (Assoc_Node, New_List (Ins_Action), Suppress);
2236    end Insert_Action;
2237
2238    --------------------
2239    -- Insert_Actions --
2240    --------------------
2241
2242    procedure Insert_Actions (Assoc_Node : Node_Id; Ins_Actions : List_Id) is
2243       N : Node_Id;
2244       P : Node_Id;
2245
2246       Wrapped_Node : Node_Id := Empty;
2247
2248    begin
2249       if No (Ins_Actions) or else Is_Empty_List (Ins_Actions) then
2250          return;
2251       end if;
2252
2253       --  Ignore insert of actions from inside default expression in the
2254       --  special preliminary analyze mode. Any insertions at this point
2255       --  have no relevance, since we are only doing the analyze to freeze
2256       --  the types of any static expressions. See section "Handling of
2257       --  Default Expressions" in the spec of package Sem for further details.
2258
2259       if In_Default_Expression then
2260          return;
2261       end if;
2262
2263       --  If the action derives from stuff inside a record, then the actions
2264       --  are attached to the current scope, to be inserted and analyzed on
2265       --  exit from the scope. The reason for this is that we may also
2266       --  be generating freeze actions at the same time, and they must
2267       --  eventually be elaborated in the correct order.
2268
2269       if Is_Record_Type (Current_Scope)
2270         and then not Is_Frozen (Current_Scope)
2271       then
2272          if No (Scope_Stack.Table
2273            (Scope_Stack.Last).Pending_Freeze_Actions)
2274          then
2275             Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions :=
2276               Ins_Actions;
2277          else
2278             Append_List
2279               (Ins_Actions,
2280                Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions);
2281          end if;
2282
2283          return;
2284       end if;
2285
2286       --  We now intend to climb up the tree to find the right point to
2287       --  insert the actions. We start at Assoc_Node, unless this node is
2288       --  a subexpression in which case we start with its parent. We do this
2289       --  for two reasons. First it speeds things up. Second, if Assoc_Node
2290       --  is itself one of the special nodes like N_And_Then, then we assume
2291       --  that an initial request to insert actions for such a node does not
2292       --  expect the actions to get deposited in the node for later handling
2293       --  when the node is expanded, since clearly the node is being dealt
2294       --  with by the caller. Note that in the subexpression case, N is
2295       --  always the child we came from.
2296
2297       --  N_Raise_xxx_Error is an annoying special case, it is a statement
2298       --  if it has type Standard_Void_Type, and a subexpression otherwise.
2299       --  otherwise. Procedure attribute references are also statements.
2300
2301       if Nkind (Assoc_Node) in N_Subexpr
2302         and then (Nkind (Assoc_Node) in N_Raise_xxx_Error
2303                    or else Etype (Assoc_Node) /= Standard_Void_Type)
2304         and then (Nkind (Assoc_Node) /= N_Attribute_Reference
2305                    or else
2306                      not Is_Procedure_Attribute_Name
2307                            (Attribute_Name (Assoc_Node)))
2308       then
2309          P := Assoc_Node;             -- ??? does not agree with above!
2310          N := Parent (Assoc_Node);
2311
2312       --  Non-subexpression case. Note that N is initially Empty in this
2313       --  case (N is only guaranteed Non-Empty in the subexpr case).
2314
2315       else
2316          P := Assoc_Node;
2317          N := Empty;
2318       end if;
2319
2320       --  Capture root of the transient scope
2321
2322       if Scope_Is_Transient then
2323          Wrapped_Node := Node_To_Be_Wrapped;
2324       end if;
2325
2326       loop
2327          pragma Assert (Present (P));
2328
2329          case Nkind (P) is
2330
2331             --  Case of right operand of AND THEN or OR ELSE. Put the actions
2332             --  in the Actions field of the right operand. They will be moved
2333             --  out further when the AND THEN or OR ELSE operator is expanded.
2334             --  Nothing special needs to be done for the left operand since
2335             --  in that case the actions are executed unconditionally.
2336
2337             when N_And_Then | N_Or_Else =>
2338                if N = Right_Opnd (P) then
2339                   if Present (Actions (P)) then
2340                      Insert_List_After_And_Analyze
2341                       (Last (Actions (P)), Ins_Actions);
2342                   else
2343                      Set_Actions (P, Ins_Actions);
2344                      Analyze_List (Actions (P));
2345                   end if;
2346
2347                   return;
2348                end if;
2349
2350             --  Then or Else operand of conditional expression. Add actions to
2351             --  Then_Actions or Else_Actions field as appropriate. The actions
2352             --  will be moved further out when the conditional is expanded.
2353
2354             when N_Conditional_Expression =>
2355                declare
2356                   ThenX : constant Node_Id := Next (First (Expressions (P)));
2357                   ElseX : constant Node_Id := Next (ThenX);
2358
2359                begin
2360                   --  Actions belong to the then expression, temporarily
2361                   --  place them as Then_Actions of the conditional expr.
2362                   --  They will be moved to the proper place later when
2363                   --  the conditional expression is expanded.
2364
2365                   if N = ThenX then
2366                      if Present (Then_Actions (P)) then
2367                         Insert_List_After_And_Analyze
2368                           (Last (Then_Actions (P)), Ins_Actions);
2369                      else
2370                         Set_Then_Actions (P, Ins_Actions);
2371                         Analyze_List (Then_Actions (P));
2372                      end if;
2373
2374                      return;
2375
2376                   --  Actions belong to the else expression, temporarily
2377                   --  place them as Else_Actions of the conditional expr.
2378                   --  They will be moved to the proper place later when
2379                   --  the conditional expression is expanded.
2380
2381                   elsif N = ElseX then
2382                      if Present (Else_Actions (P)) then
2383                         Insert_List_After_And_Analyze
2384                           (Last (Else_Actions (P)), Ins_Actions);
2385                      else
2386                         Set_Else_Actions (P, Ins_Actions);
2387                         Analyze_List (Else_Actions (P));
2388                      end if;
2389
2390                      return;
2391
2392                   --  Actions belong to the condition. In this case they are
2393                   --  unconditionally executed, and so we can continue the
2394                   --  search for the proper insert point.
2395
2396                   else
2397                      null;
2398                   end if;
2399                end;
2400
2401             --  Case of appearing in the condition of a while expression or
2402             --  elsif. We insert the actions into the Condition_Actions field.
2403             --  They will be moved further out when the while loop or elsif
2404             --  is analyzed.
2405
2406             when N_Iteration_Scheme |
2407                  N_Elsif_Part
2408             =>
2409                if N = Condition (P) then
2410                   if Present (Condition_Actions (P)) then
2411                      Insert_List_After_And_Analyze
2412                        (Last (Condition_Actions (P)), Ins_Actions);
2413                   else
2414                      Set_Condition_Actions (P, Ins_Actions);
2415
2416                      --  Set the parent of the insert actions explicitly.
2417                      --  This is not a syntactic field, but we need the
2418                      --  parent field set, in particular so that freeze
2419                      --  can understand that it is dealing with condition
2420                      --  actions, and properly insert the freezing actions.
2421
2422                      Set_Parent (Ins_Actions, P);
2423                      Analyze_List (Condition_Actions (P));
2424                   end if;
2425
2426                   return;
2427                end if;
2428
2429             --  Statements, declarations, pragmas, representation clauses
2430
2431             when
2432                --  Statements
2433
2434                N_Procedure_Call_Statement               |
2435                N_Statement_Other_Than_Procedure_Call    |
2436
2437                --  Pragmas
2438
2439                N_Pragma                                 |
2440
2441                --  Representation_Clause
2442
2443                N_At_Clause                              |
2444                N_Attribute_Definition_Clause            |
2445                N_Enumeration_Representation_Clause      |
2446                N_Record_Representation_Clause           |
2447
2448                --  Declarations
2449
2450                N_Abstract_Subprogram_Declaration        |
2451                N_Entry_Body                             |
2452                N_Exception_Declaration                  |
2453                N_Exception_Renaming_Declaration         |
2454                N_Formal_Abstract_Subprogram_Declaration |
2455                N_Formal_Concrete_Subprogram_Declaration |
2456                N_Formal_Object_Declaration              |
2457                N_Formal_Type_Declaration                |
2458                N_Full_Type_Declaration                  |
2459                N_Function_Instantiation                 |
2460                N_Generic_Function_Renaming_Declaration  |
2461                N_Generic_Package_Declaration            |
2462                N_Generic_Package_Renaming_Declaration   |
2463                N_Generic_Procedure_Renaming_Declaration |
2464                N_Generic_Subprogram_Declaration         |
2465                N_Implicit_Label_Declaration             |
2466                N_Incomplete_Type_Declaration            |
2467                N_Number_Declaration                     |
2468                N_Object_Declaration                     |
2469                N_Object_Renaming_Declaration            |
2470                N_Package_Body                           |
2471                N_Package_Body_Stub                      |
2472                N_Package_Declaration                    |
2473                N_Package_Instantiation                  |
2474                N_Package_Renaming_Declaration           |
2475                N_Private_Extension_Declaration          |
2476                N_Private_Type_Declaration               |
2477                N_Procedure_Instantiation                |
2478                N_Protected_Body                         |
2479                N_Protected_Body_Stub                    |
2480                N_Protected_Type_Declaration             |
2481                N_Single_Task_Declaration                |
2482                N_Subprogram_Body                        |
2483                N_Subprogram_Body_Stub                   |
2484                N_Subprogram_Declaration                 |
2485                N_Subprogram_Renaming_Declaration        |
2486                N_Subtype_Declaration                    |
2487                N_Task_Body                              |
2488                N_Task_Body_Stub                         |
2489                N_Task_Type_Declaration                  |
2490
2491                --  Freeze entity behaves like a declaration or statement
2492
2493                N_Freeze_Entity
2494             =>
2495                --  Do not insert here if the item is not a list member (this
2496                --  happens for example with a triggering statement, and the
2497                --  proper approach is to insert before the entire select).
2498
2499                if not Is_List_Member (P) then
2500                   null;
2501
2502                --  Do not insert if parent of P is an N_Component_Association
2503                --  node (i.e. we are in the context of an N_Aggregate or
2504                --  N_Extension_Aggregate node. In this case we want to insert
2505                --  before the entire aggregate.
2506
2507                elsif Nkind (Parent (P)) = N_Component_Association then
2508                   null;
2509
2510                --  Do not insert if the parent of P is either an N_Variant
2511                --  node or an N_Record_Definition node, meaning in either
2512                --  case that P is a member of a component list, and that
2513                --  therefore the actions should be inserted outside the
2514                --  complete record declaration.
2515
2516                elsif Nkind (Parent (P)) = N_Variant
2517                  or else Nkind (Parent (P)) = N_Record_Definition
2518                then
2519                   null;
2520
2521                --  Do not insert freeze nodes within the loop generated for
2522                --  an aggregate, because they may be elaborated too late for
2523                --  subsequent use in the back end: within a package spec the
2524                --  loop is part of the elaboration procedure and is only
2525                --  elaborated during the second pass.
2526                --  If the loop comes from source, or the entity is local to
2527                --  the loop itself it must remain within.
2528
2529                elsif Nkind (Parent (P)) = N_Loop_Statement
2530                  and then not Comes_From_Source (Parent (P))
2531                  and then Nkind (First (Ins_Actions)) = N_Freeze_Entity
2532                  and then
2533                    Scope (Entity (First (Ins_Actions))) /= Current_Scope
2534                then
2535                   null;
2536
2537                --  Otherwise we can go ahead and do the insertion
2538
2539                elsif P = Wrapped_Node then
2540                   Store_Before_Actions_In_Scope (Ins_Actions);
2541                   return;
2542
2543                else
2544                   Insert_List_Before_And_Analyze (P, Ins_Actions);
2545                   return;
2546                end if;
2547
2548             --  A special case, N_Raise_xxx_Error can act either as a
2549             --  statement or a subexpression. We tell the difference
2550             --  by looking at the Etype. It is set to Standard_Void_Type
2551             --  in the statement case.
2552
2553             when
2554                N_Raise_xxx_Error =>
2555                   if Etype (P) = Standard_Void_Type then
2556                      if  P = Wrapped_Node then
2557                         Store_Before_Actions_In_Scope (Ins_Actions);
2558                      else
2559                         Insert_List_Before_And_Analyze (P, Ins_Actions);
2560                      end if;
2561
2562                      return;
2563
2564                   --  In the subexpression case, keep climbing
2565
2566                   else
2567                      null;
2568                   end if;
2569
2570             --  If a component association appears within a loop created for
2571             --  an array aggregate, attach the actions to the association so
2572             --  they can be subsequently inserted within the loop. For other
2573             --  component associations insert outside of the aggregate. For
2574             --  an association that will generate a loop, its Loop_Actions
2575             --  attribute is already initialized (see exp_aggr.adb).
2576
2577             --  The list of loop_actions can in turn generate additional ones,
2578             --  that are inserted before the associated node. If the associated
2579             --  node is outside the aggregate, the new actions are collected
2580             --  at the end of the loop actions, to respect the order in which
2581             --  they are to be elaborated.
2582
2583             when
2584                N_Component_Association =>
2585                   if Nkind (Parent (P)) = N_Aggregate
2586                     and then Present (Loop_Actions (P))
2587                   then
2588                      if Is_Empty_List (Loop_Actions (P)) then
2589                         Set_Loop_Actions (P, Ins_Actions);
2590                         Analyze_List (Ins_Actions);
2591
2592                      else
2593                         declare
2594                            Decl : Node_Id;
2595
2596                         begin
2597                            --  Check whether these actions were generated
2598                            --  by a declaration that is part of the loop_
2599                            --  actions for the component_association.
2600
2601                            Decl := Assoc_Node;
2602                            while Present (Decl) loop
2603                               exit when Parent (Decl) = P
2604                                 and then Is_List_Member (Decl)
2605                                 and then
2606                                   List_Containing (Decl) = Loop_Actions (P);
2607                               Decl := Parent (Decl);
2608                            end loop;
2609
2610                            if Present (Decl) then
2611                               Insert_List_Before_And_Analyze
2612                                 (Decl, Ins_Actions);
2613                            else
2614                               Insert_List_After_And_Analyze
2615                                 (Last (Loop_Actions (P)), Ins_Actions);
2616                            end if;
2617                         end;
2618                      end if;
2619
2620                      return;
2621
2622                   else
2623                      null;
2624                   end if;
2625
2626             --  Another special case, an attribute denoting a procedure call
2627
2628             when
2629                N_Attribute_Reference =>
2630                   if Is_Procedure_Attribute_Name (Attribute_Name (P)) then
2631                      if P = Wrapped_Node then
2632                         Store_Before_Actions_In_Scope (Ins_Actions);
2633                      else
2634                         Insert_List_Before_And_Analyze (P, Ins_Actions);
2635                      end if;
2636
2637                      return;
2638
2639                   --  In the subexpression case, keep climbing
2640
2641                   else
2642                      null;
2643                   end if;
2644
2645             --  For all other node types, keep climbing tree
2646
2647             when
2648                N_Abortable_Part                         |
2649                N_Accept_Alternative                     |
2650                N_Access_Definition                      |
2651                N_Access_Function_Definition             |
2652                N_Access_Procedure_Definition            |
2653                N_Access_To_Object_Definition            |
2654                N_Aggregate                              |
2655                N_Allocator                              |
2656                N_Case_Statement_Alternative             |
2657                N_Character_Literal                      |
2658                N_Compilation_Unit                       |
2659                N_Compilation_Unit_Aux                   |
2660                N_Component_Clause                       |
2661                N_Component_Declaration                  |
2662                N_Component_Definition                   |
2663                N_Component_List                         |
2664                N_Constrained_Array_Definition           |
2665                N_Decimal_Fixed_Point_Definition         |
2666                N_Defining_Character_Literal             |
2667                N_Defining_Identifier                    |
2668                N_Defining_Operator_Symbol               |
2669                N_Defining_Program_Unit_Name             |
2670                N_Delay_Alternative                      |
2671                N_Delta_Constraint                       |
2672                N_Derived_Type_Definition                |
2673                N_Designator                             |
2674                N_Digits_Constraint                      |
2675                N_Discriminant_Association               |
2676                N_Discriminant_Specification             |
2677                N_Empty                                  |
2678                N_Entry_Body_Formal_Part                 |
2679                N_Entry_Call_Alternative                 |
2680                N_Entry_Declaration                      |
2681                N_Entry_Index_Specification              |
2682                N_Enumeration_Type_Definition            |
2683                N_Error                                  |
2684                N_Exception_Handler                      |
2685                N_Expanded_Name                          |
2686                N_Explicit_Dereference                   |
2687                N_Extension_Aggregate                    |
2688                N_Floating_Point_Definition              |
2689                N_Formal_Decimal_Fixed_Point_Definition  |
2690                N_Formal_Derived_Type_Definition         |
2691                N_Formal_Discrete_Type_Definition        |
2692                N_Formal_Floating_Point_Definition       |
2693                N_Formal_Modular_Type_Definition         |
2694                N_Formal_Ordinary_Fixed_Point_Definition |
2695                N_Formal_Package_Declaration             |
2696                N_Formal_Private_Type_Definition         |
2697                N_Formal_Signed_Integer_Type_Definition  |
2698                N_Function_Call                          |
2699                N_Function_Specification                 |
2700                N_Generic_Association                    |
2701                N_Handled_Sequence_Of_Statements         |
2702                N_Identifier                             |
2703                N_In                                     |
2704                N_Index_Or_Discriminant_Constraint       |
2705                N_Indexed_Component                      |
2706                N_Integer_Literal                        |
2707                N_Itype_Reference                        |
2708                N_Label                                  |
2709                N_Loop_Parameter_Specification           |
2710                N_Mod_Clause                             |
2711                N_Modular_Type_Definition                |
2712                N_Not_In                                 |
2713                N_Null                                   |
2714                N_Op_Abs                                 |
2715                N_Op_Add                                 |
2716                N_Op_And                                 |
2717                N_Op_Concat                              |
2718                N_Op_Divide                              |
2719                N_Op_Eq                                  |
2720                N_Op_Expon                               |
2721                N_Op_Ge                                  |
2722                N_Op_Gt                                  |
2723                N_Op_Le                                  |
2724                N_Op_Lt                                  |
2725                N_Op_Minus                               |
2726                N_Op_Mod                                 |
2727                N_Op_Multiply                            |
2728                N_Op_Ne                                  |
2729                N_Op_Not                                 |
2730                N_Op_Or                                  |
2731                N_Op_Plus                                |
2732                N_Op_Rem                                 |
2733                N_Op_Rotate_Left                         |
2734                N_Op_Rotate_Right                        |
2735                N_Op_Shift_Left                          |
2736                N_Op_Shift_Right                         |
2737                N_Op_Shift_Right_Arithmetic              |
2738                N_Op_Subtract                            |
2739                N_Op_Xor                                 |
2740                N_Operator_Symbol                        |
2741                N_Ordinary_Fixed_Point_Definition        |
2742                N_Others_Choice                          |
2743                N_Package_Specification                  |
2744                N_Parameter_Association                  |
2745                N_Parameter_Specification                |
2746                N_Pop_Constraint_Error_Label             |
2747                N_Pop_Program_Error_Label                |
2748                N_Pop_Storage_Error_Label                |
2749                N_Pragma_Argument_Association            |
2750                N_Procedure_Specification                |
2751                N_Protected_Definition                   |
2752                N_Push_Constraint_Error_Label            |
2753                N_Push_Program_Error_Label               |
2754                N_Push_Storage_Error_Label               |
2755                N_Qualified_Expression                   |
2756                N_Range                                  |
2757                N_Range_Constraint                       |
2758                N_Real_Literal                           |
2759                N_Real_Range_Specification               |
2760                N_Record_Definition                      |
2761                N_Reference                              |
2762                N_Selected_Component                     |
2763                N_Signed_Integer_Type_Definition         |
2764                N_Single_Protected_Declaration           |
2765                N_Slice                                  |
2766                N_String_Literal                         |
2767                N_Subprogram_Info                        |
2768                N_Subtype_Indication                     |
2769                N_Subunit                                |
2770                N_Task_Definition                        |
2771                N_Terminate_Alternative                  |
2772                N_Triggering_Alternative                 |
2773                N_Type_Conversion                        |
2774                N_Unchecked_Expression                   |
2775                N_Unchecked_Type_Conversion              |
2776                N_Unconstrained_Array_Definition         |
2777                N_Unused_At_End                          |
2778                N_Unused_At_Start                        |
2779                N_Use_Package_Clause                     |
2780                N_Use_Type_Clause                        |
2781                N_Variant                                |
2782                N_Variant_Part                           |
2783                N_Validate_Unchecked_Conversion          |
2784                N_With_Clause
2785             =>
2786                null;
2787
2788          end case;
2789
2790          --  Make sure that inserted actions stay in the transient scope
2791
2792          if P = Wrapped_Node then
2793             Store_Before_Actions_In_Scope (Ins_Actions);
2794             return;
2795          end if;
2796
2797          --  If we fall through above tests, keep climbing tree
2798
2799          N := P;
2800
2801          if Nkind (Parent (N)) = N_Subunit then
2802
2803             --  This is the proper body corresponding to a stub. Insertion
2804             --  must be done at the point of the stub, which is in the decla-
2805             --  tive part of the parent unit.
2806
2807             P := Corresponding_Stub (Parent (N));
2808
2809          else
2810             P := Parent (N);
2811          end if;
2812       end loop;
2813    end Insert_Actions;
2814
2815    --  Version with check(s) suppressed
2816
2817    procedure Insert_Actions
2818      (Assoc_Node  : Node_Id;
2819       Ins_Actions : List_Id;
2820       Suppress    : Check_Id)
2821    is
2822    begin
2823       if Suppress = All_Checks then
2824          declare
2825             Svg : constant Suppress_Array := Scope_Suppress;
2826          begin
2827             Scope_Suppress := (others => True);
2828             Insert_Actions (Assoc_Node, Ins_Actions);
2829             Scope_Suppress := Svg;
2830          end;
2831
2832       else
2833          declare
2834             Svg : constant Boolean := Scope_Suppress (Suppress);
2835          begin
2836             Scope_Suppress (Suppress) := True;
2837             Insert_Actions (Assoc_Node, Ins_Actions);
2838             Scope_Suppress (Suppress) := Svg;
2839          end;
2840       end if;
2841    end Insert_Actions;
2842
2843    --------------------------
2844    -- Insert_Actions_After --
2845    --------------------------
2846
2847    procedure Insert_Actions_After
2848      (Assoc_Node  : Node_Id;
2849       Ins_Actions : List_Id)
2850    is
2851    begin
2852       if Scope_Is_Transient
2853         and then Assoc_Node = Node_To_Be_Wrapped
2854       then
2855          Store_After_Actions_In_Scope (Ins_Actions);
2856       else
2857          Insert_List_After_And_Analyze (Assoc_Node, Ins_Actions);
2858       end if;
2859    end Insert_Actions_After;
2860
2861    ---------------------------------
2862    -- Insert_Library_Level_Action --
2863    ---------------------------------
2864
2865    procedure Insert_Library_Level_Action (N : Node_Id) is
2866       Aux : constant Node_Id := Aux_Decls_Node (Cunit (Main_Unit));
2867
2868    begin
2869       Push_Scope (Cunit_Entity (Main_Unit));
2870       --  ??? should this be Current_Sem_Unit instead of Main_Unit?
2871
2872       if No (Actions (Aux)) then
2873          Set_Actions (Aux, New_List (N));
2874       else
2875          Append (N, Actions (Aux));
2876       end if;
2877
2878       Analyze (N);
2879       Pop_Scope;
2880    end Insert_Library_Level_Action;
2881
2882    ----------------------------------
2883    -- Insert_Library_Level_Actions --
2884    ----------------------------------
2885
2886    procedure Insert_Library_Level_Actions (L : List_Id) is
2887       Aux : constant Node_Id := Aux_Decls_Node (Cunit (Main_Unit));
2888
2889    begin
2890       if Is_Non_Empty_List (L) then
2891          Push_Scope (Cunit_Entity (Main_Unit));
2892          --  ??? should this be Current_Sem_Unit instead of Main_Unit?
2893
2894          if No (Actions (Aux)) then
2895             Set_Actions (Aux, L);
2896             Analyze_List (L);
2897          else
2898             Insert_List_After_And_Analyze (Last (Actions (Aux)), L);
2899          end if;
2900
2901          Pop_Scope;
2902       end if;
2903    end Insert_Library_Level_Actions;
2904
2905    ----------------------
2906    -- Inside_Init_Proc --
2907    ----------------------
2908
2909    function Inside_Init_Proc return Boolean is
2910       S : Entity_Id;
2911
2912    begin
2913       S := Current_Scope;
2914       while Present (S)
2915         and then S /= Standard_Standard
2916       loop
2917          if Is_Init_Proc (S) then
2918             return True;
2919          else
2920             S := Scope (S);
2921          end if;
2922       end loop;
2923
2924       return False;
2925    end Inside_Init_Proc;
2926
2927    ----------------------------
2928    -- Is_All_Null_Statements --
2929    ----------------------------
2930
2931    function Is_All_Null_Statements (L : List_Id) return Boolean is
2932       Stm : Node_Id;
2933
2934    begin
2935       Stm := First (L);
2936       while Present (Stm) loop
2937          if Nkind (Stm) /= N_Null_Statement then
2938             return False;
2939          end if;
2940
2941          Next (Stm);
2942       end loop;
2943
2944       return True;
2945    end Is_All_Null_Statements;
2946
2947    ----------------------------------
2948    -- Is_Library_Level_Tagged_Type --
2949    ----------------------------------
2950
2951    function Is_Library_Level_Tagged_Type (Typ : Entity_Id) return Boolean is
2952    begin
2953       return Is_Tagged_Type (Typ)
2954         and then Is_Library_Level_Entity (Typ);
2955    end Is_Library_Level_Tagged_Type;
2956
2957    -----------------------------------------
2958    -- Is_Predefined_Dispatching_Operation --
2959    -----------------------------------------
2960
2961    function Is_Predefined_Dispatching_Operation (E : Entity_Id) return Boolean
2962    is
2963       TSS_Name : TSS_Name_Type;
2964
2965    begin
2966       if not Is_Dispatching_Operation (E) then
2967          return False;
2968       end if;
2969
2970       Get_Name_String (Chars (E));
2971
2972       if Name_Len > TSS_Name_Type'Last then
2973          TSS_Name := TSS_Name_Type (Name_Buffer (Name_Len - TSS_Name'Length + 1
2974                                      .. Name_Len));
2975          if Chars (E)        = Name_uSize
2976            or else Chars (E) = Name_uAlignment
2977            or else TSS_Name  = TSS_Stream_Read
2978            or else TSS_Name  = TSS_Stream_Write
2979            or else TSS_Name  = TSS_Stream_Input
2980            or else TSS_Name  = TSS_Stream_Output
2981            or else
2982              (Chars (E) = Name_Op_Eq
2983                 and then Etype (First_Entity (E)) = Etype (Last_Entity (E)))
2984            or else Chars (E) = Name_uAssign
2985            or else TSS_Name  = TSS_Deep_Adjust
2986            or else TSS_Name  = TSS_Deep_Finalize
2987            or else (Ada_Version >= Ada_05
2988              and then (Chars (E) = Name_uDisp_Asynchronous_Select
2989                or else Chars (E) = Name_uDisp_Conditional_Select
2990                or else Chars (E) = Name_uDisp_Get_Prim_Op_Kind
2991                or else Chars (E) = Name_uDisp_Get_Task_Id
2992                or else Chars (E) = Name_uDisp_Timed_Select))
2993          then
2994             return True;
2995          end if;
2996       end if;
2997
2998       return False;
2999    end Is_Predefined_Dispatching_Operation;
3000
3001    ----------------------------------
3002    -- Is_Possibly_Unaligned_Object --
3003    ----------------------------------
3004
3005    function Is_Possibly_Unaligned_Object (N : Node_Id) return Boolean is
3006       T  : constant Entity_Id := Etype (N);
3007
3008    begin
3009       --  If renamed object, apply test to underlying object
3010
3011       if Is_Entity_Name (N)
3012         and then Is_Object (Entity (N))
3013         and then Present (Renamed_Object (Entity (N)))
3014       then
3015          return Is_Possibly_Unaligned_Object (Renamed_Object (Entity (N)));
3016       end if;
3017
3018       --  Tagged and controlled types and aliased types are always aligned,
3019       --  as are concurrent types.
3020
3021       if Is_Aliased (T)
3022         or else Has_Controlled_Component (T)
3023         or else Is_Concurrent_Type (T)
3024         or else Is_Tagged_Type (T)
3025         or else Is_Controlled (T)
3026       then
3027          return False;
3028       end if;
3029
3030       --  If this is an element of a packed array, may be unaligned
3031
3032       if Is_Ref_To_Bit_Packed_Array (N) then
3033          return True;
3034       end if;
3035
3036       --  Case of component reference
3037
3038       if Nkind (N) = N_Selected_Component then
3039          declare
3040             P : constant Node_Id   := Prefix (N);
3041             C : constant Entity_Id := Entity (Selector_Name (N));
3042             M : Nat;
3043             S : Nat;
3044
3045          begin
3046             --  If component reference is for an array with non-static bounds,
3047             --  then it is always aligned: we can only process unaligned
3048             --  arrays with static bounds (more accurately bounds known at
3049             --  compile time).
3050
3051             if Is_Array_Type (T)
3052               and then not Compile_Time_Known_Bounds (T)
3053             then
3054                return False;
3055             end if;
3056
3057             --  If component is aliased, it is definitely properly aligned
3058
3059             if Is_Aliased (C) then
3060                return False;
3061             end if;
3062
3063             --  If component is for a type implemented as a scalar, and the
3064             --  record is packed, and the component is other than the first
3065             --  component of the record, then the component may be unaligned.
3066
3067             if Is_Packed (Etype (P))
3068               and then Represented_As_Scalar (Etype (C))
3069               and then First_Entity (Scope (C)) /= C
3070             then
3071                return True;
3072             end if;
3073
3074             --  Compute maximum possible alignment for T
3075
3076             --  If alignment is known, then that settles things
3077
3078             if Known_Alignment (T) then
3079                M := UI_To_Int (Alignment (T));
3080
3081             --  If alignment is not known, tentatively set max alignment
3082
3083             else
3084                M := Ttypes.Maximum_Alignment;
3085
3086                --  We can reduce this if the Esize is known since the default
3087                --  alignment will never be more than the smallest power of 2
3088                --  that does not exceed this Esize value.
3089
3090                if Known_Esize (T) then
3091                   S := UI_To_Int (Esize (T));
3092
3093                   while (M / 2) >= S loop
3094                      M := M / 2;
3095                   end loop;
3096                end if;
3097             end if;
3098
3099             --  If the component reference is for a record that has a specified
3100             --  alignment, and we either know it is too small, or cannot tell,
3101             --  then the component may be unaligned
3102
3103             if Known_Alignment (Etype (P))
3104               and then Alignment (Etype (P)) < Ttypes.Maximum_Alignment
3105               and then M > Alignment (Etype (P))
3106             then
3107                return True;
3108             end if;
3109
3110             --  Case of component clause present which may specify an
3111             --  unaligned position.
3112
3113             if Present (Component_Clause (C)) then
3114
3115                --  Otherwise we can do a test to make sure that the actual
3116                --  start position in the record, and the length, are both
3117                --  consistent with the required alignment. If not, we know
3118                --  that we are unaligned.
3119
3120                declare
3121                   Align_In_Bits : constant Nat := M * System_Storage_Unit;
3122                begin
3123                   if Component_Bit_Offset (C) mod Align_In_Bits /= 0
3124                     or else Esize (C) mod Align_In_Bits /= 0
3125                   then
3126                      return True;
3127                   end if;
3128                end;
3129             end if;
3130
3131             --  Otherwise, for a component reference, test prefix
3132
3133             return Is_Possibly_Unaligned_Object (P);
3134          end;
3135
3136       --  If not a component reference, must be aligned
3137
3138       else
3139          return False;
3140       end if;
3141    end Is_Possibly_Unaligned_Object;
3142
3143    ---------------------------------
3144    -- Is_Possibly_Unaligned_Slice --
3145    ---------------------------------
3146
3147    function Is_Possibly_Unaligned_Slice (N : Node_Id) return Boolean is
3148    begin
3149       --  Go to renamed object
3150
3151       if Is_Entity_Name (N)
3152         and then Is_Object (Entity (N))
3153         and then Present (Renamed_Object (Entity (N)))
3154       then
3155          return Is_Possibly_Unaligned_Slice (Renamed_Object (Entity (N)));
3156       end if;
3157
3158       --  The reference must be a slice
3159
3160       if Nkind (N) /= N_Slice then
3161          return False;
3162       end if;
3163
3164       --  Always assume the worst for a nested record component with a
3165       --  component clause, which gigi/gcc does not appear to handle well.
3166       --  It is not clear why this special test is needed at all ???
3167
3168       if Nkind (Prefix (N)) = N_Selected_Component
3169         and then Nkind (Prefix (Prefix (N))) = N_Selected_Component
3170         and then
3171           Present (Component_Clause (Entity (Selector_Name (Prefix (N)))))
3172       then
3173          return True;
3174       end if;
3175
3176       --  We only need to worry if the target has strict alignment
3177
3178       if not Target_Strict_Alignment then
3179          return False;
3180       end if;
3181
3182       --  If it is a slice, then look at the array type being sliced
3183
3184       declare
3185          Sarr : constant Node_Id := Prefix (N);
3186          --  Prefix of the slice, i.e. the array being sliced
3187
3188          Styp : constant Entity_Id := Etype (Prefix (N));
3189          --  Type of the array being sliced
3190
3191          Pref : Node_Id;
3192          Ptyp : Entity_Id;
3193
3194       begin
3195          --  The problems arise if the array object that is being sliced
3196          --  is a component of a record or array, and we cannot guarantee
3197          --  the alignment of the array within its containing object.
3198
3199          --  To investigate this, we look at successive prefixes to see
3200          --  if we have a worrisome indexed or selected component.
3201
3202          Pref := Sarr;
3203          loop
3204             --  Case of array is part of an indexed component reference
3205
3206             if Nkind (Pref) = N_Indexed_Component then
3207                Ptyp := Etype (Prefix (Pref));
3208
3209                --  The only problematic case is when the array is packed,
3210                --  in which case we really know nothing about the alignment
3211                --  of individual components.
3212
3213                if Is_Bit_Packed_Array (Ptyp) then
3214                   return True;
3215                end if;
3216
3217             --  Case of array is part of a selected component reference
3218
3219             elsif Nkind (Pref) = N_Selected_Component then
3220                Ptyp := Etype (Prefix (Pref));
3221
3222                --  We are definitely in trouble if the record in question
3223                --  has an alignment, and either we know this alignment is
3224                --  inconsistent with the alignment of the slice, or we
3225                --  don't know what the alignment of the slice should be.
3226
3227                if Known_Alignment (Ptyp)
3228                  and then (Unknown_Alignment (Styp)
3229                              or else Alignment (Styp) > Alignment (Ptyp))
3230                then
3231                   return True;
3232                end if;
3233
3234                --  We are in potential trouble if the record type is packed.
3235                --  We could special case when we know that the array is the
3236                --  first component, but that's not such a simple case ???
3237
3238                if Is_Packed (Ptyp) then
3239                   return True;
3240                end if;
3241
3242                --  We are in trouble if there is a component clause, and
3243                --  either we do not know the alignment of the slice, or
3244                --  the alignment of the slice is inconsistent with the
3245                --  bit position specified by the component clause.
3246
3247                declare
3248                   Field : constant Entity_Id := Entity (Selector_Name (Pref));
3249                begin
3250                   if Present (Component_Clause (Field))
3251                     and then
3252                       (Unknown_Alignment (Styp)
3253                         or else
3254                          (Component_Bit_Offset (Field) mod
3255                            (System_Storage_Unit * Alignment (Styp))) /= 0)
3256                   then
3257                      return True;
3258                   end if;
3259                end;
3260
3261             --  For cases other than selected or indexed components we
3262             --  know we are OK, since no issues arise over alignment.
3263
3264             else
3265                return False;
3266             end if;
3267
3268             --  We processed an indexed component or selected component
3269             --  reference that looked safe, so keep checking prefixes.
3270
3271             Pref := Prefix (Pref);
3272          end loop;
3273       end;
3274    end Is_Possibly_Unaligned_Slice;
3275
3276    --------------------------------
3277    -- Is_Ref_To_Bit_Packed_Array --
3278    --------------------------------
3279
3280    function Is_Ref_To_Bit_Packed_Array (N : Node_Id) return Boolean is
3281       Result : Boolean;
3282       Expr   : Node_Id;
3283
3284    begin
3285       if Is_Entity_Name (N)
3286         and then Is_Object (Entity (N))
3287         and then Present (Renamed_Object (Entity (N)))
3288       then
3289          return Is_Ref_To_Bit_Packed_Array (Renamed_Object (Entity (N)));
3290       end if;
3291
3292       if Nkind (N) = N_Indexed_Component
3293            or else
3294          Nkind (N) = N_Selected_Component
3295       then
3296          if Is_Bit_Packed_Array (Etype (Prefix (N))) then
3297             Result := True;
3298          else
3299             Result := Is_Ref_To_Bit_Packed_Array (Prefix (N));
3300          end if;
3301
3302          if Result and then Nkind (N) = N_Indexed_Component then
3303             Expr := First (Expressions (N));
3304             while Present (Expr) loop
3305                Force_Evaluation (Expr);
3306                Next (Expr);
3307             end loop;
3308          end if;
3309
3310          return Result;
3311
3312       else
3313          return False;
3314       end if;
3315    end Is_Ref_To_Bit_Packed_Array;
3316
3317    --------------------------------
3318    -- Is_Ref_To_Bit_Packed_Slice --
3319    --------------------------------
3320
3321    function Is_Ref_To_Bit_Packed_Slice (N : Node_Id) return Boolean is
3322    begin
3323       if Nkind (N) = N_Type_Conversion then
3324          return Is_Ref_To_Bit_Packed_Slice (Expression (N));
3325
3326       elsif Is_Entity_Name (N)
3327         and then Is_Object (Entity (N))
3328         and then Present (Renamed_Object (Entity (N)))
3329       then
3330          return Is_Ref_To_Bit_Packed_Slice (Renamed_Object (Entity (N)));
3331
3332       elsif Nkind (N) = N_Slice
3333         and then Is_Bit_Packed_Array (Etype (Prefix (N)))
3334       then
3335          return True;
3336
3337       elsif Nkind (N) = N_Indexed_Component
3338            or else
3339          Nkind (N) = N_Selected_Component
3340       then
3341          return Is_Ref_To_Bit_Packed_Slice (Prefix (N));
3342
3343       else
3344          return False;
3345       end if;
3346    end Is_Ref_To_Bit_Packed_Slice;
3347
3348    -----------------------
3349    -- Is_Renamed_Object --
3350    -----------------------
3351
3352    function Is_Renamed_Object (N : Node_Id) return Boolean is
3353       Pnod : constant Node_Id   := Parent (N);
3354       Kind : constant Node_Kind := Nkind (Pnod);
3355
3356    begin
3357       if Kind = N_Object_Renaming_Declaration then
3358          return True;
3359
3360       elsif Kind = N_Indexed_Component
3361         or else Kind = N_Selected_Component
3362       then
3363          return Is_Renamed_Object (Pnod);
3364
3365       else
3366          return False;
3367       end if;
3368    end Is_Renamed_Object;
3369
3370    ----------------------------
3371    -- Is_Untagged_Derivation --
3372    ----------------------------
3373
3374    function Is_Untagged_Derivation (T : Entity_Id) return Boolean is
3375    begin
3376       return (not Is_Tagged_Type (T) and then Is_Derived_Type (T))
3377                or else
3378              (Is_Private_Type (T) and then Present (Full_View (T))
3379                and then not Is_Tagged_Type (Full_View (T))
3380                and then Is_Derived_Type (Full_View (T))
3381                and then Etype (Full_View (T)) /= T);
3382    end Is_Untagged_Derivation;
3383
3384    --------------------
3385    -- Kill_Dead_Code --
3386    --------------------
3387
3388    procedure Kill_Dead_Code (N : Node_Id; Warn : Boolean := False) is
3389    begin
3390       if Present (N) then
3391          Remove_Warning_Messages (N);
3392
3393          if Warn then
3394             Error_Msg_F
3395               ("?this code can never be executed and has been deleted!", N);
3396          end if;
3397
3398          --  Recurse into block statements and bodies to process declarations
3399          --  and statements
3400
3401          if Nkind (N) = N_Block_Statement
3402            or else Nkind (N) = N_Subprogram_Body
3403            or else Nkind (N) = N_Package_Body
3404          then
3405             Kill_Dead_Code (Declarations (N), False);
3406             Kill_Dead_Code (Statements (Handled_Statement_Sequence (N)));
3407
3408             if Nkind (N) = N_Subprogram_Body then
3409                Set_Is_Eliminated (Defining_Entity (N));
3410             end if;
3411
3412          elsif Nkind (N) = N_Package_Declaration then
3413             Kill_Dead_Code (Visible_Declarations (Specification (N)));
3414             Kill_Dead_Code (Private_Declarations (Specification (N)));
3415
3416             --  ??? After this point, Delete_Tree has been called on all
3417             --  declarations in Specification (N), so references to
3418             --  entities therein look suspicious.
3419
3420             declare
3421                E : Entity_Id := First_Entity (Defining_Entity (N));
3422             begin
3423                while Present (E) loop
3424                   if Ekind (E) = E_Operator then
3425                      Set_Is_Eliminated (E);
3426                   end if;
3427
3428                   Next_Entity (E);
3429                end loop;
3430             end;
3431
3432          --  Recurse into composite statement to kill individual statements,
3433          --  in particular instantiations.
3434
3435          elsif Nkind (N) = N_If_Statement then
3436             Kill_Dead_Code (Then_Statements (N));
3437             Kill_Dead_Code (Elsif_Parts (N));
3438             Kill_Dead_Code (Else_Statements (N));
3439
3440          elsif Nkind (N) = N_Loop_Statement then
3441             Kill_Dead_Code (Statements (N));
3442
3443          elsif Nkind (N) = N_Case_Statement then
3444             declare
3445                Alt : Node_Id;
3446             begin
3447                Alt := First (Alternatives (N));
3448                while Present (Alt) loop
3449                   Kill_Dead_Code (Statements (Alt));
3450                   Next (Alt);
3451                end loop;
3452             end;
3453
3454          elsif Nkind (N) = N_Case_Statement_Alternative then
3455             Kill_Dead_Code (Statements (N));
3456
3457          --  Deal with dead instances caused by deleting instantiations
3458
3459          elsif Nkind (N) in N_Generic_Instantiation then
3460             Remove_Dead_Instance (N);
3461          end if;
3462
3463          Delete_Tree (N);
3464       end if;
3465    end Kill_Dead_Code;
3466
3467    --  Case where argument is a list of nodes to be killed
3468
3469    procedure Kill_Dead_Code (L : List_Id; Warn : Boolean := False) is
3470       N : Node_Id;
3471       W : Boolean;
3472    begin
3473       W := Warn;
3474       if Is_Non_Empty_List (L) then
3475          loop
3476             N := Remove_Head (L);
3477             exit when No (N);
3478             Kill_Dead_Code (N, W);
3479             W := False;
3480          end loop;
3481       end if;
3482    end Kill_Dead_Code;
3483
3484    ------------------------
3485    -- Known_Non_Negative --
3486    ------------------------
3487
3488    function Known_Non_Negative (Opnd : Node_Id) return Boolean is
3489    begin
3490       if Is_OK_Static_Expression (Opnd)
3491         and then Expr_Value (Opnd) >= 0
3492       then
3493          return True;
3494
3495       else
3496          declare
3497             Lo : constant Node_Id := Type_Low_Bound (Etype (Opnd));
3498
3499          begin
3500             return
3501               Is_OK_Static_Expression (Lo) and then Expr_Value (Lo) >= 0;
3502          end;
3503       end if;
3504    end Known_Non_Negative;
3505
3506    --------------------
3507    -- Known_Non_Null --
3508    --------------------
3509
3510    function Known_Non_Null (N : Node_Id) return Boolean is
3511    begin
3512       --  Checks for case where N is an entity reference
3513
3514       if Is_Entity_Name (N) and then Present (Entity (N)) then
3515          declare
3516             E   : constant Entity_Id := Entity (N);
3517             Op  : Node_Kind;
3518             Val : Node_Id;
3519
3520          begin
3521             --  First check if we are in decisive conditional
3522
3523             Get_Current_Value_Condition (N, Op, Val);
3524
3525             if Known_Null (Val) then
3526                if Op = N_Op_Eq then
3527                   return False;
3528                elsif Op = N_Op_Ne then
3529                   return True;
3530                end if;
3531             end if;
3532
3533             --  If OK to do replacement, test Is_Known_Non_Null flag
3534
3535             if OK_To_Do_Constant_Replacement (E) then
3536                return Is_Known_Non_Null (E);
3537
3538             --  Otherwise if not safe to do replacement, then say so
3539
3540             else
3541                return False;
3542             end if;
3543          end;
3544
3545       --  True if access attribute
3546
3547       elsif Nkind (N) = N_Attribute_Reference
3548         and then (Attribute_Name (N) = Name_Access
3549                     or else
3550                   Attribute_Name (N) = Name_Unchecked_Access
3551                     or else
3552                   Attribute_Name (N) = Name_Unrestricted_Access)
3553       then
3554          return True;
3555
3556       --  True if allocator
3557
3558       elsif Nkind (N) = N_Allocator then
3559          return True;
3560
3561       --  For a conversion, true if expression is known non-null
3562
3563       elsif Nkind (N) = N_Type_Conversion then
3564          return Known_Non_Null (Expression (N));
3565
3566       --  Above are all cases where the value could be determined to be
3567       --  non-null. In all other cases, we don't know, so return False.
3568
3569       else
3570          return False;
3571       end if;
3572    end Known_Non_Null;
3573
3574    ----------------
3575    -- Known_Null --
3576    ----------------
3577
3578    function Known_Null (N : Node_Id) return Boolean is
3579    begin
3580       --  Checks for case where N is an entity reference
3581
3582       if Is_Entity_Name (N) and then Present (Entity (N)) then
3583          declare
3584             E   : constant Entity_Id := Entity (N);
3585             Op  : Node_Kind;
3586             Val : Node_Id;
3587
3588          begin
3589             --  Constant null value is for sure null
3590
3591             if Ekind (E) = E_Constant
3592               and then Known_Null (Constant_Value (E))
3593             then
3594                return True;
3595             end if;
3596
3597             --  First check if we are in decisive conditional
3598
3599             Get_Current_Value_Condition (N, Op, Val);
3600
3601             if Known_Null (Val) then
3602                if Op = N_Op_Eq then
3603                   return True;
3604                elsif Op = N_Op_Ne then
3605                   return False;
3606                end if;
3607             end if;
3608
3609             --  If OK to do replacement, test Is_Known_Null flag
3610
3611             if OK_To_Do_Constant_Replacement (E) then
3612                return Is_Known_Null (E);
3613
3614             --  Otherwise if not safe to do replacement, then say so
3615
3616             else
3617                return False;
3618             end if;
3619          end;
3620
3621       --  True if explicit reference to null
3622
3623       elsif Nkind (N) = N_Null then
3624          return True;
3625
3626       --  For a conversion, true if expression is known null
3627
3628       elsif Nkind (N) = N_Type_Conversion then
3629          return Known_Null (Expression (N));
3630
3631       --  Above are all cases where the value could be determined to be null.
3632       --  In all other cases, we don't know, so return False.
3633
3634       else
3635          return False;
3636       end if;
3637    end Known_Null;
3638
3639    -----------------------------
3640    -- Make_CW_Equivalent_Type --
3641    -----------------------------
3642
3643    --  Create a record type used as an equivalent of any member
3644    --  of the class which takes its size from exp.
3645
3646    --  Generate the following code:
3647
3648    --   type Equiv_T is record
3649    --     _parent :  T (List of discriminant constaints taken from Exp);
3650    --     Ext__50 : Storage_Array (1 .. (Exp'size - Typ'object_size)/8);
3651    --   end Equiv_T;
3652    --
3653    --   ??? Note that this type does not guarantee same alignment as all
3654    --   derived types
3655
3656    function Make_CW_Equivalent_Type
3657      (T : Entity_Id;
3658       E : Node_Id) return Entity_Id
3659    is
3660       Loc         : constant Source_Ptr := Sloc (E);
3661       Root_Typ    : constant Entity_Id  := Root_Type (T);
3662       List_Def    : constant List_Id    := Empty_List;
3663       Comp_List   : constant List_Id    := New_List;
3664       Equiv_Type  : Entity_Id;
3665       Range_Type  : Entity_Id;
3666       Str_Type    : Entity_Id;
3667       Constr_Root : Entity_Id;
3668       Sizexpr     : Node_Id;
3669
3670    begin
3671       if not Has_Discriminants (Root_Typ) then
3672          Constr_Root := Root_Typ;
3673       else
3674          Constr_Root :=
3675            Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
3676
3677          --  subtype cstr__n is T (List of discr constraints taken from Exp)
3678
3679          Append_To (List_Def,
3680            Make_Subtype_Declaration (Loc,
3681              Defining_Identifier => Constr_Root,
3682                Subtype_Indication =>
3683                  Make_Subtype_From_Expr (E, Root_Typ)));
3684       end if;
3685
3686       --  Generate the range subtype declaration
3687
3688       Range_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('G'));
3689
3690       if not Is_Interface (Root_Typ) then
3691          --  subtype rg__xx is
3692          --    Storage_Offset range 1 .. (Expr'size - typ'size) / Storage_Unit
3693
3694          Sizexpr :=
3695            Make_Op_Subtract (Loc,
3696              Left_Opnd =>
3697                Make_Attribute_Reference (Loc,
3698                  Prefix =>
3699                    OK_Convert_To (T, Duplicate_Subexpr_No_Checks (E)),
3700                  Attribute_Name => Name_Size),
3701              Right_Opnd =>
3702                Make_Attribute_Reference (Loc,
3703                  Prefix => New_Reference_To (Constr_Root, Loc),
3704                  Attribute_Name => Name_Object_Size));
3705       else
3706          --  subtype rg__xx is
3707          --    Storage_Offset range 1 .. Expr'size / Storage_Unit
3708
3709          Sizexpr :=
3710            Make_Attribute_Reference (Loc,
3711              Prefix =>
3712                OK_Convert_To (T, Duplicate_Subexpr_No_Checks (E)),
3713              Attribute_Name => Name_Size);
3714       end if;
3715
3716       Set_Paren_Count (Sizexpr, 1);
3717
3718       Append_To (List_Def,
3719         Make_Subtype_Declaration (Loc,
3720           Defining_Identifier => Range_Type,
3721           Subtype_Indication =>
3722             Make_Subtype_Indication (Loc,
3723               Subtype_Mark => New_Reference_To (RTE (RE_Storage_Offset), Loc),
3724               Constraint => Make_Range_Constraint (Loc,
3725                 Range_Expression =>
3726                   Make_Range (Loc,
3727                     Low_Bound => Make_Integer_Literal (Loc, 1),
3728                     High_Bound =>
3729                       Make_Op_Divide (Loc,
3730                         Left_Opnd => Sizexpr,
3731                         Right_Opnd => Make_Integer_Literal (Loc,
3732                             Intval => System_Storage_Unit)))))));
3733
3734       --  subtype str__nn is Storage_Array (rg__x);
3735
3736       Str_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('S'));
3737       Append_To (List_Def,
3738         Make_Subtype_Declaration (Loc,
3739           Defining_Identifier => Str_Type,
3740           Subtype_Indication =>
3741             Make_Subtype_Indication (Loc,
3742               Subtype_Mark => New_Reference_To (RTE (RE_Storage_Array), Loc),
3743               Constraint =>
3744                 Make_Index_Or_Discriminant_Constraint (Loc,
3745                   Constraints =>
3746                     New_List (New_Reference_To (Range_Type, Loc))))));
3747
3748       --  type Equiv_T is record
3749       --    [ _parent : Tnn; ]
3750       --    E : Str_Type;
3751       --  end Equiv_T;
3752
3753       Equiv_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
3754
3755       --  When the target requires front-end layout, it's necessary to allow
3756       --  the equivalent type to be frozen so that layout can occur (when the
3757       --  associated class-wide subtype is frozen, the equivalent type will
3758       --  be frozen, see freeze.adb). For other targets, Gigi wants to have
3759       --  the equivalent type marked as frozen and deals with this type itself.
3760       --  In the Gigi case this will also avoid the generation of an init
3761       --  procedure for the type.
3762
3763       if not Frontend_Layout_On_Target then
3764          Set_Is_Frozen (Equiv_Type);
3765       end if;
3766
3767       Set_Ekind (Equiv_Type, E_Record_Type);
3768       Set_Parent_Subtype (Equiv_Type, Constr_Root);
3769
3770       if not Is_Interface (Root_Typ) then
3771          Append_To (Comp_List,
3772            Make_Component_Declaration (Loc,
3773              Defining_Identifier =>
3774                Make_Defining_Identifier (Loc, Name_uParent),
3775              Component_Definition =>
3776                Make_Component_Definition (Loc,
3777                  Aliased_Present    => False,
3778                  Subtype_Indication => New_Reference_To (Constr_Root, Loc))));
3779       end if;
3780
3781       Append_To (Comp_List,
3782         Make_Component_Declaration (Loc,
3783           Defining_Identifier =>
3784             Make_Defining_Identifier (Loc,
3785               Chars => New_Internal_Name ('C')),
3786           Component_Definition =>
3787             Make_Component_Definition (Loc,
3788               Aliased_Present    => False,
3789               Subtype_Indication => New_Reference_To (Str_Type, Loc))));
3790
3791       Append_To (List_Def,
3792         Make_Full_Type_Declaration (Loc,
3793           Defining_Identifier => Equiv_Type,
3794           Type_Definition =>
3795             Make_Record_Definition (Loc,
3796               Component_List =>
3797                 Make_Component_List (Loc,
3798                   Component_Items => Comp_List,
3799                   Variant_Part    => Empty))));
3800
3801       --  Suppress all checks during the analysis of the expanded code
3802       --  to avoid the generation of spurious warnings under ZFP run-time.
3803
3804       Insert_Actions (E, List_Def, Suppress => All_Checks);
3805       return Equiv_Type;
3806    end Make_CW_Equivalent_Type;
3807
3808    ------------------------
3809    -- Make_Literal_Range --
3810    ------------------------
3811
3812    function Make_Literal_Range
3813      (Loc         : Source_Ptr;
3814       Literal_Typ : Entity_Id) return Node_Id
3815    is
3816       Lo          : constant Node_Id :=
3817                       New_Copy_Tree (String_Literal_Low_Bound (Literal_Typ));
3818       Index       : constant Entity_Id := Etype (Lo);
3819
3820       Hi          : Node_Id;
3821       Length_Expr : constant Node_Id :=
3822                       Make_Op_Subtract (Loc,
3823                         Left_Opnd =>
3824                           Make_Integer_Literal (Loc,
3825                             Intval => String_Literal_Length (Literal_Typ)),
3826                         Right_Opnd =>
3827                           Make_Integer_Literal (Loc, 1));
3828
3829    begin
3830       Set_Analyzed (Lo, False);
3831
3832          if Is_Integer_Type (Index) then
3833             Hi :=
3834               Make_Op_Add (Loc,
3835                 Left_Opnd  => New_Copy_Tree (Lo),
3836                 Right_Opnd => Length_Expr);
3837          else
3838             Hi :=
3839               Make_Attribute_Reference (Loc,
3840                 Attribute_Name => Name_Val,
3841                 Prefix => New_Occurrence_Of (Index, Loc),
3842                 Expressions => New_List (
3843                  Make_Op_Add (Loc,
3844                    Left_Opnd =>
3845                      Make_Attribute_Reference (Loc,
3846                        Attribute_Name => Name_Pos,
3847                        Prefix => New_Occurrence_Of (Index, Loc),
3848                        Expressions => New_List (New_Copy_Tree (Lo))),
3849                   Right_Opnd => Length_Expr)));
3850          end if;
3851
3852          return
3853            Make_Range (Loc,
3854              Low_Bound  => Lo,
3855              High_Bound => Hi);
3856    end Make_Literal_Range;
3857
3858    ----------------------------
3859    -- Make_Subtype_From_Expr --
3860    ----------------------------
3861
3862    --  1. If Expr is an uncontrained array expression, creates
3863    --    Unc_Type(Expr'first(1)..Expr'Last(1),..., Expr'first(n)..Expr'last(n))
3864
3865    --  2. If Expr is a unconstrained discriminated type expression, creates
3866    --    Unc_Type(Expr.Discr1, ... , Expr.Discr_n)
3867
3868    --  3. If Expr is class-wide, creates an implicit class wide subtype
3869
3870    function Make_Subtype_From_Expr
3871      (E       : Node_Id;
3872       Unc_Typ : Entity_Id) return Node_Id
3873    is
3874       Loc         : constant Source_Ptr := Sloc (E);
3875       List_Constr : constant List_Id    := New_List;
3876       D           : Entity_Id;
3877
3878       Full_Subtyp  : Entity_Id;
3879       Priv_Subtyp  : Entity_Id;
3880       Utyp         : Entity_Id;
3881       Full_Exp     : Node_Id;
3882
3883    begin
3884       if Is_Private_Type (Unc_Typ)
3885         and then Has_Unknown_Discriminants (Unc_Typ)
3886       then
3887          --  Prepare the subtype completion, Go to base type to
3888          --  find underlying type, because the type may be a generic
3889          --  actual or an explicit subtype.
3890
3891          Utyp        := Underlying_Type (Base_Type (Unc_Typ));
3892          Full_Subtyp := Make_Defining_Identifier (Loc,
3893                           New_Internal_Name ('C'));
3894          Full_Exp    :=
3895            Unchecked_Convert_To
3896              (Utyp, Duplicate_Subexpr_No_Checks (E));
3897          Set_Parent (Full_Exp, Parent (E));
3898
3899          Priv_Subtyp :=
3900            Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
3901
3902          Insert_Action (E,
3903            Make_Subtype_Declaration (Loc,
3904              Defining_Identifier => Full_Subtyp,
3905              Subtype_Indication  => Make_Subtype_From_Expr (Full_Exp, Utyp)));
3906
3907          --  Define the dummy private subtype
3908
3909          Set_Ekind          (Priv_Subtyp, Subtype_Kind (Ekind (Unc_Typ)));
3910          Set_Etype          (Priv_Subtyp, Base_Type (Unc_Typ));
3911          Set_Scope          (Priv_Subtyp, Full_Subtyp);
3912          Set_Is_Constrained (Priv_Subtyp);
3913          Set_Is_Tagged_Type (Priv_Subtyp, Is_Tagged_Type (Unc_Typ));
3914          Set_Is_Itype       (Priv_Subtyp);
3915          Set_Associated_Node_For_Itype (Priv_Subtyp, E);
3916
3917          if Is_Tagged_Type  (Priv_Subtyp) then
3918             Set_Class_Wide_Type
3919               (Base_Type (Priv_Subtyp), Class_Wide_Type (Unc_Typ));
3920             Set_Primitive_Operations (Priv_Subtyp,
3921               Primitive_Operations (Unc_Typ));
3922          end if;
3923
3924          Set_Full_View (Priv_Subtyp, Full_Subtyp);
3925
3926          return New_Reference_To (Priv_Subtyp, Loc);
3927
3928       elsif Is_Array_Type (Unc_Typ) then
3929          for J in 1 .. Number_Dimensions (Unc_Typ) loop
3930             Append_To (List_Constr,
3931               Make_Range (Loc,
3932                 Low_Bound =>
3933                   Make_Attribute_Reference (Loc,
3934                     Prefix => Duplicate_Subexpr_No_Checks (E),
3935                     Attribute_Name => Name_First,
3936                     Expressions => New_List (
3937                       Make_Integer_Literal (Loc, J))),
3938
3939                 High_Bound =>
3940                   Make_Attribute_Reference (Loc,
3941                     Prefix         => Duplicate_Subexpr_No_Checks (E),
3942                     Attribute_Name => Name_Last,
3943                     Expressions    => New_List (
3944                       Make_Integer_Literal (Loc, J)))));
3945          end loop;
3946
3947       elsif Is_Class_Wide_Type (Unc_Typ) then
3948          declare
3949             CW_Subtype : Entity_Id;
3950             EQ_Typ     : Entity_Id := Empty;
3951
3952          begin
3953             --  A class-wide equivalent type is not needed when VM_Target
3954             --  because the VM back-ends handle the class-wide object
3955             --  initialization itself (and doesn't need or want the
3956             --  additional intermediate type to handle the assignment).
3957
3958             if Expander_Active and then VM_Target = No_VM then
3959                EQ_Typ := Make_CW_Equivalent_Type (Unc_Typ, E);
3960             end if;
3961
3962             CW_Subtype := New_Class_Wide_Subtype (Unc_Typ, E);
3963             Set_Equivalent_Type (CW_Subtype, EQ_Typ);
3964
3965             if Present (EQ_Typ) then
3966                Set_Is_Class_Wide_Equivalent_Type (EQ_Typ);
3967             end if;
3968
3969             Set_Cloned_Subtype (CW_Subtype, Base_Type (Unc_Typ));
3970
3971             return New_Occurrence_Of (CW_Subtype, Loc);
3972          end;
3973
3974       --  Indefinite record type with discriminants
3975
3976       else
3977          D := First_Discriminant (Unc_Typ);
3978          while Present (D) loop
3979             Append_To (List_Constr,
3980               Make_Selected_Component (Loc,
3981                 Prefix        => Duplicate_Subexpr_No_Checks (E),
3982                 Selector_Name => New_Reference_To (D, Loc)));
3983
3984             Next_Discriminant (D);
3985          end loop;
3986       end if;
3987
3988       return
3989         Make_Subtype_Indication (Loc,
3990           Subtype_Mark => New_Reference_To (Unc_Typ, Loc),
3991           Constraint   =>
3992             Make_Index_Or_Discriminant_Constraint (Loc,
3993               Constraints => List_Constr));
3994    end Make_Subtype_From_Expr;
3995
3996    -----------------------------
3997    -- May_Generate_Large_Temp --
3998    -----------------------------
3999
4000    --  At the current time, the only types that we return False for (i.e.
4001    --  where we decide we know they cannot generate large temps) are ones
4002    --  where we know the size is 256 bits or less at compile time, and we
4003    --  are still not doing a thorough job on arrays and records ???
4004
4005    function May_Generate_Large_Temp (Typ : Entity_Id) return Boolean is
4006    begin
4007       if not Size_Known_At_Compile_Time (Typ) then
4008          return False;
4009
4010       elsif Esize (Typ) /= 0 and then Esize (Typ) <= 256 then
4011          return False;
4012
4013       elsif Is_Array_Type (Typ)
4014         and then Present (Packed_Array_Type (Typ))
4015       then
4016          return May_Generate_Large_Temp (Packed_Array_Type (Typ));
4017
4018       --  We could do more here to find other small types ???
4019
4020       else
4021          return True;
4022       end if;
4023    end May_Generate_Large_Temp;
4024
4025    ----------------------------
4026    -- New_Class_Wide_Subtype --
4027    ----------------------------
4028
4029    function New_Class_Wide_Subtype
4030      (CW_Typ : Entity_Id;
4031       N      : Node_Id) return Entity_Id
4032    is
4033       Res       : constant Entity_Id := Create_Itype (E_Void, N);
4034       Res_Name  : constant Name_Id   := Chars (Res);
4035       Res_Scope : constant Entity_Id := Scope (Res);
4036
4037    begin
4038       Copy_Node (CW_Typ, Res);
4039       Set_Comes_From_Source (Res, False);
4040       Set_Sloc (Res, Sloc (N));
4041       Set_Is_Itype (Res);
4042       Set_Associated_Node_For_Itype (Res, N);
4043       Set_Is_Public (Res, False);   --  By default, may be changed below.
4044       Set_Public_Status (Res);
4045       Set_Chars (Res, Res_Name);
4046       Set_Scope (Res, Res_Scope);
4047       Set_Ekind (Res, E_Class_Wide_Subtype);
4048       Set_Next_Entity (Res, Empty);
4049       Set_Etype (Res, Base_Type (CW_Typ));
4050
4051       --  For targets where front-end layout is required, reset the Is_Frozen
4052       --  status of the subtype to False (it can be implicitly set to true
4053       --  from the copy of the class-wide type). For other targets, Gigi
4054       --  doesn't want the class-wide subtype to go through the freezing
4055       --  process (though it's unclear why that causes problems and it would
4056       --  be nice to allow freezing to occur normally for all targets ???).
4057
4058       if Frontend_Layout_On_Target then
4059          Set_Is_Frozen (Res, False);
4060       end if;
4061
4062       Set_Freeze_Node (Res, Empty);
4063       return (Res);
4064    end New_Class_Wide_Subtype;
4065
4066    --------------------------------
4067    -- Non_Limited_Designated_Type --
4068    ---------------------------------
4069
4070    function Non_Limited_Designated_Type (T : Entity_Id) return Entity_Id is
4071       Desig : constant Entity_Id := Designated_Type (T);
4072    begin
4073       if Ekind (Desig) = E_Incomplete_Type
4074         and then Present (Non_Limited_View (Desig))
4075       then
4076          return Non_Limited_View (Desig);
4077       else
4078          return Desig;
4079       end if;
4080    end Non_Limited_Designated_Type;
4081
4082    -----------------------------------
4083    -- OK_To_Do_Constant_Replacement --
4084    -----------------------------------
4085
4086    function OK_To_Do_Constant_Replacement (E : Entity_Id) return Boolean is
4087       ES : constant Entity_Id := Scope (E);
4088       CS : Entity_Id;
4089
4090    begin
4091       --  Do not replace statically allocated objects, because they may be
4092       --  modified outside the current scope.
4093
4094       if Is_Statically_Allocated (E) then
4095          return False;
4096
4097       --  Do not replace aliased or volatile objects, since we don't know what
4098       --  else might change the value.
4099
4100       elsif Is_Aliased (E) or else Treat_As_Volatile (E) then
4101          return False;
4102
4103       --  Debug flag -gnatdM disconnects this optimization
4104
4105       elsif Debug_Flag_MM then
4106          return False;
4107
4108       --  Otherwise check scopes
4109
4110       else
4111          CS := Current_Scope;
4112
4113          loop
4114             --  If we are in right scope, replacement is safe
4115
4116             if CS = ES then
4117                return True;
4118
4119             --  Packages do not affect the determination of safety
4120
4121             elsif Ekind (CS) = E_Package then
4122                exit when CS = Standard_Standard;
4123                CS := Scope (CS);
4124
4125             --  Blocks do not affect the determination of safety
4126
4127             elsif Ekind (CS) = E_Block then
4128                CS := Scope (CS);
4129
4130             --  Loops do not affect the determination of safety. Note that we
4131             --  kill all current values on entry to a loop, so we are just
4132             --  talking about processing within a loop here.
4133
4134             elsif Ekind (CS) = E_Loop then
4135                CS := Scope (CS);
4136
4137             --  Otherwise, the reference is dubious, and we cannot be sure that
4138             --  it is safe to do the replacement.
4139
4140             else
4141                exit;
4142             end if;
4143          end loop;
4144
4145          return False;
4146       end if;
4147    end OK_To_Do_Constant_Replacement;
4148
4149    ------------------------------------
4150    -- Possible_Bit_Aligned_Component --
4151    ------------------------------------
4152
4153    function Possible_Bit_Aligned_Component (N : Node_Id) return Boolean is
4154    begin
4155       case Nkind (N) is
4156
4157          --  Case of indexed component
4158
4159          when N_Indexed_Component =>
4160             declare
4161                P    : constant Node_Id   := Prefix (N);
4162                Ptyp : constant Entity_Id := Etype (P);
4163
4164             begin
4165                --  If we know the component size and it is less than 64, then
4166                --  we are definitely OK. The back end always does assignment
4167                --  of misaligned small objects correctly.
4168
4169                if Known_Static_Component_Size (Ptyp)
4170                  and then Component_Size (Ptyp) <= 64
4171                then
4172                   return False;
4173
4174                --  Otherwise, we need to test the prefix, to see if we are
4175                --  indexing from a possibly unaligned component.
4176
4177                else
4178                   return Possible_Bit_Aligned_Component (P);
4179                end if;
4180             end;
4181
4182          --  Case of selected component
4183
4184          when N_Selected_Component =>
4185             declare
4186                P    : constant Node_Id   := Prefix (N);
4187                Comp : constant Entity_Id := Entity (Selector_Name (N));
4188
4189             begin
4190                --  If there is no component clause, then we are in the clear
4191                --  since the back end will never misalign a large component
4192                --  unless it is forced to do so. In the clear means we need
4193                --  only the recursive test on the prefix.
4194
4195                if Component_May_Be_Bit_Aligned (Comp) then
4196                   return True;
4197                else
4198                   return Possible_Bit_Aligned_Component (P);
4199                end if;
4200             end;
4201
4202          --  If we have neither a record nor array component, it means that we
4203          --  have fallen off the top testing prefixes recursively, and we now
4204          --  have a stand alone object, where we don't have a problem.
4205
4206          when others =>
4207             return False;
4208
4209       end case;
4210    end Possible_Bit_Aligned_Component;
4211
4212    -------------------------
4213    -- Remove_Side_Effects --
4214    -------------------------
4215
4216    procedure Remove_Side_Effects
4217      (Exp          : Node_Id;
4218       Name_Req     : Boolean := False;
4219       Variable_Ref : Boolean := False)
4220    is
4221       Loc          : constant Source_Ptr     := Sloc (Exp);
4222       Exp_Type     : constant Entity_Id      := Etype (Exp);
4223       Svg_Suppress : constant Suppress_Array := Scope_Suppress;
4224       Def_Id       : Entity_Id;
4225       Ref_Type     : Entity_Id;
4226       Res          : Node_Id;
4227       Ptr_Typ_Decl : Node_Id;
4228       New_Exp      : Node_Id;
4229       E            : Node_Id;
4230
4231       function Side_Effect_Free (N : Node_Id) return Boolean;
4232       --  Determines if the tree N represents an expression that is known not
4233       --  to have side effects, and for which no processing is required.
4234
4235       function Side_Effect_Free (L : List_Id) return Boolean;
4236       --  Determines if all elements of the list L are side effect free
4237
4238       function Safe_Prefixed_Reference (N : Node_Id) return Boolean;
4239       --  The argument N is a construct where the Prefix is dereferenced if it
4240       --  is an access type and the result is a variable. The call returns True
4241       --  if the construct is side effect free (not considering side effects in
4242       --  other than the prefix which are to be tested by the caller).
4243
4244       function Within_In_Parameter (N : Node_Id) return Boolean;
4245       --  Determines if N is a subcomponent of a composite in-parameter. If so,
4246       --  N is not side-effect free when the actual is global and modifiable
4247       --  indirectly from within a subprogram, because it may be passed by
4248       --  reference. The front-end must be conservative here and assume that
4249       --  this may happen with any array or record type. On the other hand, we
4250       --  cannot create temporaries for all expressions for which this
4251       --  condition is true, for various reasons that might require clearing up
4252       --  ??? For example, descriminant references that appear out of place, or
4253       --  spurious type errors with class-wide expressions. As a result, we
4254       --  limit the transformation to loop bounds, which is so far the only
4255       --  case that requires it.
4256
4257       -----------------------------
4258       -- Safe_Prefixed_Reference --
4259       -----------------------------
4260
4261       function Safe_Prefixed_Reference (N : Node_Id) return Boolean is
4262       begin
4263          --  If prefix is not side effect free, definitely not safe
4264
4265          if not Side_Effect_Free (Prefix (N)) then
4266             return False;
4267
4268          --  If the prefix is of an access type that is not access-to-constant,
4269          --  then this construct is a variable reference, which means it is to
4270          --  be considered to have side effects if Variable_Ref is set True
4271          --  Exception is an access to an entity that is a constant or an
4272          --  in-parameter which does not come from source, and is the result
4273          --  of a previous removal of side-effects.
4274
4275          elsif Is_Access_Type (Etype (Prefix (N)))
4276            and then not Is_Access_Constant (Etype (Prefix (N)))
4277            and then Variable_Ref
4278          then
4279             if not Is_Entity_Name (Prefix (N)) then
4280                return False;
4281             else
4282                return Ekind (Entity (Prefix (N))) = E_Constant
4283                  or else Ekind (Entity (Prefix (N))) = E_In_Parameter;
4284             end if;
4285
4286          --  The following test is the simplest way of solving a complex
4287          --  problem uncovered by BB08-010: Side effect on loop bound that
4288          --  is a subcomponent of a global variable:
4289          --    If a loop bound is a subcomponent of a global variable, a
4290          --    modification of that variable within the loop may incorrectly
4291          --    affect the execution of the loop.
4292
4293          elsif not
4294            (Nkind (Parent (Parent (N))) /= N_Loop_Parameter_Specification
4295               or else not Within_In_Parameter (Prefix (N)))
4296          then
4297             return False;
4298
4299          --  All other cases are side effect free
4300
4301          else
4302             return True;
4303          end if;
4304       end Safe_Prefixed_Reference;
4305
4306       ----------------------
4307       -- Side_Effect_Free --
4308       ----------------------
4309
4310       function Side_Effect_Free (N : Node_Id) return Boolean is
4311       begin
4312          --  Note on checks that could raise Constraint_Error. Strictly, if
4313          --  we take advantage of 11.6, these checks do not count as side
4314          --  effects. However, we would just as soon consider that they are
4315          --  side effects, since the backend CSE does not work very well on
4316          --  expressions which can raise Constraint_Error. On the other
4317          --  hand, if we do not consider them to be side effect free, then
4318          --  we get some awkward expansions in -gnato mode, resulting in
4319          --  code insertions at a point where we do not have a clear model
4320          --  for performing the insertions. See 4908-002/comment for details.
4321
4322          --  Special handling for entity names
4323
4324          if Is_Entity_Name (N) then
4325
4326             --  If the entity is a constant, it is definitely side effect
4327             --  free. Note that the test of Is_Variable (N) below might
4328             --  be expected to catch this case, but it does not, because
4329             --  this test goes to the original tree, and we may have
4330             --  already rewritten a variable node with a constant as
4331             --  a result of an earlier Force_Evaluation call.
4332
4333             if Ekind (Entity (N)) = E_Constant
4334               or else Ekind (Entity (N)) = E_In_Parameter
4335             then
4336                return True;
4337
4338             --  Functions are not side effect free
4339
4340             elsif Ekind (Entity (N)) = E_Function then
4341                return False;
4342
4343             --  Variables are considered to be a side effect if Variable_Ref
4344             --  is set or if we have a volatile variable and Name_Req is off.
4345             --  If Name_Req is True then we can't help returning a name which
4346             --  effectively allows multiple references in any case.
4347
4348             elsif Is_Variable (N) then
4349                return not Variable_Ref
4350                  and then (not Treat_As_Volatile (Entity (N))
4351                              or else Name_Req);
4352
4353             --  Any other entity (e.g. a subtype name) is definitely side
4354             --  effect free.
4355
4356             else
4357                return True;
4358             end if;
4359
4360          --  A value known at compile time is always side effect free
4361
4362          elsif Compile_Time_Known_Value (N) then
4363             return True;
4364
4365          --  A variable renaming is not side-effet free, because the
4366          --  renaming will function like a macro in the front-end in
4367          --  some cases, and an assignment can modify the the component
4368          --  designated by N, so we need to create a temporary for it.
4369
4370          elsif Is_Entity_Name (Original_Node (N))
4371            and then Is_Renaming_Of_Object (Entity (Original_Node (N)))
4372            and then Ekind (Entity (Original_Node (N))) /= E_Constant
4373          then
4374             return False;
4375          end if;
4376
4377          --  For other than entity names and compile time known values,
4378          --  check the node kind for special processing.
4379
4380          case Nkind (N) is
4381
4382             --  An attribute reference is side effect free if its expressions
4383             --  are side effect free and its prefix is side effect free or
4384             --  is an entity reference.
4385
4386             --  Is this right? what about x'first where x is a variable???
4387
4388             when N_Attribute_Reference =>
4389                return Side_Effect_Free (Expressions (N))
4390                  and then Attribute_Name (N) /= Name_Input
4391                  and then (Is_Entity_Name (Prefix (N))
4392                             or else Side_Effect_Free (Prefix (N)));
4393
4394             --  A binary operator is side effect free if and both operands
4395             --  are side effect free. For this purpose binary operators
4396             --  include membership tests and short circuit forms
4397
4398             when N_Binary_Op       |
4399                  N_Membership_Test |
4400                  N_And_Then        |
4401                  N_Or_Else         =>
4402                return Side_Effect_Free (Left_Opnd  (N))
4403                  and then Side_Effect_Free (Right_Opnd (N));
4404
4405             --  An explicit dereference is side effect free only if it is
4406             --  a side effect free prefixed reference.
4407
4408             when N_Explicit_Dereference =>
4409                return Safe_Prefixed_Reference (N);
4410
4411             --  A call to _rep_to_pos is side effect free, since we generate
4412             --  this pure function call ourselves. Moreover it is critically
4413             --  important to make this exception, since otherwise we can
4414             --  have discriminants in array components which don't look
4415             --  side effect free in the case of an array whose index type
4416             --  is an enumeration type with an enumeration rep clause.
4417
4418             --  All other function calls are not side effect free
4419
4420             when N_Function_Call =>
4421                return Nkind (Name (N)) = N_Identifier
4422                  and then Is_TSS (Name (N), TSS_Rep_To_Pos)
4423                  and then
4424                    Side_Effect_Free (First (Parameter_Associations (N)));
4425
4426             --  An indexed component is side effect free if it is a side
4427             --  effect free prefixed reference and all the indexing
4428             --  expressions are side effect free.
4429
4430             when N_Indexed_Component =>
4431                return Side_Effect_Free (Expressions (N))
4432                  and then Safe_Prefixed_Reference (N);
4433
4434             --  A type qualification is side effect free if the expression
4435             --  is side effect free.
4436
4437             when N_Qualified_Expression =>
4438                return Side_Effect_Free (Expression (N));
4439
4440             --  A selected component is side effect free only if it is a
4441             --  side effect free prefixed reference. If it designates a
4442             --  component with a rep. clause it must be treated has having
4443             --  a potential side effect, because it may be modified through
4444             --  a renaming, and a subsequent use of the renaming as a macro
4445             --  will yield the wrong value. This complex interaction between
4446             --  renaming and removing side effects is a reminder that the
4447             --  latter has become a headache to maintain, and that it should
4448             --  be removed in favor of the gcc mechanism to capture values ???
4449
4450             when N_Selected_Component =>
4451                if Nkind (Parent (N)) = N_Explicit_Dereference
4452                  and then Has_Non_Standard_Rep (Designated_Type (Etype (N)))
4453                then
4454                   return False;
4455                else
4456                   return Safe_Prefixed_Reference (N);
4457                end if;
4458
4459             --  A range is side effect free if the bounds are side effect free
4460
4461             when N_Range =>
4462                return Side_Effect_Free (Low_Bound (N))
4463                  and then Side_Effect_Free (High_Bound (N));
4464
4465             --  A slice is side effect free if it is a side effect free
4466             --  prefixed reference and the bounds are side effect free.
4467
4468             when N_Slice =>
4469                return Side_Effect_Free (Discrete_Range (N))
4470                  and then Safe_Prefixed_Reference (N);
4471
4472             --  A type conversion is side effect free if the expression to be
4473             --  converted is side effect free.
4474
4475             when N_Type_Conversion =>
4476                return Side_Effect_Free (Expression (N));
4477
4478             --  A unary operator is side effect free if the operand
4479             --  is side effect free.
4480
4481             when N_Unary_Op =>
4482                return Side_Effect_Free (Right_Opnd (N));
4483
4484             --  An unchecked type conversion is side effect free only if it
4485             --  is safe and its argument is side effect free.
4486
4487             when N_Unchecked_Type_Conversion =>
4488                return Safe_Unchecked_Type_Conversion (N)
4489                  and then Side_Effect_Free (Expression (N));
4490
4491             --  An unchecked expression is side effect free if its expression
4492             --  is side effect free.
4493
4494             when N_Unchecked_Expression =>
4495                return Side_Effect_Free (Expression (N));
4496
4497             --  A literal is side effect free
4498
4499             when N_Character_Literal    |
4500                  N_Integer_Literal      |
4501                  N_Real_Literal         |
4502                  N_String_Literal       =>
4503                return True;
4504
4505             --  We consider that anything else has side effects. This is a bit
4506             --  crude, but we are pretty close for most common cases, and we
4507             --  are certainly correct (i.e. we never return True when the
4508             --  answer should be False).
4509
4510             when others =>
4511                return False;
4512          end case;
4513       end Side_Effect_Free;
4514
4515       --  A list is side effect free if all elements of the list are
4516       --  side effect free.
4517
4518       function Side_Effect_Free (L : List_Id) return Boolean is
4519          N : Node_Id;
4520
4521       begin
4522          if L = No_List or else L = Error_List then
4523             return True;
4524
4525          else
4526             N := First (L);
4527             while Present (N) loop
4528                if not Side_Effect_Free (N) then
4529                   return False;
4530                else
4531                   Next (N);
4532                end if;
4533             end loop;
4534
4535             return True;
4536          end if;
4537       end Side_Effect_Free;
4538
4539       -------------------------
4540       -- Within_In_Parameter --
4541       -------------------------
4542
4543       function Within_In_Parameter (N : Node_Id) return Boolean is
4544       begin
4545          if not Comes_From_Source (N) then
4546             return False;
4547
4548          elsif Is_Entity_Name (N) then
4549             return Ekind (Entity (N)) = E_In_Parameter;
4550
4551          elsif Nkind (N) = N_Indexed_Component
4552            or else Nkind (N) = N_Selected_Component
4553          then
4554             return Within_In_Parameter (Prefix (N));
4555          else
4556
4557             return False;
4558          end if;
4559       end Within_In_Parameter;
4560
4561    --  Start of processing for Remove_Side_Effects
4562
4563    begin
4564       --  If we are side effect free already or expansion is disabled,
4565       --  there is nothing to do.
4566
4567       if Side_Effect_Free (Exp) or else not Expander_Active then
4568          return;
4569       end if;
4570
4571       --  All this must not have any checks
4572
4573       Scope_Suppress := (others => True);
4574
4575       --  If it is a scalar type and we need to capture the value, just make
4576       --  a copy. Likewise for a function or operator call. And if we have a
4577       --  volatile variable and Nam_Req is not set (see comments above for
4578       --  Side_Effect_Free).
4579
4580       if Is_Elementary_Type (Exp_Type)
4581         and then (Variable_Ref
4582                    or else Nkind (Exp) = N_Function_Call
4583                    or else Nkind (Exp) in N_Op
4584                    or else (not Name_Req
4585                              and then Is_Entity_Name (Exp)
4586                              and then Treat_As_Volatile (Entity (Exp))))
4587       then
4588          Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4589          Set_Etype (Def_Id, Exp_Type);
4590          Res := New_Reference_To (Def_Id, Loc);
4591
4592          E :=
4593            Make_Object_Declaration (Loc,
4594              Defining_Identifier => Def_Id,
4595              Object_Definition   => New_Reference_To (Exp_Type, Loc),
4596              Constant_Present    => True,
4597              Expression          => Relocate_Node (Exp));
4598
4599          Set_Assignment_OK (E);
4600          Insert_Action (Exp, E);
4601
4602       --  If the expression has the form v.all then we can just capture
4603       --  the pointer, and then do an explicit dereference on the result.
4604
4605       elsif Nkind (Exp) = N_Explicit_Dereference then
4606          Def_Id :=
4607            Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4608          Res :=
4609            Make_Explicit_Dereference (Loc, New_Reference_To (Def_Id, Loc));
4610
4611          Insert_Action (Exp,
4612            Make_Object_Declaration (Loc,
4613              Defining_Identifier => Def_Id,
4614              Object_Definition   =>
4615                New_Reference_To (Etype (Prefix (Exp)), Loc),
4616              Constant_Present    => True,
4617              Expression          => Relocate_Node (Prefix (Exp))));
4618
4619       --  Similar processing for an unchecked conversion of an expression
4620       --  of the form v.all, where we want the same kind of treatment.
4621
4622       elsif Nkind (Exp) = N_Unchecked_Type_Conversion
4623         and then Nkind (Expression (Exp)) = N_Explicit_Dereference
4624       then
4625          Remove_Side_Effects (Expression (Exp), Name_Req, Variable_Ref);
4626          Scope_Suppress := Svg_Suppress;
4627          return;
4628
4629       --  If this is a type conversion, leave the type conversion and remove
4630       --  the side effects in the expression. This is important in several
4631       --  circumstances: for change of representations, and also when this
4632       --  is a view conversion to a smaller object, where gigi can end up
4633       --  creating its own temporary of the wrong size.
4634
4635       elsif Nkind (Exp) = N_Type_Conversion then
4636          Remove_Side_Effects (Expression (Exp), Name_Req, Variable_Ref);
4637          Scope_Suppress := Svg_Suppress;
4638          return;
4639
4640       --  If this is an unchecked conversion that Gigi can't handle, make
4641       --  a copy or a use a renaming to capture the value.
4642
4643       elsif Nkind (Exp) = N_Unchecked_Type_Conversion
4644         and then not Safe_Unchecked_Type_Conversion (Exp)
4645       then
4646          if CW_Or_Controlled_Type (Exp_Type) then
4647
4648             --  Use a renaming to capture the expression, rather than create
4649             --  a controlled temporary.
4650
4651             Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4652             Res := New_Reference_To (Def_Id, Loc);
4653
4654             Insert_Action (Exp,
4655               Make_Object_Renaming_Declaration (Loc,
4656                 Defining_Identifier => Def_Id,
4657                 Subtype_Mark        => New_Reference_To (Exp_Type, Loc),
4658                 Name                => Relocate_Node (Exp)));
4659
4660          else
4661             Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4662             Set_Etype (Def_Id, Exp_Type);
4663             Res := New_Reference_To (Def_Id, Loc);
4664
4665             E :=
4666               Make_Object_Declaration (Loc,
4667                 Defining_Identifier => Def_Id,
4668                 Object_Definition   => New_Reference_To (Exp_Type, Loc),
4669                 Constant_Present    => not Is_Variable (Exp),
4670                 Expression          => Relocate_Node (Exp));
4671
4672             Set_Assignment_OK (E);
4673             Insert_Action (Exp, E);
4674          end if;
4675
4676       --  For expressions that denote objects, we can use a renaming scheme.
4677       --  We skip using this if we have a volatile variable and we do not
4678       --  have Nam_Req set true (see comments above for Side_Effect_Free).
4679
4680       elsif Is_Object_Reference (Exp)
4681         and then Nkind (Exp) /= N_Function_Call
4682         and then (Name_Req
4683                    or else not Is_Entity_Name (Exp)
4684                    or else not Treat_As_Volatile (Entity (Exp)))
4685       then
4686          Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4687
4688          if Nkind (Exp) = N_Selected_Component
4689            and then Nkind (Prefix (Exp)) = N_Function_Call
4690            and then Is_Array_Type (Exp_Type)
4691          then
4692             --  Avoid generating a variable-sized temporary, by generating
4693             --  the renaming declaration just for the function call. The
4694             --  transformation could be refined to apply only when the array
4695             --  component is constrained by a discriminant???
4696
4697             Res :=
4698               Make_Selected_Component (Loc,
4699                 Prefix => New_Occurrence_Of (Def_Id, Loc),
4700                 Selector_Name => Selector_Name (Exp));
4701
4702             Insert_Action (Exp,
4703               Make_Object_Renaming_Declaration (Loc,
4704                 Defining_Identifier => Def_Id,
4705                 Subtype_Mark        =>
4706                   New_Reference_To (Base_Type (Etype (Prefix (Exp))), Loc),
4707                 Name                => Relocate_Node (Prefix (Exp))));
4708
4709          else
4710             Res := New_Reference_To (Def_Id, Loc);
4711
4712             Insert_Action (Exp,
4713               Make_Object_Renaming_Declaration (Loc,
4714                 Defining_Identifier => Def_Id,
4715                 Subtype_Mark        => New_Reference_To (Exp_Type, Loc),
4716                 Name                => Relocate_Node (Exp)));
4717
4718          end if;
4719
4720          --  If this is a packed reference, or a selected component with a
4721          --  non-standard representation, a reference to the temporary will
4722          --  be replaced by a copy of the original expression (see
4723          --  exp_ch2.Expand_Renaming). Otherwise the temporary must be
4724          --  elaborated by gigi, and is of course not to be replaced in-line
4725          --  by the expression it renames, which would defeat the purpose of
4726          --  removing the side-effect.
4727
4728          if (Nkind (Exp) = N_Selected_Component
4729               or else Nkind (Exp) = N_Indexed_Component)
4730            and then Has_Non_Standard_Rep (Etype (Prefix (Exp)))
4731          then
4732             null;
4733          else
4734             Set_Is_Renaming_Of_Object (Def_Id, False);
4735          end if;
4736
4737       --  Otherwise we generate a reference to the value
4738
4739       else
4740          Ref_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
4741
4742          Ptr_Typ_Decl :=
4743            Make_Full_Type_Declaration (Loc,
4744              Defining_Identifier => Ref_Type,
4745              Type_Definition =>
4746                Make_Access_To_Object_Definition (Loc,
4747                  All_Present => True,
4748                  Subtype_Indication =>
4749                    New_Reference_To (Exp_Type, Loc)));
4750
4751          E := Exp;
4752          Insert_Action (Exp, Ptr_Typ_Decl);
4753
4754          Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4755          Set_Etype (Def_Id, Exp_Type);
4756
4757          Res :=
4758            Make_Explicit_Dereference (Loc,
4759              Prefix => New_Reference_To (Def_Id, Loc));
4760
4761          if Nkind (E) = N_Explicit_Dereference then
4762             New_Exp := Relocate_Node (Prefix (E));
4763          else
4764             E := Relocate_Node (E);
4765             New_Exp := Make_Reference (Loc, E);
4766          end if;
4767
4768          if Is_Delayed_Aggregate (E) then
4769
4770             --  The expansion of nested aggregates is delayed until the
4771             --  enclosing aggregate is expanded. As aggregates are often
4772             --  qualified, the predicate applies to qualified expressions
4773             --  as well, indicating that the enclosing aggregate has not
4774             --  been expanded yet. At this point the aggregate is part of
4775             --  a stand-alone declaration, and must be fully expanded.
4776
4777             if Nkind (E) = N_Qualified_Expression then
4778                Set_Expansion_Delayed (Expression (E), False);
4779                Set_Analyzed (Expression (E), False);
4780             else
4781                Set_Expansion_Delayed (E, False);
4782             end if;
4783
4784             Set_Analyzed (E, False);
4785          end if;
4786
4787          Insert_Action (Exp,
4788            Make_Object_Declaration (Loc,
4789              Defining_Identifier => Def_Id,
4790              Object_Definition   => New_Reference_To (Ref_Type, Loc),
4791              Expression          => New_Exp));
4792       end if;
4793
4794       --  Preserve the Assignment_OK flag in all copies, since at least
4795       --  one copy may be used in a context where this flag must be set
4796       --  (otherwise why would the flag be set in the first place).
4797
4798       Set_Assignment_OK (Res, Assignment_OK (Exp));
4799
4800       --  Finally rewrite the original expression and we are done
4801
4802       Rewrite (Exp, Res);
4803       Analyze_And_Resolve (Exp, Exp_Type);
4804       Scope_Suppress := Svg_Suppress;
4805    end Remove_Side_Effects;
4806
4807    ---------------------------
4808    -- Represented_As_Scalar --
4809    ---------------------------
4810
4811    function Represented_As_Scalar (T : Entity_Id) return Boolean is
4812       UT : constant Entity_Id := Underlying_Type (T);
4813    begin
4814       return Is_Scalar_Type (UT)
4815         or else (Is_Bit_Packed_Array (UT)
4816                    and then Is_Scalar_Type (Packed_Array_Type (UT)));
4817    end Represented_As_Scalar;
4818
4819    ------------------------------------
4820    -- Safe_Unchecked_Type_Conversion --
4821    ------------------------------------
4822
4823    --  Note: this function knows quite a bit about the exact requirements
4824    --  of Gigi with respect to unchecked type conversions, and its code
4825    --  must be coordinated with any changes in Gigi in this area.
4826
4827    --  The above requirements should be documented in Sinfo ???
4828
4829    function Safe_Unchecked_Type_Conversion (Exp : Node_Id) return Boolean is
4830       Otyp   : Entity_Id;
4831       Ityp   : Entity_Id;
4832       Oalign : Uint;
4833       Ialign : Uint;
4834       Pexp   : constant Node_Id := Parent (Exp);
4835
4836    begin
4837       --  If the expression is the RHS of an assignment or object declaration
4838       --   we are always OK because there will always be a target.
4839
4840       --  Object renaming declarations, (generated for view conversions of
4841       --  actuals in inlined calls), like object declarations, provide an
4842       --  explicit type, and are safe as well.
4843
4844       if (Nkind (Pexp) = N_Assignment_Statement
4845            and then Expression (Pexp) = Exp)
4846         or else Nkind (Pexp) = N_Object_Declaration
4847         or else Nkind (Pexp) = N_Object_Renaming_Declaration
4848       then
4849          return True;
4850
4851       --  If the expression is the prefix of an N_Selected_Component
4852       --  we should also be OK because GCC knows to look inside the
4853       --  conversion except if the type is discriminated. We assume
4854       --  that we are OK anyway if the type is not set yet or if it is
4855       --  controlled since we can't afford to introduce a temporary in
4856       --  this case.
4857
4858       elsif Nkind (Pexp) = N_Selected_Component
4859          and then Prefix (Pexp) = Exp
4860       then
4861          if No (Etype (Pexp)) then
4862             return True;
4863          else
4864             return
4865               not Has_Discriminants (Etype (Pexp))
4866                 or else Is_Constrained (Etype (Pexp));
4867          end if;
4868       end if;
4869
4870       --  Set the output type, this comes from Etype if it is set, otherwise
4871       --  we take it from the subtype mark, which we assume was already
4872       --  fully analyzed.
4873
4874       if Present (Etype (Exp)) then
4875          Otyp := Etype (Exp);
4876       else
4877          Otyp := Entity (Subtype_Mark (Exp));
4878       end if;
4879
4880       --  The input type always comes from the expression, and we assume
4881       --  this is indeed always analyzed, so we can simply get the Etype.
4882
4883       Ityp := Etype (Expression (Exp));
4884
4885       --  Initialize alignments to unknown so far
4886
4887       Oalign := No_Uint;
4888       Ialign := No_Uint;
4889
4890       --  Replace a concurrent type by its corresponding record type
4891       --  and each type by its underlying type and do the tests on those.
4892       --  The original type may be a private type whose completion is a
4893       --  concurrent type, so find the underlying type first.
4894
4895       if Present (Underlying_Type (Otyp)) then
4896          Otyp := Underlying_Type (Otyp);
4897       end if;
4898
4899       if Present (Underlying_Type (Ityp)) then
4900          Ityp := Underlying_Type (Ityp);
4901       end if;
4902
4903       if Is_Concurrent_Type (Otyp) then
4904          Otyp := Corresponding_Record_Type (Otyp);
4905       end if;
4906
4907       if Is_Concurrent_Type (Ityp) then
4908          Ityp := Corresponding_Record_Type (Ityp);
4909       end if;
4910
4911       --  If the base types are the same, we know there is no problem since
4912       --  this conversion will be a noop.
4913
4914       if Implementation_Base_Type (Otyp) = Implementation_Base_Type (Ityp) then
4915          return True;
4916
4917       --  Same if this is an upwards conversion of an untagged type, and there
4918       --  are no constraints involved (could be more general???)
4919
4920       elsif Etype (Ityp) = Otyp
4921         and then not Is_Tagged_Type (Ityp)
4922         and then not Has_Discriminants (Ityp)
4923         and then No (First_Rep_Item (Base_Type (Ityp)))
4924       then
4925          return True;
4926
4927       --  If the size of output type is known at compile time, there is
4928       --  never a problem.  Note that unconstrained records are considered
4929       --  to be of known size, but we can't consider them that way here,
4930       --  because we are talking about the actual size of the object.
4931
4932       --  We also make sure that in addition to the size being known, we do
4933       --  not have a case which might generate an embarrassingly large temp
4934       --  in stack checking mode.
4935
4936       elsif Size_Known_At_Compile_Time (Otyp)
4937         and then
4938           (not Stack_Checking_Enabled
4939              or else not May_Generate_Large_Temp (Otyp))
4940         and then not (Is_Record_Type (Otyp) and then not Is_Constrained (Otyp))
4941       then
4942          return True;
4943
4944       --  If either type is tagged, then we know the alignment is OK so
4945       --  Gigi will be able to use pointer punning.
4946
4947       elsif Is_Tagged_Type (Otyp) or else Is_Tagged_Type (Ityp) then
4948          return True;
4949
4950       --  If either type is a limited record type, we cannot do a copy, so
4951       --  say safe since there's nothing else we can do.
4952
4953       elsif Is_Limited_Record (Otyp) or else Is_Limited_Record (Ityp) then
4954          return True;
4955
4956       --  Conversions to and from packed array types are always ignored and
4957       --  hence are safe.
4958
4959       elsif Is_Packed_Array_Type (Otyp)
4960         or else Is_Packed_Array_Type (Ityp)
4961       then
4962          return True;
4963       end if;
4964
4965       --  The only other cases known to be safe is if the input type's
4966       --  alignment is known to be at least the maximum alignment for the
4967       --  target or if both alignments are known and the output type's
4968       --  alignment is no stricter than the input's.  We can use the alignment
4969       --  of the component type of an array if a type is an unpacked
4970       --  array type.
4971
4972       if Present (Alignment_Clause (Otyp)) then
4973          Oalign := Expr_Value (Expression (Alignment_Clause (Otyp)));
4974
4975       elsif Is_Array_Type (Otyp)
4976         and then Present (Alignment_Clause (Component_Type (Otyp)))
4977       then
4978          Oalign := Expr_Value (Expression (Alignment_Clause
4979                                            (Component_Type (Otyp))));
4980       end if;
4981
4982       if Present (Alignment_Clause (Ityp)) then
4983          Ialign := Expr_Value (Expression (Alignment_Clause (Ityp)));
4984
4985       elsif Is_Array_Type (Ityp)
4986         and then Present (Alignment_Clause (Component_Type (Ityp)))
4987       then
4988          Ialign := Expr_Value (Expression (Alignment_Clause
4989                                            (Component_Type (Ityp))));
4990       end if;
4991
4992       if Ialign /= No_Uint and then Ialign > Maximum_Alignment then
4993          return True;
4994
4995       elsif Ialign /= No_Uint and then Oalign /= No_Uint
4996         and then Ialign <= Oalign
4997       then
4998          return True;
4999
5000       --   Otherwise, Gigi cannot handle this and we must make a temporary
5001
5002       else
5003          return False;
5004       end if;
5005    end Safe_Unchecked_Type_Conversion;
5006
5007    ---------------------------------
5008    -- Set_Current_Value_Condition --
5009    ---------------------------------
5010
5011    --  Note: the implementation of this procedure is very closely tied to the
5012    --  implementation of Get_Current_Value_Condition. Here we set required
5013    --  Current_Value fields, and in Get_Current_Value_Condition, we interpret
5014    --  them, so they must have a consistent view.
5015
5016    procedure Set_Current_Value_Condition (Cnode : Node_Id) is
5017
5018       procedure Set_Entity_Current_Value (N : Node_Id);
5019       --  If N is an entity reference, where the entity is of an appropriate
5020       --  kind, then set the current value of this entity to Cnode, unless
5021       --  there is already a definite value set there.
5022
5023       procedure Set_Expression_Current_Value (N : Node_Id);
5024       --  If N is of an appropriate form, sets an appropriate entry in current
5025       --  value fields of relevant entities. Multiple entities can be affected
5026       --  in the case of an AND or AND THEN.
5027
5028       ------------------------------
5029       -- Set_Entity_Current_Value --
5030       ------------------------------
5031
5032       procedure Set_Entity_Current_Value (N : Node_Id) is
5033       begin
5034          if Is_Entity_Name (N) then
5035             declare
5036                Ent : constant Entity_Id := Entity (N);
5037
5038             begin
5039                --  Don't capture if not safe to do so
5040
5041                if not Safe_To_Capture_Value (N, Ent, Cond => True) then
5042                   return;
5043                end if;
5044
5045                --  Here we have a case where the Current_Value field may
5046                --  need to be set. We set it if it is not already set to a
5047                --  compile time expression value.
5048
5049                --  Note that this represents a decision that one condition
5050                --  blots out another previous one. That's certainly right
5051                --  if they occur at the same level. If the second one is
5052                --  nested, then the decision is neither right nor wrong (it
5053                --  would be equally OK to leave the outer one in place, or
5054                --  take the new inner one. Really we should record both, but
5055                --  our data structures are not that elaborate.
5056
5057                if Nkind (Current_Value (Ent)) not in N_Subexpr then
5058                   Set_Current_Value (Ent, Cnode);
5059                end if;
5060             end;
5061          end if;
5062       end Set_Entity_Current_Value;
5063
5064       ----------------------------------
5065       -- Set_Expression_Current_Value --
5066       ----------------------------------
5067
5068       procedure Set_Expression_Current_Value (N : Node_Id) is
5069          Cond : Node_Id;
5070
5071       begin
5072          Cond := N;
5073
5074          --  Loop to deal with (ignore for now) any NOT operators present. The
5075          --  presence of NOT operators will be handled properly when we call
5076          --  Get_Current_Value_Condition.
5077
5078          while Nkind (Cond) = N_Op_Not loop
5079             Cond := Right_Opnd (Cond);
5080          end loop;
5081
5082          --  For an AND or AND THEN, recursively process operands
5083
5084          if Nkind (Cond) = N_Op_And or else Nkind (Cond) = N_And_Then then
5085             Set_Expression_Current_Value (Left_Opnd (Cond));
5086             Set_Expression_Current_Value (Right_Opnd (Cond));
5087             return;
5088          end if;
5089
5090          --  Check possible relational operator
5091
5092          if Nkind (Cond) in N_Op_Compare then
5093             if Compile_Time_Known_Value (Right_Opnd (Cond)) then
5094                Set_Entity_Current_Value (Left_Opnd (Cond));
5095             elsif Compile_Time_Known_Value (Left_Opnd (Cond)) then
5096                Set_Entity_Current_Value (Right_Opnd (Cond));
5097             end if;
5098
5099             --  Check possible boolean variable reference
5100
5101          else
5102             Set_Entity_Current_Value (Cond);
5103          end if;
5104       end Set_Expression_Current_Value;
5105
5106    --  Start of processing for Set_Current_Value_Condition
5107
5108    begin
5109       Set_Expression_Current_Value (Condition (Cnode));
5110    end Set_Current_Value_Condition;
5111
5112    --------------------------
5113    -- Set_Elaboration_Flag --
5114    --------------------------
5115
5116    procedure Set_Elaboration_Flag (N : Node_Id; Spec_Id : Entity_Id) is
5117       Loc : constant Source_Ptr := Sloc (N);
5118       Ent : constant Entity_Id  := Elaboration_Entity (Spec_Id);
5119       Asn : Node_Id;
5120
5121    begin
5122       if Present (Ent) then
5123
5124          --  Nothing to do if at the compilation unit level, because in this
5125          --  case the flag is set by the binder generated elaboration routine.
5126
5127          if Nkind (Parent (N)) = N_Compilation_Unit then
5128             null;
5129
5130          --  Here we do need to generate an assignment statement
5131
5132          else
5133             Check_Restriction (No_Elaboration_Code, N);
5134             Asn :=
5135               Make_Assignment_Statement (Loc,
5136                 Name       => New_Occurrence_Of (Ent, Loc),
5137                 Expression => New_Occurrence_Of (Standard_True, Loc));
5138
5139             if Nkind (Parent (N)) = N_Subunit then
5140                Insert_After (Corresponding_Stub (Parent (N)), Asn);
5141             else
5142                Insert_After (N, Asn);
5143             end if;
5144
5145             Analyze (Asn);
5146
5147             --  Kill current value indication. This is necessary because
5148             --  the tests of this flag are inserted out of sequence and must
5149             --  not pick up bogus indications of the wrong constant value.
5150
5151             Set_Current_Value (Ent, Empty);
5152          end if;
5153       end if;
5154    end Set_Elaboration_Flag;
5155
5156    ----------------------------
5157    -- Set_Renamed_Subprogram --
5158    ----------------------------
5159
5160    procedure Set_Renamed_Subprogram (N : Node_Id; E : Entity_Id) is
5161    begin
5162       --  If input node is an identifier, we can just reset it
5163
5164       if Nkind (N) = N_Identifier then
5165          Set_Chars  (N, Chars (E));
5166          Set_Entity (N, E);
5167
5168          --  Otherwise we have to do a rewrite, preserving Comes_From_Source
5169
5170       else
5171          declare
5172             CS : constant Boolean := Comes_From_Source (N);
5173          begin
5174             Rewrite (N, Make_Identifier (Sloc (N), Chars => Chars (E)));
5175             Set_Entity (N, E);
5176             Set_Comes_From_Source (N, CS);
5177             Set_Analyzed (N, True);
5178          end;
5179       end if;
5180    end Set_Renamed_Subprogram;
5181
5182    --------------------------
5183    -- Target_Has_Fixed_Ops --
5184    --------------------------
5185
5186    Integer_Sized_Small : Ureal;
5187    --  Set to 2.0 ** -(Integer'Size - 1) the first time that this
5188    --  function is called (we don't want to compute it more than once!)
5189
5190    Long_Integer_Sized_Small : Ureal;
5191    --  Set to 2.0 ** -(Long_Integer'Size - 1) the first time that this
5192    --  functoin is called (we don't want to compute it more than once)
5193
5194    First_Time_For_THFO : Boolean := True;
5195    --  Set to False after first call (if Fractional_Fixed_Ops_On_Target)
5196
5197    function Target_Has_Fixed_Ops
5198      (Left_Typ   : Entity_Id;
5199       Right_Typ  : Entity_Id;
5200       Result_Typ : Entity_Id) return Boolean
5201    is
5202       function Is_Fractional_Type (Typ : Entity_Id) return Boolean;
5203       --  Return True if the given type is a fixed-point type with a small
5204       --  value equal to 2 ** (-(T'Object_Size - 1)) and whose values have
5205       --  an absolute value less than 1.0. This is currently limited
5206       --  to fixed-point types that map to Integer or Long_Integer.
5207
5208       ------------------------
5209       -- Is_Fractional_Type --
5210       ------------------------
5211
5212       function Is_Fractional_Type (Typ : Entity_Id) return Boolean is
5213       begin
5214          if Esize (Typ) = Standard_Integer_Size then
5215             return Small_Value (Typ) = Integer_Sized_Small;
5216
5217          elsif Esize (Typ) = Standard_Long_Integer_Size then
5218             return Small_Value (Typ) = Long_Integer_Sized_Small;
5219
5220          else
5221             return False;
5222          end if;
5223       end Is_Fractional_Type;
5224
5225    --  Start of processing for Target_Has_Fixed_Ops
5226
5227    begin
5228       --  Return False if Fractional_Fixed_Ops_On_Target is false
5229
5230       if not Fractional_Fixed_Ops_On_Target then
5231          return False;
5232       end if;
5233
5234       --  Here the target has Fractional_Fixed_Ops, if first time, compute
5235       --  standard constants used by Is_Fractional_Type.
5236
5237       if First_Time_For_THFO then
5238          First_Time_For_THFO := False;
5239
5240          Integer_Sized_Small :=
5241            UR_From_Components
5242              (Num   => Uint_1,
5243               Den   => UI_From_Int (Standard_Integer_Size - 1),
5244               Rbase => 2);
5245
5246          Long_Integer_Sized_Small :=
5247            UR_From_Components
5248              (Num   => Uint_1,
5249               Den   => UI_From_Int (Standard_Long_Integer_Size - 1),
5250               Rbase => 2);
5251       end if;
5252
5253       --  Return True if target supports fixed-by-fixed multiply/divide
5254       --  for fractional fixed-point types (see Is_Fractional_Type) and
5255       --  the operand and result types are equivalent fractional types.
5256
5257       return Is_Fractional_Type (Base_Type (Left_Typ))
5258         and then Is_Fractional_Type (Base_Type (Right_Typ))
5259         and then Is_Fractional_Type (Base_Type (Result_Typ))
5260         and then Esize (Left_Typ) = Esize (Right_Typ)
5261         and then Esize (Left_Typ) = Esize (Result_Typ);
5262    end Target_Has_Fixed_Ops;
5263
5264    ------------------------------------------
5265    -- Type_May_Have_Bit_Aligned_Components --
5266    ------------------------------------------
5267
5268    function Type_May_Have_Bit_Aligned_Components
5269      (Typ : Entity_Id) return Boolean
5270    is
5271    begin
5272       --  Array type, check component type
5273
5274       if Is_Array_Type (Typ) then
5275          return
5276            Type_May_Have_Bit_Aligned_Components (Component_Type (Typ));
5277
5278       --  Record type, check components
5279
5280       elsif Is_Record_Type (Typ) then
5281          declare
5282             E : Entity_Id;
5283
5284          begin
5285             E := First_Component_Or_Discriminant (Typ);
5286             while Present (E) loop
5287                if Component_May_Be_Bit_Aligned (E)
5288                  or else Type_May_Have_Bit_Aligned_Components (Etype (E))
5289                then
5290                   return True;
5291                end if;
5292
5293                Next_Component_Or_Discriminant (E);
5294             end loop;
5295
5296             return False;
5297          end;
5298
5299       --  Type other than array or record is always OK
5300
5301       else
5302          return False;
5303       end if;
5304    end Type_May_Have_Bit_Aligned_Components;
5305
5306    ----------------------------
5307    -- Wrap_Cleanup_Procedure --
5308    ----------------------------
5309
5310    procedure Wrap_Cleanup_Procedure (N : Node_Id) is
5311       Loc   : constant Source_Ptr := Sloc (N);
5312       Stseq : constant Node_Id    := Handled_Statement_Sequence (N);
5313       Stmts : constant List_Id    := Statements (Stseq);
5314
5315    begin
5316       if Abort_Allowed then
5317          Prepend_To (Stmts, Build_Runtime_Call (Loc, RE_Abort_Defer));
5318          Append_To  (Stmts, Build_Runtime_Call (Loc, RE_Abort_Undefer));
5319       end if;
5320    end Wrap_Cleanup_Procedure;
5321
5322 end Exp_Util;