OSDN Git Service

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