1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                              S E M _ R E S                               --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1992-2021, 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
26with Aspects;        use Aspects;
27with Atree;          use Atree;
28with Checks;         use Checks;
29with Debug;          use Debug;
30with Debug_A;        use Debug_A;
31with Einfo;          use Einfo;
32with Einfo.Entities; use Einfo.Entities;
33with Einfo.Utils;    use Einfo.Utils;
34with Errout;         use Errout;
35with Expander;       use Expander;
36with Exp_Ch6;        use Exp_Ch6;
37with Exp_Ch7;        use Exp_Ch7;
38with Exp_Disp;       use Exp_Disp;
39with Exp_Tss;        use Exp_Tss;
40with Exp_Util;       use Exp_Util;
41with Freeze;         use Freeze;
42with Ghost;          use Ghost;
43with Inline;         use Inline;
44with Itypes;         use Itypes;
45with Lib;            use Lib;
46with Lib.Xref;       use Lib.Xref;
47with Namet;          use Namet;
48with Nmake;          use Nmake;
49with Nlists;         use Nlists;
50with Opt;            use Opt;
51with Output;         use Output;
52with Par_SCO;        use Par_SCO;
53with Restrict;       use Restrict;
54with Rident;         use Rident;
55with Rtsfind;        use Rtsfind;
56with Sem;            use Sem;
57with Sem_Aggr;       use Sem_Aggr;
58with Sem_Attr;       use Sem_Attr;
59with Sem_Aux;        use Sem_Aux;
60with Sem_Case;       use Sem_Case;
61with Sem_Cat;        use Sem_Cat;
62with Sem_Ch3;        use Sem_Ch3;
63with Sem_Ch4;        use Sem_Ch4;
64with Sem_Ch6;        use Sem_Ch6;
65with Sem_Ch8;        use Sem_Ch8;
66with Sem_Ch13;       use Sem_Ch13;
67with Sem_Dim;        use Sem_Dim;
68with Sem_Disp;       use Sem_Disp;
69with Sem_Dist;       use Sem_Dist;
70with Sem_Elab;       use Sem_Elab;
71with Sem_Elim;       use Sem_Elim;
72with Sem_Eval;       use Sem_Eval;
73with Sem_Intr;       use Sem_Intr;
74with Sem_Mech;       use Sem_Mech;
75with Sem_Type;       use Sem_Type;
76with Sem_Util;       use Sem_Util;
77with Sem_Warn;       use Sem_Warn;
78with Sinfo;          use Sinfo;
79with Sinfo.Nodes;    use Sinfo.Nodes;
80with Sinfo.Utils;    use Sinfo.Utils;
81with Sinfo.CN;       use Sinfo.CN;
82with Snames;         use Snames;
83with Stand;          use Stand;
84with Stringt;        use Stringt;
85with Strub;          use Strub;
86with Style;          use Style;
87with Targparm;       use Targparm;
88with Tbuild;         use Tbuild;
89with Uintp;          use Uintp;
90with Urealp;         use Urealp;
91
92package body Sem_Res is
93
94   -----------------------
95   -- Local Subprograms --
96   -----------------------
97
98   --  Second pass (top-down) type checking and overload resolution procedures
99   --  Typ is the type required by context. These procedures propagate the
100   --  type information recursively to the descendants of N. If the node is not
101   --  overloaded, its Etype is established in the first pass. If overloaded,
102   --  the Resolve routines set the correct type. For arithmetic operators, the
103   --  Etype is the base type of the context.
104
105   --  Note that Resolve_Attribute is separated off in Sem_Attr
106
107   function Has_Applicable_User_Defined_Literal
108     (N   : Node_Id;
109      Typ : Entity_Id) return Boolean;
110   --  If N is a literal or a named number, check whether Typ
111   --  has a user-defined literal aspect that can apply to N.
112   --  If present, replace N with a call to the corresponding
113   --  function and return True.
114
115   procedure Check_Discriminant_Use (N : Node_Id);
116   --  Enforce the restrictions on the use of discriminants when constraining
117   --  a component of a discriminated type (record or concurrent type).
118
119   procedure Check_For_Visible_Operator (N : Node_Id; T : Entity_Id);
120   --  Given a node for an operator associated with type T, check that the
121   --  operator is visible. Operators all of whose operands are universal must
122   --  be checked for visibility during resolution because their type is not
123   --  determinable based on their operands.
124
125   procedure Check_Fully_Declared_Prefix
126     (Typ  : Entity_Id;
127      Pref : Node_Id);
128   --  Check that the type of the prefix of a dereference is not incomplete
129
130   function Check_Infinite_Recursion (Call : Node_Id) return Boolean;
131   --  Given a call node, Call, which is known to occur immediately within the
132   --  subprogram being called, determines whether it is a detectable case of
133   --  an infinite recursion, and if so, outputs appropriate messages. Returns
134   --  True if an infinite recursion is detected, and False otherwise.
135
136   procedure Check_No_Direct_Boolean_Operators (N : Node_Id);
137   --  N is the node for a logical operator. If the operator is predefined, and
138   --  the root type of the operands is Standard.Boolean, then a check is made
139   --  for restriction No_Direct_Boolean_Operators. This procedure also handles
140   --  the style check for Style_Check_Boolean_And_Or.
141
142   function Is_Atomic_Ref_With_Address (N : Node_Id) return Boolean;
143   --  N is either an indexed component or a selected component. This function
144   --  returns true if the prefix refers to an object that has an address
145   --  clause (the case in which we may want to issue a warning).
146
147   function Is_Definite_Access_Type (E : Entity_Id) return Boolean;
148   --  Determine whether E is an access type declared by an access declaration,
149   --  and not an (anonymous) allocator type.
150
151   function Is_Predefined_Op (Nam : Entity_Id) return Boolean;
152   --  Utility to check whether the entity for an operator is a predefined
153   --  operator, in which case the expression is left as an operator in the
154   --  tree (else it is rewritten into a call). An instance of an intrinsic
155   --  conversion operation may be given an operator name, but is not treated
156   --  like an operator. Note that an operator that is an imported back-end
157   --  builtin has convention Intrinsic, but is expected to be rewritten into
158   --  a call, so such an operator is not treated as predefined by this
159   --  predicate.
160
161   procedure Preanalyze_And_Resolve
162     (N             : Node_Id;
163      T             : Entity_Id;
164      With_Freezing : Boolean);
165   --  Subsidiary of public versions of Preanalyze_And_Resolve.
166
167   procedure Replace_Actual_Discriminants (N : Node_Id; Default : Node_Id);
168   --  If a default expression in entry call N depends on the discriminants
169   --  of the task, it must be replaced with a reference to the discriminant
170   --  of the task being called.
171
172   procedure Resolve_Op_Concat_Arg
173     (N       : Node_Id;
174      Arg     : Node_Id;
175      Typ     : Entity_Id;
176      Is_Comp : Boolean);
177   --  Internal procedure for Resolve_Op_Concat to resolve one operand of
178   --  concatenation operator. The operand is either of the array type or of
179   --  the component type. If the operand is an aggregate, and the component
180   --  type is composite, this is ambiguous if component type has aggregates.
181
182   procedure Resolve_Op_Concat_First (N : Node_Id; Typ : Entity_Id);
183   --  Does the first part of the work of Resolve_Op_Concat
184
185   procedure Resolve_Op_Concat_Rest (N : Node_Id; Typ : Entity_Id);
186   --  Does the "rest" of the work of Resolve_Op_Concat, after the left operand
187   --  has been resolved. See Resolve_Op_Concat for details.
188
189   procedure Resolve_Allocator                 (N : Node_Id; Typ : Entity_Id);
190   procedure Resolve_Arithmetic_Op             (N : Node_Id; Typ : Entity_Id);
191   procedure Resolve_Call                      (N : Node_Id; Typ : Entity_Id);
192   procedure Resolve_Case_Expression           (N : Node_Id; Typ : Entity_Id);
193   procedure Resolve_Character_Literal         (N : Node_Id; Typ : Entity_Id);
194   procedure Resolve_Comparison_Op             (N : Node_Id; Typ : Entity_Id);
195   procedure Resolve_Declare_Expression        (N : Node_Id; Typ : Entity_Id);
196   procedure Resolve_Entity_Name               (N : Node_Id; Typ : Entity_Id);
197   procedure Resolve_Equality_Op               (N : Node_Id; Typ : Entity_Id);
198   procedure Resolve_Explicit_Dereference      (N : Node_Id; Typ : Entity_Id);
199   procedure Resolve_Expression_With_Actions   (N : Node_Id; Typ : Entity_Id);
200   procedure Resolve_If_Expression             (N : Node_Id; Typ : Entity_Id);
201   procedure Resolve_Generalized_Indexing      (N : Node_Id; Typ : Entity_Id);
202   procedure Resolve_Indexed_Component         (N : Node_Id; Typ : Entity_Id);
203   procedure Resolve_Integer_Literal           (N : Node_Id; Typ : Entity_Id);
204   procedure Resolve_Logical_Op                (N : Node_Id; Typ : Entity_Id);
205   procedure Resolve_Membership_Op             (N : Node_Id; Typ : Entity_Id);
206   procedure Resolve_Null                      (N : Node_Id; Typ : Entity_Id);
207   procedure Resolve_Operator_Symbol           (N : Node_Id; Typ : Entity_Id);
208   procedure Resolve_Op_Concat                 (N : Node_Id; Typ : Entity_Id);
209   procedure Resolve_Op_Expon                  (N : Node_Id; Typ : Entity_Id);
210   procedure Resolve_Op_Not                    (N : Node_Id; Typ : Entity_Id);
211   procedure Resolve_Qualified_Expression      (N : Node_Id; Typ : Entity_Id);
212   procedure Resolve_Raise_Expression          (N : Node_Id; Typ : Entity_Id);
213   procedure Resolve_Range                     (N : Node_Id; Typ : Entity_Id);
214   procedure Resolve_Real_Literal              (N : Node_Id; Typ : Entity_Id);
215   procedure Resolve_Reference                 (N : Node_Id; Typ : Entity_Id);
216   procedure Resolve_Selected_Component        (N : Node_Id; Typ : Entity_Id);
217   procedure Resolve_Shift                     (N : Node_Id; Typ : Entity_Id);
218   procedure Resolve_Short_Circuit             (N : Node_Id; Typ : Entity_Id);
219   procedure Resolve_Slice                     (N : Node_Id; Typ : Entity_Id);
220   procedure Resolve_String_Literal            (N : Node_Id; Typ : Entity_Id);
221   procedure Resolve_Target_Name               (N : Node_Id; Typ : Entity_Id);
222   procedure Resolve_Type_Conversion           (N : Node_Id; Typ : Entity_Id);
223   procedure Resolve_Unary_Op                  (N : Node_Id; Typ : Entity_Id);
224   procedure Resolve_Unchecked_Expression      (N : Node_Id; Typ : Entity_Id);
225   procedure Resolve_Unchecked_Type_Conversion (N : Node_Id; Typ : Entity_Id);
226
227   function Operator_Kind
228     (Op_Name   : Name_Id;
229      Is_Binary : Boolean) return Node_Kind;
230   --  Utility to map the name of an operator into the corresponding Node. Used
231   --  by other node rewriting procedures.
232
233   procedure Resolve_Actuals (N : Node_Id; Nam : Entity_Id);
234   --  Resolve actuals of call, and add default expressions for missing ones.
235   --  N is the Node_Id for the subprogram call, and Nam is the entity of the
236   --  called subprogram.
237
238   procedure Resolve_Entry_Call (N : Node_Id; Typ : Entity_Id);
239   --  Called from Resolve_Call, when the prefix denotes an entry or element
240   --  of entry family. Actuals are resolved as for subprograms, and the node
241   --  is rebuilt as an entry call. Also called for protected operations. Typ
242   --  is the context type, which is used when the operation is a protected
243   --  function with no arguments, and the return value is indexed.
244
245   procedure Resolve_Implicit_Dereference (P : Node_Id);
246   --  Called when P is the prefix of an indexed component, or of a selected
247   --  component, or of a slice. If P is of an access type, we unconditionally
248   --  rewrite it as an explicit dereference. This ensures that the expander
249   --  and the code generator have a fully explicit tree to work with.
250
251   procedure Resolve_Intrinsic_Operator (N : Node_Id; Typ : Entity_Id);
252   --  A call to a user-defined intrinsic operator is rewritten as a call to
253   --  the corresponding predefined operator, with suitable conversions. Note
254   --  that this applies only for intrinsic operators that denote predefined
255   --  operators, not ones that are intrinsic imports of back-end builtins.
256
257   procedure Resolve_Intrinsic_Unary_Operator (N : Node_Id; Typ : Entity_Id);
258   --  Ditto, for arithmetic unary operators
259
260   procedure Rewrite_Operator_As_Call (N : Node_Id; Nam : Entity_Id);
261   --  If an operator node resolves to a call to a user-defined operator,
262   --  rewrite the node as a function call.
263
264   procedure Make_Call_Into_Operator
265     (N     : Node_Id;
266      Typ   : Entity_Id;
267      Op_Id : Entity_Id);
268   --  Inverse transformation: if an operator is given in functional notation,
269   --  then after resolving the node, transform into an operator node, so that
270   --  operands are resolved properly. Recall that predefined operators do not
271   --  have a full signature and special resolution rules apply.
272
273   procedure Rewrite_Renamed_Operator
274     (N   : Node_Id;
275      Op  : Entity_Id;
276      Typ : Entity_Id);
277   --  An operator can rename another, e.g. in an instantiation. In that
278   --  case, the proper operator node must be constructed and resolved.
279
280   procedure Set_String_Literal_Subtype (N : Node_Id; Typ : Entity_Id);
281   --  The String_Literal_Subtype is built for all strings that are not
282   --  operands of a static concatenation operation. If the argument is not
283   --  a N_String_Literal node, then the call has no effect.
284
285   procedure Set_Slice_Subtype (N : Node_Id);
286   --  Build subtype of array type, with the range specified by the slice
287
288   procedure Simplify_Type_Conversion (N : Node_Id);
289   --  Called after N has been resolved and evaluated, but before range checks
290   --  have been applied. This rewrites the conversion into a simpler form.
291
292   function Unique_Fixed_Point_Type (N : Node_Id) return Entity_Id;
293   --  A universal_fixed expression in an universal context is unambiguous if
294   --  there is only one applicable fixed point type. Determining whether there
295   --  is only one requires a search over all visible entities, and happens
296   --  only in very pathological cases (see 6115-006).
297
298   function Try_User_Defined_Literal
299     (N   : Node_Id;
300      Typ : Entity_Id) return Boolean;
301   --  If an operator node has a literal operand, check whether the type
302   --  of the context, or the type of the other operand has a user-defined
303   --  literal aspect that can be applied to the literal to resolve the node.
304   --  If such aspect exists, replace literal with a call to the
305   --  corresponing function and return True, return false otherwise.
306
307   -------------------------
308   -- Ambiguous_Character --
309   -------------------------
310
311   procedure Ambiguous_Character (C : Node_Id) is
312      E : Entity_Id;
313
314   begin
315      if Nkind (C) = N_Character_Literal then
316         Error_Msg_N ("ambiguous character literal", C);
317
318         --  First the ones in Standard
319
320         Error_Msg_N ("\\possible interpretation: Character!", C);
321         Error_Msg_N ("\\possible interpretation: Wide_Character!", C);
322
323         --  Include Wide_Wide_Character in Ada 2005 mode
324
325         if Ada_Version >= Ada_2005 then
326            Error_Msg_N ("\\possible interpretation: Wide_Wide_Character!", C);
327         end if;
328
329         --  Now any other types that match
330
331         E := Current_Entity (C);
332         while Present (E) loop
333            Error_Msg_NE ("\\possible interpretation:}!", C, Etype (E));
334            E := Homonym (E);
335         end loop;
336      end if;
337   end Ambiguous_Character;
338
339   -------------------------
340   -- Analyze_And_Resolve --
341   -------------------------
342
343   procedure Analyze_And_Resolve (N : Node_Id) is
344   begin
345      Analyze (N);
346      Resolve (N);
347   end Analyze_And_Resolve;
348
349   procedure Analyze_And_Resolve (N : Node_Id; Typ : Entity_Id) is
350   begin
351      Analyze (N);
352      Resolve (N, Typ);
353   end Analyze_And_Resolve;
354
355   --  Versions with check(s) suppressed
356
357   procedure Analyze_And_Resolve
358     (N        : Node_Id;
359      Typ      : Entity_Id;
360      Suppress : Check_Id)
361   is
362      Scop : constant Entity_Id := Current_Scope;
363
364   begin
365      if Suppress = All_Checks then
366         declare
367            Sva : constant Suppress_Array := Scope_Suppress.Suppress;
368         begin
369            Scope_Suppress.Suppress := (others => True);
370            Analyze_And_Resolve (N, Typ);
371            Scope_Suppress.Suppress := Sva;
372         end;
373
374      else
375         declare
376            Svg : constant Boolean := Scope_Suppress.Suppress (Suppress);
377         begin
378            Scope_Suppress.Suppress (Suppress) := True;
379            Analyze_And_Resolve (N, Typ);
380            Scope_Suppress.Suppress (Suppress) := Svg;
381         end;
382      end if;
383
384      if Current_Scope /= Scop
385        and then Scope_Is_Transient
386      then
387         --  This can only happen if a transient scope was created for an inner
388         --  expression, which will be removed upon completion of the analysis
389         --  of an enclosing construct. The transient scope must have the
390         --  suppress status of the enclosing environment, not of this Analyze
391         --  call.
392
393         Scope_Stack.Table (Scope_Stack.Last).Save_Scope_Suppress :=
394           Scope_Suppress;
395      end if;
396   end Analyze_And_Resolve;
397
398   procedure Analyze_And_Resolve
399     (N        : Node_Id;
400      Suppress : Check_Id)
401   is
402      Scop : constant Entity_Id := Current_Scope;
403
404   begin
405      if Suppress = All_Checks then
406         declare
407            Sva : constant Suppress_Array := Scope_Suppress.Suppress;
408         begin
409            Scope_Suppress.Suppress := (others => True);
410            Analyze_And_Resolve (N);
411            Scope_Suppress.Suppress := Sva;
412         end;
413
414      else
415         declare
416            Svg : constant Boolean := Scope_Suppress.Suppress (Suppress);
417         begin
418            Scope_Suppress.Suppress (Suppress) := True;
419            Analyze_And_Resolve (N);
420            Scope_Suppress.Suppress (Suppress) := Svg;
421         end;
422      end if;
423
424      if Current_Scope /= Scop and then Scope_Is_Transient then
425         Scope_Stack.Table (Scope_Stack.Last).Save_Scope_Suppress :=
426           Scope_Suppress;
427      end if;
428   end Analyze_And_Resolve;
429
430   -------------------------------------
431   -- Has_Applicable_User_Defined_Literal --
432   -------------------------------------
433
434   function Has_Applicable_User_Defined_Literal
435     (N   : Node_Id;
436      Typ : Entity_Id) return Boolean
437   is
438      Loc  : constant Source_Ptr := Sloc (N);
439      Literal_Aspect_Map :
440        constant array (N_Numeric_Or_String_Literal) of Aspect_Id :=
441          (N_Integer_Literal => Aspect_Integer_Literal,
442           N_Real_Literal    => Aspect_Real_Literal,
443           N_String_Literal  => Aspect_String_Literal);
444
445      Named_Number_Aspect_Map : constant array (Named_Kind) of Aspect_Id :=
446        (E_Named_Integer => Aspect_Integer_Literal,
447         E_Named_Real    => Aspect_Real_Literal);
448
449      Lit_Aspect : Aspect_Id;
450
451      Callee : Entity_Id;
452      Name   : Node_Id;
453      Param1 : Node_Id;
454      Param2 : Node_Id;
455      Params : List_Id;
456      Call   : Node_Id;
457      Expr   : Node_Id;
458
459   begin
460      if (Nkind (N) in N_Numeric_Or_String_Literal
461           and then Present
462            (Find_Aspect (Typ, Literal_Aspect_Map (Nkind (N)))))
463        or else
464          (Nkind (N) = N_Identifier
465            and then Is_Named_Number (Entity (N))
466            and then
467              Present
468                (Find_Aspect
469                  (Typ, Named_Number_Aspect_Map (Ekind (Entity (N))))))
470      then
471         Lit_Aspect :=
472           (if Nkind (N) = N_Identifier
473            then Named_Number_Aspect_Map (Ekind (Entity (N)))
474            else Literal_Aspect_Map (Nkind (N)));
475         Callee :=
476           Entity (Expression (Find_Aspect (Typ, Lit_Aspect)));
477         Name := Make_Identifier (Loc, Chars (Callee));
478
479         if Is_Derived_Type (Typ)
480           and then Is_Tagged_Type (Typ)
481           and then Base_Type (Etype (Callee)) /= Base_Type (Typ)
482         then
483            Callee :=
484              Corresponding_Primitive_Op
485                (Ancestor_Op     => Callee,
486                 Descendant_Type => Base_Type (Typ));
487         end if;
488
489         --  Handle an identifier that denotes a named number.
490
491         if Nkind (N) = N_Identifier then
492            Expr := Expression (Declaration_Node (Entity (N)));
493
494            if Ekind (Entity (N)) = E_Named_Integer then
495               UI_Image (Expr_Value (Expr), Decimal);
496               Start_String;
497               Store_String_Chars
498                 (UI_Image_Buffer (1 .. UI_Image_Length));
499               Param1 := Make_String_Literal (Loc, End_String);
500               Params := New_List (Param1);
501
502            else
503               UI_Image (Norm_Num (Expr_Value_R (Expr)), Decimal);
504               Start_String;
505
506               if UR_Is_Negative (Expr_Value_R (Expr)) then
507                  Store_String_Chars ("-");
508               end if;
509
510               Store_String_Chars
511                 (UI_Image_Buffer (1 .. UI_Image_Length));
512               Param1 := Make_String_Literal (Loc, End_String);
513
514               --  Note: Set_Etype is called below on Param1
515
516               UI_Image (Norm_Den (Expr_Value_R (Expr)), Decimal);
517               Start_String;
518               Store_String_Chars
519                 (UI_Image_Buffer (1 .. UI_Image_Length));
520               Param2 := Make_String_Literal (Loc, End_String);
521               Set_Etype (Param2, Standard_String);
522
523               Params := New_List (Param1, Param2);
524
525               if Present (Related_Expression (Callee)) then
526                  Callee := Related_Expression (Callee);
527               else
528                  Error_Msg_NE
529                    ("cannot resolve & for a named real", N, Callee);
530                  return False;
531               end if;
532            end if;
533
534         elsif Nkind (N) = N_String_Literal then
535            Param1 := Make_String_Literal (Loc, Strval (N));
536            Params := New_List (Param1);
537
538         else
539            Param1 :=
540              Make_String_Literal
541                (Loc, String_From_Numeric_Literal (N));
542            Params := New_List (Param1);
543         end if;
544
545         Call :=
546           Make_Function_Call
547             (Sloc                   => Loc,
548              Name                   => Name,
549              Parameter_Associations => Params);
550
551         Set_Entity (Name, Callee);
552         Set_Is_Overloaded (Name, False);
553
554         if Lit_Aspect = Aspect_String_Literal then
555            Set_Etype (Param1, Standard_Wide_Wide_String);
556         else
557            Set_Etype (Param1, Standard_String);
558         end if;
559
560         Set_Etype (Call, Etype (Callee));
561
562         if Base_Type (Etype (Call)) /= Base_Type (Typ) then
563            --  Conversion may be needed in case of an inherited
564            --  aspect of a derived type. For a null extension, we
565            --  use a null extension aggregate instead because the
566            --  downward type conversion would be illegal.
567
568            if Is_Null_Extension_Of
569                 (Descendant => Typ,
570                  Ancestor   => Etype (Call))
571            then
572               Call := Make_Extension_Aggregate (Loc,
573                         Ancestor_Part       => Call,
574                         Null_Record_Present => True);
575            else
576               Call := Convert_To (Typ, Call);
577            end if;
578         end if;
579
580         Rewrite (N, Call);
581
582         Analyze_And_Resolve (N, Typ);
583         return True;
584      else
585         return False;
586      end if;
587   end Has_Applicable_User_Defined_Literal;
588
589   ----------------------------
590   -- Check_Discriminant_Use --
591   ----------------------------
592
593   procedure Check_Discriminant_Use (N : Node_Id) is
594      PN   : constant Node_Id   := Parent (N);
595      Disc : constant Entity_Id := Entity (N);
596      P    : Node_Id;
597      D    : Node_Id;
598
599   begin
600      --  Any use in a spec-expression is legal
601
602      if In_Spec_Expression then
603         null;
604
605      elsif Nkind (PN) = N_Range then
606
607         --  Discriminant cannot be used to constrain a scalar type
608
609         P := Parent (PN);
610
611         if Nkind (P) = N_Range_Constraint
612           and then Nkind (Parent (P)) = N_Subtype_Indication
613           and then Nkind (Parent (Parent (P))) = N_Component_Definition
614         then
615            Error_Msg_N ("discriminant cannot constrain scalar type", N);
616
617         elsif Nkind (P) = N_Index_Or_Discriminant_Constraint then
618
619            --  The following check catches the unusual case where a
620            --  discriminant appears within an index constraint that is part
621            --  of a larger expression within a constraint on a component,
622            --  e.g. "C : Int range 1 .. F (new A(1 .. D))". For now we only
623            --  check case of record components, and note that a similar check
624            --  should also apply in the case of discriminant constraints
625            --  below. ???
626
627            --  Note that the check for N_Subtype_Declaration below is to
628            --  detect the valid use of discriminants in the constraints of a
629            --  subtype declaration when this subtype declaration appears
630            --  inside the scope of a record type (which is syntactically
631            --  illegal, but which may be created as part of derived type
632            --  processing for records). See Sem_Ch3.Build_Derived_Record_Type
633            --  for more info.
634
635            if Ekind (Current_Scope) = E_Record_Type
636              and then Scope (Disc) = Current_Scope
637              and then not
638                (Nkind (Parent (P)) = N_Subtype_Indication
639                  and then
640                    Nkind (Parent (Parent (P))) in N_Component_Definition
641                                                 | N_Subtype_Declaration
642                  and then Paren_Count (N) = 0)
643            then
644               Error_Msg_N
645                 ("discriminant must appear alone in component constraint", N);
646               return;
647            end if;
648
649            --   Detect a common error:
650
651            --   type R (D : Positive := 100) is record
652            --     Name : String (1 .. D);
653            --   end record;
654
655            --  The default value causes an object of type R to be allocated
656            --  with room for Positive'Last characters. The RM does not mandate
657            --  the allocation of the maximum size, but that is what GNAT does
658            --  so we should warn the programmer that there is a problem.
659
660            Check_Large : declare
661               SI : Node_Id;
662               T  : Entity_Id;
663               TB : Node_Id;
664               CB : Entity_Id;
665
666               function Large_Storage_Type (T : Entity_Id) return Boolean;
667               --  Return True if type T has a large enough range that any
668               --  array whose index type covered the whole range of the type
669               --  would likely raise Storage_Error.
670
671               ------------------------
672               -- Large_Storage_Type --
673               ------------------------
674
675               function Large_Storage_Type (T : Entity_Id) return Boolean is
676               begin
677                  --  The type is considered large if its bounds are known at
678                  --  compile time and if it requires at least as many bits as
679                  --  a Positive to store the possible values.
680
681                  return Compile_Time_Known_Value (Type_Low_Bound (T))
682                    and then Compile_Time_Known_Value (Type_High_Bound (T))
683                    and then
684                      Minimum_Size (T, Biased => True) >=
685                        RM_Size (Standard_Positive);
686               end Large_Storage_Type;
687
688            --  Start of processing for Check_Large
689
690            begin
691               --  Check that the Disc has a large range
692
693               if not Large_Storage_Type (Etype (Disc)) then
694                  goto No_Danger;
695               end if;
696
697               --  If the enclosing type is limited, we allocate only the
698               --  default value, not the maximum, and there is no need for
699               --  a warning.
700
701               if Is_Limited_Type (Scope (Disc)) then
702                  goto No_Danger;
703               end if;
704
705               --  Check that it is the high bound
706
707               if N /= High_Bound (PN)
708                 or else No (Discriminant_Default_Value (Disc))
709               then
710                  goto No_Danger;
711               end if;
712
713               --  Check the array allows a large range at this bound. First
714               --  find the array
715
716               SI := Parent (P);
717
718               if Nkind (SI) /= N_Subtype_Indication then
719                  goto No_Danger;
720               end if;
721
722               T := Entity (Subtype_Mark (SI));
723
724               if not Is_Array_Type (T) then
725                  goto No_Danger;
726               end if;
727
728               --  Next, find the dimension
729
730               TB := First_Index (T);
731               CB := First (Constraints (P));
732               while True
733                 and then Present (TB)
734                 and then Present (CB)
735                 and then CB /= PN
736               loop
737                  Next_Index (TB);
738                  Next (CB);
739               end loop;
740
741               if CB /= PN then
742                  goto No_Danger;
743               end if;
744
745               --  Now, check the dimension has a large range
746
747               if not Large_Storage_Type (Etype (TB)) then
748                  goto No_Danger;
749               end if;
750
751               --  Warn about the danger
752
753               Error_Msg_N
754                 ("??creation of & object may raise Storage_Error!",
755                  Scope (Disc));
756
757               <<No_Danger>>
758                  null;
759
760            end Check_Large;
761         end if;
762
763      --  Legal case is in index or discriminant constraint
764
765      elsif Nkind (PN) in N_Index_Or_Discriminant_Constraint
766                        | N_Discriminant_Association
767      then
768         if Paren_Count (N) > 0 then
769            Error_Msg_N
770              ("discriminant in constraint must appear alone",  N);
771
772         elsif Nkind (N) = N_Expanded_Name
773           and then Comes_From_Source (N)
774         then
775            Error_Msg_N
776              ("discriminant must appear alone as a direct name", N);
777         end if;
778
779         return;
780
781      --  Otherwise, context is an expression. It should not be within (i.e. a
782      --  subexpression of) a constraint for a component.
783
784      else
785         D := PN;
786         P := Parent (PN);
787         while Nkind (P) not in
788           N_Component_Declaration | N_Subtype_Indication | N_Entry_Declaration
789         loop
790            D := P;
791            P := Parent (P);
792            exit when No (P);
793         end loop;
794
795         --  If the discriminant is used in an expression that is a bound of a
796         --  scalar type, an Itype is created and the bounds are attached to
797         --  its range, not to the original subtype indication. Such use is of
798         --  course a double fault.
799
800         if (Nkind (P) = N_Subtype_Indication
801              and then Nkind (Parent (P)) in N_Component_Definition
802                                           | N_Derived_Type_Definition
803              and then D = Constraint (P))
804
805           --  The constraint itself may be given by a subtype indication,
806           --  rather than by a more common discrete range.
807
808           or else (Nkind (P) = N_Subtype_Indication
809                      and then
810                    Nkind (Parent (P)) = N_Index_Or_Discriminant_Constraint)
811           or else Nkind (P) = N_Entry_Declaration
812           or else Nkind (D) = N_Defining_Identifier
813         then
814            Error_Msg_N
815              ("discriminant in constraint must appear alone",  N);
816         end if;
817      end if;
818   end Check_Discriminant_Use;
819
820   --------------------------------
821   -- Check_For_Visible_Operator --
822   --------------------------------
823
824   procedure Check_For_Visible_Operator (N : Node_Id; T : Entity_Id) is
825   begin
826      if Is_Invisible_Operator (N, T) then
827         Error_Msg_NE -- CODEFIX
828           ("operator for} is not directly visible!", N, First_Subtype (T));
829         Error_Msg_N -- CODEFIX
830           ("use clause would make operation legal!", N);
831      end if;
832   end Check_For_Visible_Operator;
833
834   ---------------------------------
835   -- Check_Fully_Declared_Prefix --
836   ---------------------------------
837
838   procedure Check_Fully_Declared_Prefix
839     (Typ  : Entity_Id;
840      Pref : Node_Id)
841   is
842   begin
843      --  Check that the designated type of the prefix of a dereference is
844      --  not an incomplete type. This cannot be done unconditionally, because
845      --  dereferences of private types are legal in default expressions. This
846      --  case is taken care of in Check_Fully_Declared, called below. There
847      --  are also 2005 cases where it is legal for the prefix to be unfrozen.
848
849      --  This consideration also applies to similar checks for allocators,
850      --  qualified expressions, and type conversions.
851
852      --  An additional exception concerns other per-object expressions that
853      --  are not directly related to component declarations, in particular
854      --  representation pragmas for tasks. These will be per-object
855      --  expressions if they depend on discriminants or some global entity.
856      --  If the task has access discriminants, the designated type may be
857      --  incomplete at the point the expression is resolved. This resolution
858      --  takes place within the body of the initialization procedure, where
859      --  the discriminant is replaced by its discriminal.
860
861      if Is_Entity_Name (Pref)
862        and then Ekind (Entity (Pref)) = E_In_Parameter
863      then
864         null;
865
866      --  Ada 2005 (AI-326): Tagged incomplete types allowed. The wrong usages
867      --  are handled by Analyze_Access_Attribute, Analyze_Assignment,
868      --  Analyze_Object_Renaming, and Freeze_Entity.
869
870      elsif Ada_Version >= Ada_2005
871        and then Is_Entity_Name (Pref)
872        and then Is_Access_Type (Etype (Pref))
873        and then Ekind (Directly_Designated_Type (Etype (Pref))) =
874                                                       E_Incomplete_Type
875        and then Is_Tagged_Type (Directly_Designated_Type (Etype (Pref)))
876      then
877         null;
878      else
879         Check_Fully_Declared (Typ, Parent (Pref));
880      end if;
881   end Check_Fully_Declared_Prefix;
882
883   ------------------------------
884   -- Check_Infinite_Recursion --
885   ------------------------------
886
887   function Check_Infinite_Recursion (Call : Node_Id) return Boolean is
888      function Enclosing_Declaration_Or_Statement (N : Node_Id) return Node_Id;
889      --  Return the nearest enclosing declaration or statement that houses
890      --  arbitrary node N.
891
892      function Invoked_With_Different_Arguments (N : Node_Id) return Boolean;
893      --  Determine whether call N invokes the related enclosing subprogram
894      --  with actuals that differ from the subprogram's formals.
895
896      function Is_Conditional_Statement (N : Node_Id) return Boolean;
897      --  Determine whether arbitrary node N denotes a conditional construct
898
899      function Is_Control_Flow_Statement (N : Node_Id) return Boolean;
900      --  Determine whether arbitrary node N denotes a control flow statement
901      --  or a construct that may contains such a statement.
902
903      function Is_Immediately_Within_Body (N : Node_Id) return Boolean;
904      --  Determine whether arbitrary node N appears immediately within the
905      --  statements of an entry or subprogram body.
906
907      function Is_Raise_Idiom (N : Node_Id) return Boolean;
908      --  Determine whether arbitrary node N appears immediately within the
909      --  body of an entry or subprogram, and is preceded by a single raise
910      --  statement.
911
912      function Is_Raise_Statement (N : Node_Id) return Boolean;
913      --  Determine whether arbitrary node N denotes a raise statement
914
915      function Is_Sole_Statement (N : Node_Id) return Boolean;
916      --  Determine whether arbitrary node N is the sole source statement in
917      --  the body of the enclosing subprogram.
918
919      function Preceded_By_Control_Flow_Statement (N : Node_Id) return Boolean;
920      --  Determine whether arbitrary node N is preceded by a control flow
921      --  statement.
922
923      function Within_Conditional_Statement (N : Node_Id) return Boolean;
924      --  Determine whether arbitrary node N appears within a conditional
925      --  construct.
926
927      ----------------------------------------
928      -- Enclosing_Declaration_Or_Statement --
929      ----------------------------------------
930
931      function Enclosing_Declaration_Or_Statement
932        (N : Node_Id) return Node_Id
933      is
934         Par : Node_Id;
935
936      begin
937         Par := N;
938         while Present (Par) loop
939            if Is_Declaration (Par) or else Is_Statement (Par) then
940               return Par;
941
942            --  Prevent the search from going too far
943
944            elsif Is_Body_Or_Package_Declaration (Par) then
945               exit;
946            end if;
947
948            Par := Parent (Par);
949         end loop;
950
951         return N;
952      end Enclosing_Declaration_Or_Statement;
953
954      --------------------------------------
955      -- Invoked_With_Different_Arguments --
956      --------------------------------------
957
958      function Invoked_With_Different_Arguments (N : Node_Id) return Boolean is
959         Subp : constant Entity_Id := Entity (Name (N));
960
961         Actual : Node_Id;
962         Formal : Entity_Id;
963
964      begin
965         --  Determine whether the formals of the invoked subprogram are not
966         --  used as actuals in the call.
967
968         Actual := First_Actual (Call);
969         Formal := First_Formal (Subp);
970         while Present (Actual) and then Present (Formal) loop
971
972            --  The current actual does not match the current formal
973
974            if not (Is_Entity_Name (Actual)
975                     and then Entity (Actual) = Formal)
976            then
977               return True;
978            end if;
979
980            Next_Actual (Actual);
981            Next_Formal (Formal);
982         end loop;
983
984         return False;
985      end Invoked_With_Different_Arguments;
986
987      ------------------------------
988      -- Is_Conditional_Statement --
989      ------------------------------
990
991      function Is_Conditional_Statement (N : Node_Id) return Boolean is
992      begin
993         return
994           Nkind (N) in N_And_Then
995                      | N_Case_Expression
996                      | N_Case_Statement
997                      | N_If_Expression
998                      | N_If_Statement
999                      | N_Or_Else;
1000      end Is_Conditional_Statement;
1001
1002      -------------------------------
1003      -- Is_Control_Flow_Statement --
1004      -------------------------------
1005
1006      function Is_Control_Flow_Statement (N : Node_Id) return Boolean is
1007      begin
1008         --  It is assumed that all statements may affect the control flow in
1009         --  some way. A raise statement may be expanded into a non-statement
1010         --  node.
1011
1012         return Is_Statement (N) or else Is_Raise_Statement (N);
1013      end Is_Control_Flow_Statement;
1014
1015      --------------------------------
1016      -- Is_Immediately_Within_Body --
1017      --------------------------------
1018
1019      function Is_Immediately_Within_Body (N : Node_Id) return Boolean is
1020         HSS : constant Node_Id := Parent (N);
1021
1022      begin
1023         return
1024           Nkind (HSS) = N_Handled_Sequence_Of_Statements
1025             and then Nkind (Parent (HSS)) in N_Entry_Body | N_Subprogram_Body
1026             and then Is_List_Member (N)
1027             and then List_Containing (N) = Statements (HSS);
1028      end Is_Immediately_Within_Body;
1029
1030      --------------------
1031      -- Is_Raise_Idiom --
1032      --------------------
1033
1034      function Is_Raise_Idiom (N : Node_Id) return Boolean is
1035         Raise_Stmt : Node_Id;
1036         Stmt       : Node_Id;
1037
1038      begin
1039         if Is_Immediately_Within_Body (N) then
1040
1041            --  Assume that no raise statement has been seen yet
1042
1043            Raise_Stmt := Empty;
1044
1045            --  Examine the statements preceding the input node, skipping
1046            --  internally-generated constructs.
1047
1048            Stmt := Prev (N);
1049            while Present (Stmt) loop
1050
1051               --  Multiple raise statements violate the idiom
1052
1053               if Is_Raise_Statement (Stmt) then
1054                  if Present (Raise_Stmt) then
1055                     return False;
1056                  end if;
1057
1058                  Raise_Stmt := Stmt;
1059
1060               elsif Comes_From_Source (Stmt) then
1061                  exit;
1062               end if;
1063
1064               Stmt := Prev (Stmt);
1065            end loop;
1066
1067            --  At this point the node must be preceded by a raise statement,
1068            --  and the raise statement has to be the sole statement within
1069            --  the enclosing entry or subprogram body.
1070
1071            return
1072              Present (Raise_Stmt) and then Is_Sole_Statement (Raise_Stmt);
1073         end if;
1074
1075         return False;
1076      end Is_Raise_Idiom;
1077
1078      ------------------------
1079      -- Is_Raise_Statement --
1080      ------------------------
1081
1082      function Is_Raise_Statement (N : Node_Id) return Boolean is
1083      begin
1084         --  A raise statement may be transfomed into a Raise_xxx_Error node
1085
1086         return
1087           Nkind (N) = N_Raise_Statement
1088             or else Nkind (N) in N_Raise_xxx_Error;
1089      end Is_Raise_Statement;
1090
1091      -----------------------
1092      -- Is_Sole_Statement --
1093      -----------------------
1094
1095      function Is_Sole_Statement (N : Node_Id) return Boolean is
1096         Stmt : Node_Id;
1097
1098      begin
1099         --  The input node appears within the statements of an entry or
1100         --  subprogram body. Examine the statements preceding the node.
1101
1102         if Is_Immediately_Within_Body (N) then
1103            Stmt := Prev (N);
1104
1105            while Present (Stmt) loop
1106
1107               --  The statement is preceded by another statement or a source
1108               --  construct. This indicates that the node does not appear by
1109               --  itself.
1110
1111               if Is_Control_Flow_Statement (Stmt)
1112                 or else Comes_From_Source (Stmt)
1113               then
1114                  return False;
1115               end if;
1116
1117               Stmt := Prev (Stmt);
1118            end loop;
1119
1120            return True;
1121         end if;
1122
1123         --  The input node is within a construct nested inside the entry or
1124         --  subprogram body.
1125
1126         return False;
1127      end Is_Sole_Statement;
1128
1129      ----------------------------------------
1130      -- Preceded_By_Control_Flow_Statement --
1131      ----------------------------------------
1132
1133      function Preceded_By_Control_Flow_Statement
1134        (N : Node_Id) return Boolean
1135      is
1136         Stmt : Node_Id;
1137
1138      begin
1139         if Is_List_Member (N) then
1140            Stmt := Prev (N);
1141
1142            --  Examine the statements preceding the input node
1143
1144            while Present (Stmt) loop
1145               if Is_Control_Flow_Statement (Stmt) then
1146                  return True;
1147               end if;
1148
1149               Stmt := Prev (Stmt);
1150            end loop;
1151
1152            return False;
1153         end if;
1154
1155         --  Assume that the node is part of some control flow statement
1156
1157         return True;
1158      end Preceded_By_Control_Flow_Statement;
1159
1160      ----------------------------------
1161      -- Within_Conditional_Statement --
1162      ----------------------------------
1163
1164      function Within_Conditional_Statement (N : Node_Id) return Boolean is
1165         Stmt : Node_Id;
1166
1167      begin
1168         Stmt := Parent (N);
1169         while Present (Stmt) loop
1170            if Is_Conditional_Statement (Stmt) then
1171               return True;
1172
1173            --  Prevent the search from going too far
1174
1175            elsif Is_Body_Or_Package_Declaration (Stmt) then
1176               exit;
1177            end if;
1178
1179            Stmt := Parent (Stmt);
1180         end loop;
1181
1182         return False;
1183      end Within_Conditional_Statement;
1184
1185      --  Local variables
1186
1187      Call_Context : constant Node_Id :=
1188                       Enclosing_Declaration_Or_Statement (Call);
1189
1190   --  Start of processing for Check_Infinite_Recursion
1191
1192   begin
1193      --  The call is assumed to be safe when the enclosing subprogram is
1194      --  invoked with actuals other than its formals.
1195      --
1196      --    procedure Proc (F1 : ...; F2 : ...; ...; FN : ...) is
1197      --    begin
1198      --       ...
1199      --       Proc (A1, A2, ..., AN);
1200      --       ...
1201      --    end Proc;
1202
1203      if Invoked_With_Different_Arguments (Call) then
1204         return False;
1205
1206      --  The call is assumed to be safe when the invocation of the enclosing
1207      --  subprogram depends on a conditional statement.
1208      --
1209      --    procedure Proc (F1 : ...; F2 : ...; ...; FN : ...) is
1210      --    begin
1211      --       ...
1212      --       if Some_Condition then
1213      --          Proc (F1, F2, ..., FN);
1214      --       end if;
1215      --       ...
1216      --    end Proc;
1217
1218      elsif Within_Conditional_Statement (Call) then
1219         return False;
1220
1221      --  The context of the call is assumed to be safe when the invocation of
1222      --  the enclosing subprogram is preceded by some control flow statement.
1223      --
1224      --    procedure Proc (F1 : ...; F2 : ...; ...; FN : ...) is
1225      --    begin
1226      --       ...
1227      --       if Some_Condition then
1228      --          ...
1229      --       end if;
1230      --       ...
1231      --       Proc (F1, F2, ..., FN);
1232      --       ...
1233      --    end Proc;
1234
1235      elsif Preceded_By_Control_Flow_Statement (Call_Context) then
1236         return False;
1237
1238      --  Detect an idiom where the context of the call is preceded by a single
1239      --  raise statement.
1240      --
1241      --    procedure Proc (F1 : ...; F2 : ...; ...; FN : ...) is
1242      --    begin
1243      --       raise ...;
1244      --       Proc (F1, F2, ..., FN);
1245      --    end Proc;
1246
1247      elsif Is_Raise_Idiom (Call_Context) then
1248         return False;
1249      end if;
1250
1251      --  At this point it is certain that infinite recursion will take place
1252      --  as long as the call is executed. Detect a case where the context of
1253      --  the call is the sole source statement within the subprogram body.
1254      --
1255      --    procedure Proc (F1 : ...; F2 : ...; ...; FN : ...) is
1256      --    begin
1257      --       Proc (F1, F2, ..., FN);
1258      --    end Proc;
1259      --
1260      --  Install an explicit raise to prevent the infinite recursion.
1261
1262      if Is_Sole_Statement (Call_Context) then
1263         Error_Msg_Warn := SPARK_Mode /= On;
1264         Error_Msg_N ("!infinite recursion<<", Call);
1265         Error_Msg_N ("\!Storage_Error [<<", Call);
1266
1267         Insert_Action (Call,
1268           Make_Raise_Storage_Error (Sloc (Call),
1269             Reason => SE_Infinite_Recursion));
1270
1271      --  Otherwise infinite recursion could take place, considering other flow
1272      --  control constructs such as gotos, exit statements, etc.
1273
1274      else
1275         Error_Msg_Warn := SPARK_Mode /= On;
1276         Error_Msg_N ("!possible infinite recursion<<", Call);
1277         Error_Msg_N ("\!??Storage_Error ]<<", Call);
1278      end if;
1279
1280      return True;
1281   end Check_Infinite_Recursion;
1282
1283   ---------------------------------------
1284   -- Check_No_Direct_Boolean_Operators --
1285   ---------------------------------------
1286
1287   procedure Check_No_Direct_Boolean_Operators (N : Node_Id) is
1288   begin
1289      if Scope (Entity (N)) = Standard_Standard
1290        and then Root_Type (Etype (Left_Opnd (N))) = Standard_Boolean
1291      then
1292         --  Restriction only applies to original source code
1293
1294         if Comes_From_Source (N) then
1295            Check_Restriction (No_Direct_Boolean_Operators, N);
1296         end if;
1297      end if;
1298
1299      --  Do style check (but skip if in instance, error is on template)
1300
1301      if Style_Check then
1302         if not In_Instance then
1303            Check_Boolean_Operator (N);
1304         end if;
1305      end if;
1306   end Check_No_Direct_Boolean_Operators;
1307
1308   ------------------------------
1309   -- Check_Parameterless_Call --
1310   ------------------------------
1311
1312   procedure Check_Parameterless_Call (N : Node_Id) is
1313      Nam : Node_Id;
1314
1315      function Prefix_Is_Access_Subp return Boolean;
1316      --  If the prefix is of an access_to_subprogram type, the node must be
1317      --  rewritten as a call. Ditto if the prefix is overloaded and all its
1318      --  interpretations are access to subprograms.
1319
1320      ---------------------------
1321      -- Prefix_Is_Access_Subp --
1322      ---------------------------
1323
1324      function Prefix_Is_Access_Subp return Boolean is
1325         I   : Interp_Index;
1326         It  : Interp;
1327
1328      begin
1329         --  If the context is an attribute reference that can apply to
1330         --  functions, this is never a parameterless call (RM 4.1.4(6)).
1331
1332         if Nkind (Parent (N)) = N_Attribute_Reference
1333            and then Attribute_Name (Parent (N))
1334                       in Name_Address | Name_Code_Address | Name_Access
1335         then
1336            return False;
1337         end if;
1338
1339         if not Is_Overloaded (N) then
1340            return
1341              Ekind (Etype (N)) = E_Subprogram_Type
1342                and then Base_Type (Etype (Etype (N))) /= Standard_Void_Type;
1343         else
1344            Get_First_Interp (N, I, It);
1345            while Present (It.Typ) loop
1346               if Ekind (It.Typ) /= E_Subprogram_Type
1347                 or else Base_Type (Etype (It.Typ)) = Standard_Void_Type
1348               then
1349                  return False;
1350               end if;
1351
1352               Get_Next_Interp (I, It);
1353            end loop;
1354
1355            return True;
1356         end if;
1357      end Prefix_Is_Access_Subp;
1358
1359   --  Start of processing for Check_Parameterless_Call
1360
1361   begin
1362      --  Defend against junk stuff if errors already detected
1363
1364      if Total_Errors_Detected /= 0 then
1365         if Nkind (N) in N_Has_Etype and then Etype (N) = Any_Type then
1366            return;
1367         elsif Nkind (N) in N_Has_Chars
1368           and then not Is_Valid_Name (Chars (N))
1369         then
1370            return;
1371         end if;
1372
1373         Require_Entity (N);
1374      end if;
1375
1376      --  If the context expects a value, and the name is a procedure, this is
1377      --  most likely a missing 'Access. Don't try to resolve the parameterless
1378      --  call, error will be caught when the outer call is analyzed.
1379
1380      if Is_Entity_Name (N)
1381        and then Ekind (Entity (N)) = E_Procedure
1382        and then not Is_Overloaded (N)
1383        and then
1384         Nkind (Parent (N)) in N_Parameter_Association
1385                             | N_Function_Call
1386                             | N_Procedure_Call_Statement
1387      then
1388         return;
1389      end if;
1390
1391      --  Rewrite as call if overloadable entity that is (or could be, in the
1392      --  overloaded case) a function call. If we know for sure that the entity
1393      --  is an enumeration literal, we do not rewrite it.
1394
1395      --  If the entity is the name of an operator, it cannot be a call because
1396      --  operators cannot have default parameters. In this case, this must be
1397      --  a string whose contents coincide with an operator name. Set the kind
1398      --  of the node appropriately.
1399
1400      if (Is_Entity_Name (N)
1401            and then Nkind (N) /= N_Operator_Symbol
1402            and then Is_Overloadable (Entity (N))
1403            and then (Ekind (Entity (N)) /= E_Enumeration_Literal
1404                       or else Is_Overloaded (N)))
1405
1406      --  Rewrite as call if it is an explicit dereference of an expression of
1407      --  a subprogram access type, and the subprogram type is not that of a
1408      --  procedure or entry.
1409
1410      or else
1411        (Nkind (N) = N_Explicit_Dereference and then Prefix_Is_Access_Subp)
1412
1413      --  Rewrite as call if it is a selected component which is a function,
1414      --  this is the case of a call to a protected function (which may be
1415      --  overloaded with other protected operations).
1416
1417      or else
1418        (Nkind (N) = N_Selected_Component
1419          and then (Ekind (Entity (Selector_Name (N))) = E_Function
1420                     or else
1421                       (Ekind (Entity (Selector_Name (N))) in
1422                          E_Entry | E_Procedure
1423                         and then Is_Overloaded (Selector_Name (N)))))
1424
1425      --  If one of the above three conditions is met, rewrite as call. Apply
1426      --  the rewriting only once.
1427
1428      then
1429         if Nkind (Parent (N)) /= N_Function_Call
1430           or else N /= Name (Parent (N))
1431         then
1432
1433            --  This may be a prefixed call that was not fully analyzed, e.g.
1434            --  an actual in an instance.
1435
1436            if Ada_Version >= Ada_2005
1437              and then Nkind (N) = N_Selected_Component
1438              and then Is_Dispatching_Operation (Entity (Selector_Name (N)))
1439            then
1440               Analyze_Selected_Component (N);
1441
1442               if Nkind (N) /= N_Selected_Component then
1443                  return;
1444               end if;
1445            end if;
1446
1447            --  The node is the name of the parameterless call. Preserve its
1448            --  descendants, which may be complex expressions.
1449
1450            Nam := Relocate_Node (N);
1451
1452            --  If overloaded, overload set belongs to new copy
1453
1454            Save_Interps (N, Nam);
1455
1456            --  Change node to parameterless function call (note that the
1457            --  Parameter_Associations associations field is left set to Empty,
1458            --  its normal default value since there are no parameters)
1459
1460            Change_Node (N, N_Function_Call);
1461            Set_Name (N, Nam);
1462            Set_Sloc (N, Sloc (Nam));
1463            Analyze_Call (N);
1464         end if;
1465
1466      elsif Nkind (N) = N_Parameter_Association then
1467         Check_Parameterless_Call (Explicit_Actual_Parameter (N));
1468
1469      elsif Nkind (N) = N_Operator_Symbol then
1470         Set_Etype (N, Empty);
1471         Set_Entity (N, Empty);
1472         Set_Is_Overloaded (N, False);
1473         Change_Operator_Symbol_To_String_Literal (N);
1474         Set_Etype (N, Any_String);
1475      end if;
1476   end Check_Parameterless_Call;
1477
1478   --------------------------------
1479   -- Is_Atomic_Ref_With_Address --
1480   --------------------------------
1481
1482   function Is_Atomic_Ref_With_Address (N : Node_Id) return Boolean is
1483      Pref : constant Node_Id := Prefix (N);
1484
1485   begin
1486      if not Is_Entity_Name (Pref) then
1487         return False;
1488
1489      else
1490         declare
1491            Pent : constant Entity_Id := Entity (Pref);
1492            Ptyp : constant Entity_Id := Etype (Pent);
1493         begin
1494            return not Is_Access_Type (Ptyp)
1495              and then (Is_Atomic (Ptyp) or else Is_Atomic (Pent))
1496              and then Present (Address_Clause (Pent));
1497         end;
1498      end if;
1499   end Is_Atomic_Ref_With_Address;
1500
1501   -----------------------------
1502   -- Is_Definite_Access_Type --
1503   -----------------------------
1504
1505   function Is_Definite_Access_Type (E : Entity_Id) return Boolean is
1506      Btyp : constant Entity_Id := Base_Type (E);
1507   begin
1508      return Ekind (Btyp) = E_Access_Type
1509        or else (Ekind (Btyp) = E_Access_Subprogram_Type
1510                  and then Comes_From_Source (Btyp));
1511   end Is_Definite_Access_Type;
1512
1513   ----------------------
1514   -- Is_Predefined_Op --
1515   ----------------------
1516
1517   function Is_Predefined_Op (Nam : Entity_Id) return Boolean is
1518   begin
1519      --  Predefined operators are intrinsic subprograms
1520
1521      if not Is_Intrinsic_Subprogram (Nam) then
1522         return False;
1523      end if;
1524
1525      --  A call to a back-end builtin is never a predefined operator
1526
1527      if Is_Imported (Nam) and then Present (Interface_Name (Nam)) then
1528         return False;
1529      end if;
1530
1531      return not Is_Generic_Instance (Nam)
1532        and then Chars (Nam) in Any_Operator_Name
1533        and then (No (Alias (Nam)) or else Is_Predefined_Op (Alias (Nam)));
1534   end Is_Predefined_Op;
1535
1536   -----------------------------
1537   -- Make_Call_Into_Operator --
1538   -----------------------------
1539
1540   procedure Make_Call_Into_Operator
1541     (N     : Node_Id;
1542      Typ   : Entity_Id;
1543      Op_Id : Entity_Id)
1544   is
1545      Op_Name   : constant Name_Id := Chars (Op_Id);
1546      Act1      : Node_Id := First_Actual (N);
1547      Act2      : Node_Id := Next_Actual (Act1);
1548      Error     : Boolean := False;
1549      Func      : constant Entity_Id := Entity (Name (N));
1550      Is_Binary : constant Boolean   := Present (Act2);
1551      Op_Node   : Node_Id;
1552      Opnd_Type : Entity_Id := Empty;
1553      Orig_Type : Entity_Id := Empty;
1554      Pack      : Entity_Id;
1555
1556      type Kind_Test is access function (E : Entity_Id) return Boolean;
1557
1558      function Operand_Type_In_Scope (S : Entity_Id) return Boolean;
1559      --  If the operand is not universal, and the operator is given by an
1560      --  expanded name, verify that the operand has an interpretation with a
1561      --  type defined in the given scope of the operator.
1562
1563      function Type_In_P (Test : Kind_Test) return Entity_Id;
1564      --  Find a type of the given class in package Pack that contains the
1565      --  operator.
1566
1567      ---------------------------
1568      -- Operand_Type_In_Scope --
1569      ---------------------------
1570
1571      function Operand_Type_In_Scope (S : Entity_Id) return Boolean is
1572         Nod : constant Node_Id := Right_Opnd (Op_Node);
1573         I   : Interp_Index;
1574         It  : Interp;
1575
1576      begin
1577         if not Is_Overloaded (Nod) then
1578            return Scope (Base_Type (Etype (Nod))) = S;
1579
1580         else
1581            Get_First_Interp (Nod, I, It);
1582            while Present (It.Typ) loop
1583               if Scope (Base_Type (It.Typ)) = S then
1584                  return True;
1585               end if;
1586
1587               Get_Next_Interp (I, It);
1588            end loop;
1589
1590            return False;
1591         end if;
1592      end Operand_Type_In_Scope;
1593
1594      ---------------
1595      -- Type_In_P --
1596      ---------------
1597
1598      function Type_In_P (Test : Kind_Test) return Entity_Id is
1599         E : Entity_Id;
1600
1601         function In_Decl return Boolean;
1602         --  Verify that node is not part of the type declaration for the
1603         --  candidate type, which would otherwise be invisible.
1604
1605         -------------
1606         -- In_Decl --
1607         -------------
1608
1609         function In_Decl return Boolean is
1610            Decl_Node : constant Node_Id := Parent (E);
1611            N2        : Node_Id;
1612
1613         begin
1614            N2 := N;
1615
1616            if Etype (E) = Any_Type then
1617               return True;
1618
1619            elsif No (Decl_Node) then
1620               return False;
1621
1622            else
1623               while Present (N2)
1624                 and then Nkind (N2) /= N_Compilation_Unit
1625               loop
1626                  if N2 = Decl_Node then
1627                     return True;
1628                  else
1629                     N2 := Parent (N2);
1630                  end if;
1631               end loop;
1632
1633               return False;
1634            end if;
1635         end In_Decl;
1636
1637      --  Start of processing for Type_In_P
1638
1639      begin
1640         --  If the context type is declared in the prefix package, this is the
1641         --  desired base type.
1642
1643         if Scope (Base_Type (Typ)) = Pack and then Test (Typ) then
1644            return Base_Type (Typ);
1645
1646         else
1647            E := First_Entity (Pack);
1648            while Present (E) loop
1649               if Test (E) and then not In_Decl then
1650                  return E;
1651               end if;
1652
1653               Next_Entity (E);
1654            end loop;
1655
1656            return Empty;
1657         end if;
1658      end Type_In_P;
1659
1660   --  Start of processing for Make_Call_Into_Operator
1661
1662   begin
1663      Op_Node := New_Node (Operator_Kind (Op_Name, Is_Binary), Sloc (N));
1664
1665      --  Ensure that the corresponding operator has the same parent as the
1666      --  original call. This guarantees that parent traversals performed by
1667      --  the ABE mechanism succeed.
1668
1669      Set_Parent (Op_Node, Parent (N));
1670
1671      --  Binary operator
1672
1673      if Is_Binary then
1674         Set_Left_Opnd  (Op_Node, Relocate_Node (Act1));
1675         Set_Right_Opnd (Op_Node, Relocate_Node (Act2));
1676         Save_Interps (Act1, Left_Opnd  (Op_Node));
1677         Save_Interps (Act2, Right_Opnd (Op_Node));
1678         Act1 := Left_Opnd (Op_Node);
1679         Act2 := Right_Opnd (Op_Node);
1680
1681      --  Unary operator
1682
1683      else
1684         Set_Right_Opnd (Op_Node, Relocate_Node (Act1));
1685         Save_Interps (Act1, Right_Opnd (Op_Node));
1686         Act1 := Right_Opnd (Op_Node);
1687      end if;
1688
1689      --  If the operator is denoted by an expanded name, and the prefix is
1690      --  not Standard, but the operator is a predefined one whose scope is
1691      --  Standard, then this is an implicit_operator, inserted as an
1692      --  interpretation by the procedure of the same name. This procedure
1693      --  overestimates the presence of implicit operators, because it does
1694      --  not examine the type of the operands. Verify now that the operand
1695      --  type appears in the given scope. If right operand is universal,
1696      --  check the other operand. In the case of concatenation, either
1697      --  argument can be the component type, so check the type of the result.
1698      --  If both arguments are literals, look for a type of the right kind
1699      --  defined in the given scope. This elaborate nonsense is brought to
1700      --  you courtesy of b33302a. The type itself must be frozen, so we must
1701      --  find the type of the proper class in the given scope.
1702
1703      --  A final wrinkle is the multiplication operator for fixed point types,
1704      --  which is defined in Standard only, and not in the scope of the
1705      --  fixed point type itself.
1706
1707      if Nkind (Name (N)) = N_Expanded_Name then
1708         Pack := Entity (Prefix (Name (N)));
1709
1710         --  If this is a package renaming, get renamed entity, which will be
1711         --  the scope of the operands if operaton is type-correct.
1712
1713         if Present (Renamed_Entity (Pack)) then
1714            Pack := Renamed_Entity (Pack);
1715         end if;
1716
1717         --  If the entity being called is defined in the given package, it is
1718         --  a renaming of a predefined operator, and known to be legal.
1719
1720         if Scope (Entity (Name (N))) = Pack
1721            and then Pack /= Standard_Standard
1722         then
1723            null;
1724
1725         --  Visibility does not need to be checked in an instance: if the
1726         --  operator was not visible in the generic it has been diagnosed
1727         --  already, else there is an implicit copy of it in the instance.
1728
1729         elsif In_Instance then
1730            null;
1731
1732         elsif Op_Name in Name_Op_Multiply | Name_Op_Divide
1733           and then Is_Fixed_Point_Type (Etype (Act1))
1734           and then Is_Fixed_Point_Type (Etype (Act2))
1735         then
1736            if Pack /= Standard_Standard then
1737               Error := True;
1738            end if;
1739
1740         --  Ada 2005 AI-420: Predefined equality on Universal_Access is
1741         --  available.
1742
1743         elsif Ada_Version >= Ada_2005
1744           and then Op_Name in Name_Op_Eq | Name_Op_Ne
1745           and then (Is_Anonymous_Access_Type (Etype (Act1))
1746                      or else Is_Anonymous_Access_Type (Etype (Act2)))
1747         then
1748            null;
1749
1750         else
1751            Opnd_Type := Base_Type (Etype (Right_Opnd (Op_Node)));
1752
1753            if Op_Name = Name_Op_Concat then
1754               Opnd_Type := Base_Type (Typ);
1755
1756            elsif (Scope (Opnd_Type) = Standard_Standard
1757                    and then Is_Binary)
1758              or else (Nkind (Right_Opnd (Op_Node)) = N_Attribute_Reference
1759                        and then Is_Binary
1760                        and then not Comes_From_Source (Opnd_Type))
1761            then
1762               Opnd_Type := Base_Type (Etype (Left_Opnd (Op_Node)));
1763            end if;
1764
1765            if Scope (Opnd_Type) = Standard_Standard then
1766
1767               --  Verify that the scope contains a type that corresponds to
1768               --  the given literal. Optimize the case where Pack is Standard.
1769
1770               if Pack /= Standard_Standard then
1771                  if Opnd_Type = Universal_Integer then
1772                     Orig_Type := Type_In_P (Is_Integer_Type'Access);
1773
1774                  elsif Opnd_Type = Universal_Real then
1775                     Orig_Type := Type_In_P (Is_Real_Type'Access);
1776
1777                  elsif Opnd_Type = Any_String then
1778                     Orig_Type := Type_In_P (Is_String_Type'Access);
1779
1780                  elsif Opnd_Type = Any_Access then
1781                     Orig_Type := Type_In_P (Is_Definite_Access_Type'Access);
1782
1783                  elsif Opnd_Type = Any_Composite then
1784                     Orig_Type := Type_In_P (Is_Composite_Type'Access);
1785
1786                     if Present (Orig_Type) then
1787                        if Has_Private_Component (Orig_Type) then
1788                           Orig_Type := Empty;
1789                        else
1790                           Set_Etype (Act1, Orig_Type);
1791
1792                           if Is_Binary then
1793                              Set_Etype (Act2, Orig_Type);
1794                           end if;
1795                        end if;
1796                     end if;
1797
1798                  else
1799                     Orig_Type := Empty;
1800                  end if;
1801
1802                  Error := No (Orig_Type);
1803               end if;
1804
1805            elsif Ekind (Opnd_Type) = E_Allocator_Type
1806               and then No (Type_In_P (Is_Definite_Access_Type'Access))
1807            then
1808               Error := True;
1809
1810            --  If the type is defined elsewhere, and the operator is not
1811            --  defined in the given scope (by a renaming declaration, e.g.)
1812            --  then this is an error as well. If an extension of System is
1813            --  present, and the type may be defined there, Pack must be
1814            --  System itself.
1815
1816            elsif Scope (Opnd_Type) /= Pack
1817              and then Scope (Op_Id) /= Pack
1818              and then (No (System_Aux_Id)
1819                         or else Scope (Opnd_Type) /= System_Aux_Id
1820                         or else Pack /= Scope (System_Aux_Id))
1821            then
1822               if not Is_Overloaded (Right_Opnd (Op_Node)) then
1823                  Error := True;
1824               else
1825                  Error := not Operand_Type_In_Scope (Pack);
1826               end if;
1827
1828            elsif Pack = Standard_Standard
1829              and then not Operand_Type_In_Scope (Standard_Standard)
1830            then
1831               Error := True;
1832            end if;
1833         end if;
1834
1835         if Error then
1836            Error_Msg_Node_2 := Pack;
1837            Error_Msg_NE
1838              ("& not declared in&", N, Selector_Name (Name (N)));
1839            Set_Etype (N, Any_Type);
1840            return;
1841
1842         --  Detect a mismatch between the context type and the result type
1843         --  in the named package, which is otherwise not detected if the
1844         --  operands are universal. Check is only needed if source entity is
1845         --  an operator, not a function that renames an operator.
1846
1847         elsif Nkind (Parent (N)) /= N_Type_Conversion
1848           and then Ekind (Entity (Name (N))) = E_Operator
1849           and then Is_Numeric_Type (Typ)
1850           and then not Is_Universal_Numeric_Type (Typ)
1851           and then Scope (Base_Type (Typ)) /= Pack
1852           and then not In_Instance
1853         then
1854            if Is_Fixed_Point_Type (Typ)
1855              and then Op_Name in Name_Op_Multiply | Name_Op_Divide
1856            then
1857               --  Already checked above
1858
1859               null;
1860
1861            --  Operator may be defined in an extension of System
1862
1863            elsif Present (System_Aux_Id)
1864              and then Present (Opnd_Type)
1865              and then Scope (Opnd_Type) = System_Aux_Id
1866            then
1867               null;
1868
1869            else
1870               --  Could we use Wrong_Type here??? (this would require setting
1871               --  Etype (N) to the actual type found where Typ was expected).
1872
1873               Error_Msg_NE ("expect }", N, Typ);
1874            end if;
1875         end if;
1876      end if;
1877
1878      Set_Chars  (Op_Node, Op_Name);
1879
1880      if not Is_Private_Type (Etype (N)) then
1881         Set_Etype (Op_Node, Base_Type (Etype (N)));
1882      else
1883         Set_Etype (Op_Node, Etype (N));
1884      end if;
1885
1886      --  If this is a call to a function that renames a predefined equality,
1887      --  the renaming declaration provides a type that must be used to
1888      --  resolve the operands. This must be done now because resolution of
1889      --  the equality node will not resolve any remaining ambiguity, and it
1890      --  assumes that the first operand is not overloaded.
1891
1892      if Op_Name in Name_Op_Eq | Name_Op_Ne
1893        and then Ekind (Func) = E_Function
1894        and then Is_Overloaded (Act1)
1895      then
1896         Resolve (Act1, Base_Type (Etype (First_Formal (Func))));
1897         Resolve (Act2, Base_Type (Etype (First_Formal (Func))));
1898      end if;
1899
1900      Set_Entity (Op_Node, Op_Id);
1901      Generate_Reference (Op_Id, N, ' ');
1902
1903      --  Do rewrite setting Comes_From_Source on the result if the original
1904      --  call came from source. Although it is not strictly the case that the
1905      --  operator as such comes from the source, logically it corresponds
1906      --  exactly to the function call in the source, so it should be marked
1907      --  this way (e.g. to make sure that validity checks work fine).
1908
1909      declare
1910         CS : constant Boolean := Comes_From_Source (N);
1911      begin
1912         Rewrite (N, Op_Node);
1913         Set_Comes_From_Source (N, CS);
1914      end;
1915
1916      --  If this is an arithmetic operator and the result type is private,
1917      --  the operands and the result must be wrapped in conversion to
1918      --  expose the underlying numeric type and expand the proper checks,
1919      --  e.g. on division.
1920
1921      if Is_Private_Type (Typ) then
1922         case Nkind (N) is
1923            when N_Op_Add
1924               | N_Op_Divide
1925               | N_Op_Expon
1926               | N_Op_Mod
1927               | N_Op_Multiply
1928               | N_Op_Rem
1929               | N_Op_Subtract
1930            =>
1931               Resolve_Intrinsic_Operator (N, Typ);
1932
1933            when N_Op_Abs
1934               | N_Op_Minus
1935               | N_Op_Plus
1936            =>
1937               Resolve_Intrinsic_Unary_Operator (N, Typ);
1938
1939            when others =>
1940               Resolve (N, Typ);
1941         end case;
1942      else
1943         Resolve (N, Typ);
1944      end if;
1945   end Make_Call_Into_Operator;
1946
1947   -------------------
1948   -- Operator_Kind --
1949   -------------------
1950
1951   function Operator_Kind
1952     (Op_Name   : Name_Id;
1953      Is_Binary : Boolean) return Node_Kind
1954   is
1955      Kind : Node_Kind;
1956
1957   begin
1958      --  Use CASE statement or array???
1959
1960      if Is_Binary then
1961         if    Op_Name = Name_Op_And      then
1962            Kind := N_Op_And;
1963         elsif Op_Name = Name_Op_Or       then
1964            Kind := N_Op_Or;
1965         elsif Op_Name = Name_Op_Xor      then
1966            Kind := N_Op_Xor;
1967         elsif Op_Name = Name_Op_Eq       then
1968            Kind := N_Op_Eq;
1969         elsif Op_Name = Name_Op_Ne       then
1970            Kind := N_Op_Ne;
1971         elsif Op_Name = Name_Op_Lt       then
1972            Kind := N_Op_Lt;
1973         elsif Op_Name = Name_Op_Le       then
1974            Kind := N_Op_Le;
1975         elsif Op_Name = Name_Op_Gt       then
1976            Kind := N_Op_Gt;
1977         elsif Op_Name = Name_Op_Ge       then
1978            Kind := N_Op_Ge;
1979         elsif Op_Name = Name_Op_Add      then
1980            Kind := N_Op_Add;
1981         elsif Op_Name = Name_Op_Subtract then
1982            Kind := N_Op_Subtract;
1983         elsif Op_Name = Name_Op_Concat   then
1984            Kind := N_Op_Concat;
1985         elsif Op_Name = Name_Op_Multiply then
1986            Kind := N_Op_Multiply;
1987         elsif Op_Name = Name_Op_Divide   then
1988            Kind := N_Op_Divide;
1989         elsif Op_Name = Name_Op_Mod      then
1990            Kind := N_Op_Mod;
1991         elsif Op_Name = Name_Op_Rem      then
1992            Kind := N_Op_Rem;
1993         elsif Op_Name = Name_Op_Expon    then
1994            Kind := N_Op_Expon;
1995         else
1996            raise Program_Error;
1997         end if;
1998
1999      --  Unary operators
2000
2001      else
2002         if    Op_Name = Name_Op_Add      then
2003            Kind := N_Op_Plus;
2004         elsif Op_Name = Name_Op_Subtract then
2005            Kind := N_Op_Minus;
2006         elsif Op_Name = Name_Op_Abs      then
2007            Kind := N_Op_Abs;
2008         elsif Op_Name = Name_Op_Not      then
2009            Kind := N_Op_Not;
2010         else
2011            raise Program_Error;
2012         end if;
2013      end if;
2014
2015      return Kind;
2016   end Operator_Kind;
2017
2018   ----------------------------
2019   -- Preanalyze_And_Resolve --
2020   ----------------------------
2021
2022   procedure Preanalyze_And_Resolve
2023     (N             : Node_Id;
2024      T             : Entity_Id;
2025      With_Freezing : Boolean)
2026   is
2027      Save_Full_Analysis     : constant Boolean := Full_Analysis;
2028      Save_Must_Not_Freeze   : constant Boolean := Must_Not_Freeze (N);
2029      Save_Preanalysis_Count : constant Nat :=
2030                                 Inside_Preanalysis_Without_Freezing;
2031   begin
2032      pragma Assert (Nkind (N) in N_Subexpr);
2033
2034      if not With_Freezing then
2035         Set_Must_Not_Freeze (N);
2036         Inside_Preanalysis_Without_Freezing :=
2037           Inside_Preanalysis_Without_Freezing + 1;
2038      end if;
2039
2040      Full_Analysis := False;
2041      Expander_Mode_Save_And_Set (False);
2042
2043      --  Normally, we suppress all checks for this preanalysis. There is no
2044      --  point in processing them now, since they will be applied properly
2045      --  and in the proper location when the default expressions reanalyzed
2046      --  and reexpanded later on. We will also have more information at that
2047      --  point for possible suppression of individual checks.
2048
2049      --  However, in SPARK mode, most expansion is suppressed, and this
2050      --  later reanalysis and reexpansion may not occur. SPARK mode does
2051      --  require the setting of checking flags for proof purposes, so we
2052      --  do the SPARK preanalysis without suppressing checks.
2053
2054      --  This special handling for SPARK mode is required for example in the
2055      --  case of Ada 2012 constructs such as quantified expressions, which are
2056      --  expanded in two separate steps.
2057
2058      if GNATprove_Mode then
2059         Analyze_And_Resolve (N, T);
2060      else
2061         Analyze_And_Resolve (N, T, Suppress => All_Checks);
2062      end if;
2063
2064      Expander_Mode_Restore;
2065      Full_Analysis := Save_Full_Analysis;
2066
2067      if not With_Freezing then
2068         Set_Must_Not_Freeze (N, Save_Must_Not_Freeze);
2069         Inside_Preanalysis_Without_Freezing :=
2070           Inside_Preanalysis_Without_Freezing - 1;
2071      end if;
2072
2073      pragma Assert
2074        (Inside_Preanalysis_Without_Freezing = Save_Preanalysis_Count);
2075   end Preanalyze_And_Resolve;
2076
2077   ----------------------------
2078   -- Preanalyze_And_Resolve --
2079   ----------------------------
2080
2081   procedure Preanalyze_And_Resolve (N : Node_Id; T : Entity_Id) is
2082   begin
2083      Preanalyze_And_Resolve (N, T, With_Freezing => False);
2084   end Preanalyze_And_Resolve;
2085
2086   --  Version without context type
2087
2088   procedure Preanalyze_And_Resolve (N : Node_Id) is
2089      Save_Full_Analysis : constant Boolean := Full_Analysis;
2090
2091   begin
2092      Full_Analysis := False;
2093      Expander_Mode_Save_And_Set (False);
2094
2095      Analyze (N);
2096      Resolve (N, Etype (N), Suppress => All_Checks);
2097
2098      Expander_Mode_Restore;
2099      Full_Analysis := Save_Full_Analysis;
2100   end Preanalyze_And_Resolve;
2101
2102   ------------------------------------------
2103   -- Preanalyze_With_Freezing_And_Resolve --
2104   ------------------------------------------
2105
2106   procedure Preanalyze_With_Freezing_And_Resolve
2107     (N : Node_Id;
2108      T : Entity_Id)
2109   is
2110   begin
2111      Preanalyze_And_Resolve (N, T, With_Freezing => True);
2112   end Preanalyze_With_Freezing_And_Resolve;
2113
2114   ----------------------------------
2115   -- Replace_Actual_Discriminants --
2116   ----------------------------------
2117
2118   procedure Replace_Actual_Discriminants (N : Node_Id; Default : Node_Id) is
2119      Loc : constant Source_Ptr := Sloc (N);
2120      Tsk : Node_Id := Empty;
2121
2122      function Process_Discr (Nod : Node_Id) return Traverse_Result;
2123      --  Comment needed???
2124
2125      -------------------
2126      -- Process_Discr --
2127      -------------------
2128
2129      function Process_Discr (Nod : Node_Id) return Traverse_Result is
2130         Ent : Entity_Id;
2131
2132      begin
2133         if Nkind (Nod) = N_Identifier then
2134            Ent := Entity (Nod);
2135
2136            if Present (Ent)
2137              and then Ekind (Ent) = E_Discriminant
2138            then
2139               Rewrite (Nod,
2140                 Make_Selected_Component (Loc,
2141                   Prefix        => New_Copy_Tree (Tsk, New_Sloc => Loc),
2142                   Selector_Name => Make_Identifier (Loc, Chars (Ent))));
2143
2144               Set_Etype (Nod, Etype (Ent));
2145            end if;
2146
2147         end if;
2148
2149         return OK;
2150      end Process_Discr;
2151
2152      procedure Replace_Discrs is new Traverse_Proc (Process_Discr);
2153
2154   --  Start of processing for Replace_Actual_Discriminants
2155
2156   begin
2157      if Expander_Active then
2158         null;
2159
2160      --  Allow the replacement of concurrent discriminants in GNATprove even
2161      --  though this is a light expansion activity. Note that generic units
2162      --  are not modified.
2163
2164      elsif GNATprove_Mode and not Inside_A_Generic then
2165         null;
2166
2167      else
2168         return;
2169      end if;
2170
2171      if Nkind (Name (N)) = N_Selected_Component then
2172         Tsk := Prefix (Name (N));
2173
2174      elsif Nkind (Name (N)) = N_Indexed_Component then
2175         Tsk := Prefix (Prefix (Name (N)));
2176      end if;
2177
2178      if Present (Tsk) then
2179         Replace_Discrs (Default);
2180      end if;
2181   end Replace_Actual_Discriminants;
2182
2183   -------------
2184   -- Resolve --
2185   -------------
2186
2187   procedure Resolve (N : Node_Id; Typ : Entity_Id) is
2188      Ambiguous : Boolean   := False;
2189      Ctx_Type  : Entity_Id := Typ;
2190      Expr_Type : Entity_Id := Empty; -- prevent junk warning
2191      Err_Type  : Entity_Id := Empty;
2192      Found     : Boolean   := False;
2193      From_Lib  : Boolean;
2194      I         : Interp_Index;
2195      I1        : Interp_Index := 0;  -- prevent junk warning
2196      It        : Interp;
2197      It1       : Interp;
2198      Seen      : Entity_Id := Empty; -- prevent junk warning
2199
2200      function Comes_From_Predefined_Lib_Unit (Nod : Node_Id) return Boolean;
2201      --  Determine whether a node comes from a predefined library unit or
2202      --  Standard.
2203
2204      procedure Patch_Up_Value (N : Node_Id; Typ : Entity_Id);
2205      --  Try and fix up a literal so that it matches its expected type. New
2206      --  literals are manufactured if necessary to avoid cascaded errors.
2207
2208      procedure Report_Ambiguous_Argument;
2209      --  Additional diagnostics when an ambiguous call has an ambiguous
2210      --  argument (typically a controlling actual).
2211
2212      procedure Resolution_Failed;
2213      --  Called when attempt at resolving current expression fails
2214
2215      ------------------------------------
2216      -- Comes_From_Predefined_Lib_Unit --
2217      -------------------------------------
2218
2219      function Comes_From_Predefined_Lib_Unit (Nod : Node_Id) return Boolean is
2220      begin
2221         return
2222           Sloc (Nod) = Standard_Location or else In_Predefined_Unit (Nod);
2223      end Comes_From_Predefined_Lib_Unit;
2224
2225      --------------------
2226      -- Patch_Up_Value --
2227      --------------------
2228
2229      procedure Patch_Up_Value (N : Node_Id; Typ : Entity_Id) is
2230      begin
2231         if Nkind (N) = N_Integer_Literal and then Is_Real_Type (Typ) then
2232            Rewrite (N,
2233              Make_Real_Literal (Sloc (N),
2234                Realval => UR_From_Uint (Intval (N))));
2235            Set_Etype (N, Universal_Real);
2236            Set_Is_Static_Expression (N);
2237
2238         elsif Nkind (N) = N_Real_Literal and then Is_Integer_Type (Typ) then
2239            Rewrite (N,
2240              Make_Integer_Literal (Sloc (N),
2241                Intval => UR_To_Uint (Realval (N))));
2242            Set_Etype (N, Universal_Integer);
2243            Set_Is_Static_Expression (N);
2244
2245         elsif Nkind (N) = N_String_Literal
2246                 and then Is_Character_Type (Typ)
2247         then
2248            Set_Character_Literal_Name (Char_Code (Character'Pos ('A')));
2249            Rewrite (N,
2250              Make_Character_Literal (Sloc (N),
2251                Chars => Name_Find,
2252                Char_Literal_Value =>
2253                  UI_From_Int (Character'Pos ('A'))));
2254            Set_Etype (N, Any_Character);
2255            Set_Is_Static_Expression (N);
2256
2257         elsif Nkind (N) /= N_String_Literal and then Is_String_Type (Typ) then
2258            Rewrite (N,
2259              Make_String_Literal (Sloc (N),
2260                Strval => End_String));
2261
2262         elsif Nkind (N) = N_Range then
2263            Patch_Up_Value (Low_Bound (N),  Typ);
2264            Patch_Up_Value (High_Bound (N), Typ);
2265         end if;
2266      end Patch_Up_Value;
2267
2268      -------------------------------
2269      -- Report_Ambiguous_Argument --
2270      -------------------------------
2271
2272      procedure Report_Ambiguous_Argument is
2273         Arg : constant Node_Id := First (Parameter_Associations (N));
2274         I   : Interp_Index;
2275         It  : Interp;
2276
2277      begin
2278         if Nkind (Arg) = N_Function_Call
2279           and then Is_Entity_Name (Name (Arg))
2280           and then Is_Overloaded (Name (Arg))
2281         then
2282            Error_Msg_NE ("ambiguous call to&", Arg, Name (Arg));
2283
2284            --  Examine possible interpretations, and adapt the message
2285            --  for inherited subprograms declared by a type derivation.
2286
2287            Get_First_Interp (Name (Arg), I, It);
2288            while Present (It.Nam) loop
2289               Error_Msg_Sloc := Sloc (It.Nam);
2290
2291               if Nkind (Parent (It.Nam)) = N_Full_Type_Declaration then
2292                  Error_Msg_N ("interpretation (inherited) #!", Arg);
2293               else
2294                  Error_Msg_N ("interpretation #!", Arg);
2295               end if;
2296
2297               Get_Next_Interp (I, It);
2298            end loop;
2299         end if;
2300
2301         --  Additional message and hint if the ambiguity involves an Ada 2022
2302         --  container aggregate.
2303
2304         Check_Ambiguous_Aggregate (N);
2305      end Report_Ambiguous_Argument;
2306
2307      -----------------------
2308      -- Resolution_Failed --
2309      -----------------------
2310
2311      procedure Resolution_Failed is
2312      begin
2313         Patch_Up_Value (N, Typ);
2314
2315         --  Set the type to the desired one to minimize cascaded errors. Note
2316         --  that this is an approximation and does not work in all cases.
2317
2318         Set_Etype (N, Typ);
2319
2320         Debug_A_Exit ("resolving  ", N, " (done, resolution failed)");
2321         Set_Is_Overloaded (N, False);
2322
2323         --  The caller will return without calling the expander, so we need
2324         --  to set the analyzed flag. Note that it is fine to set Analyzed
2325         --  to True even if we are in the middle of a shallow analysis,
2326         --  (see the spec of sem for more details) since this is an error
2327         --  situation anyway, and there is no point in repeating the
2328         --  analysis later (indeed it won't work to repeat it later, since
2329         --  we haven't got a clear resolution of which entity is being
2330         --  referenced.)
2331
2332         Set_Analyzed (N, True);
2333         return;
2334      end Resolution_Failed;
2335
2336   --  Start of processing for Resolve
2337
2338   begin
2339      if N = Error then
2340         return;
2341      end if;
2342
2343      --  Access attribute on remote subprogram cannot be used for a non-remote
2344      --  access-to-subprogram type.
2345
2346      if Nkind (N) = N_Attribute_Reference
2347        and then Attribute_Name (N) in Name_Access
2348                                     | Name_Unrestricted_Access
2349                                     | Name_Unchecked_Access
2350        and then Comes_From_Source (N)
2351        and then Is_Entity_Name (Prefix (N))
2352        and then Is_Subprogram (Entity (Prefix (N)))
2353        and then Is_Remote_Call_Interface (Entity (Prefix (N)))
2354        and then not Is_Remote_Access_To_Subprogram_Type (Typ)
2355      then
2356         Error_Msg_N
2357           ("prefix must statically denote a non-remote subprogram", N);
2358      end if;
2359
2360      From_Lib := Comes_From_Predefined_Lib_Unit (N);
2361
2362      --  If the context is a Remote_Access_To_Subprogram, access attributes
2363      --  must be resolved with the corresponding fat pointer. There is no need
2364      --  to check for the attribute name since the return type of an
2365      --  attribute is never a remote type.
2366
2367      if Nkind (N) = N_Attribute_Reference
2368        and then Comes_From_Source (N)
2369        and then (Is_Remote_Call_Interface (Typ) or else Is_Remote_Types (Typ))
2370      then
2371         declare
2372            Attr      : constant Attribute_Id :=
2373                          Get_Attribute_Id (Attribute_Name (N));
2374            Pref      : constant Node_Id      := Prefix (N);
2375            Decl      : Node_Id;
2376            Spec      : Node_Id;
2377            Is_Remote : Boolean := True;
2378
2379         begin
2380            --  Check that Typ is a remote access-to-subprogram type
2381
2382            if Is_Remote_Access_To_Subprogram_Type (Typ) then
2383
2384               --  Prefix (N) must statically denote a remote subprogram
2385               --  declared in a package specification.
2386
2387               if Attr = Attribute_Access           or else
2388                  Attr = Attribute_Unchecked_Access or else
2389                  Attr = Attribute_Unrestricted_Access
2390               then
2391                  Decl := Unit_Declaration_Node (Entity (Pref));
2392
2393                  if Nkind (Decl) = N_Subprogram_Body then
2394                     Spec := Corresponding_Spec (Decl);
2395
2396                     if Present (Spec) then
2397                        Decl := Unit_Declaration_Node (Spec);
2398                     end if;
2399                  end if;
2400
2401                  Spec := Parent (Decl);
2402
2403                  if not Is_Entity_Name (Prefix (N))
2404                    or else Nkind (Spec) /= N_Package_Specification
2405                    or else
2406                      not Is_Remote_Call_Interface (Defining_Entity (Spec))
2407                  then
2408                     Is_Remote := False;
2409                     Error_Msg_N
2410                       ("prefix must statically denote a remote subprogram",
2411                        N);
2412                  end if;
2413
2414                  --  If we are generating code in distributed mode, perform
2415                  --  semantic checks against corresponding remote entities.
2416
2417                  if Expander_Active
2418                    and then Get_PCS_Name /= Name_No_DSA
2419                  then
2420                     Check_Subtype_Conformant
2421                       (New_Id  => Entity (Prefix (N)),
2422                        Old_Id  => Designated_Type
2423                                     (Corresponding_Remote_Type (Typ)),
2424                        Err_Loc => N);
2425
2426                     if Is_Remote then
2427                        Process_Remote_AST_Attribute (N, Typ);
2428                     end if;
2429                  end if;
2430               end if;
2431            end if;
2432         end;
2433      end if;
2434
2435      Debug_A_Entry ("resolving  ", N);
2436
2437      if Debug_Flag_V then
2438         Write_Overloads (N);
2439      end if;
2440
2441      if Comes_From_Source (N) then
2442         if Is_Fixed_Point_Type (Typ) then
2443            Check_Restriction (No_Fixed_Point, N);
2444
2445         elsif Is_Floating_Point_Type (Typ)
2446           and then Typ /= Universal_Real
2447           and then Typ /= Any_Real
2448         then
2449            Check_Restriction (No_Floating_Point, N);
2450         end if;
2451      end if;
2452
2453      --  Return if already analyzed
2454
2455      if Analyzed (N) then
2456         Debug_A_Exit ("resolving  ", N, "  (done, already analyzed)");
2457         Analyze_Dimension (N);
2458         return;
2459
2460      --  Any case of Any_Type as the Etype value means that we had a
2461      --  previous error.
2462
2463      elsif Etype (N) = Any_Type then
2464         Debug_A_Exit ("resolving  ", N, "  (done, Etype = Any_Type)");
2465         return;
2466      end if;
2467
2468      Check_Parameterless_Call (N);
2469
2470      --  The resolution of an Expression_With_Actions is determined by
2471      --  its Expression, but if the node comes from source it is a
2472      --  Declare_Expression and requires scope management.
2473
2474      if Nkind (N) = N_Expression_With_Actions then
2475         if Comes_From_Source (N) and then N = Original_Node (N) then
2476            Resolve_Declare_Expression (N, Typ);
2477         else
2478            Resolve (Expression (N), Typ);
2479         end if;
2480
2481         Found := True;
2482         Expr_Type := Etype (Expression (N));
2483
2484      --  If not overloaded, then we know the type, and all that needs doing
2485      --  is to check that this type is compatible with the context.
2486
2487      elsif not Is_Overloaded (N) then
2488         Found := Covers (Typ, Etype (N));
2489         Expr_Type := Etype (N);
2490
2491      --  In the overloaded case, we must select the interpretation that
2492      --  is compatible with the context (i.e. the type passed to Resolve)
2493
2494      else
2495         --  Loop through possible interpretations
2496
2497         Get_First_Interp (N, I, It);
2498         Interp_Loop : while Present (It.Typ) loop
2499            if Debug_Flag_V then
2500               Write_Str ("Interp: ");
2501               Write_Interp (It);
2502            end if;
2503
2504            --  We are only interested in interpretations that are compatible
2505            --  with the expected type, any other interpretations are ignored.
2506
2507            if not Covers (Typ, It.Typ) then
2508               if Debug_Flag_V then
2509                  Write_Str ("    interpretation incompatible with context");
2510                  Write_Eol;
2511               end if;
2512
2513            else
2514               --  Skip the current interpretation if it is disabled by an
2515               --  abstract operator. This action is performed only when the
2516               --  type against which we are resolving is the same as the
2517               --  type of the interpretation.
2518
2519               if Ada_Version >= Ada_2005
2520                 and then It.Typ = Typ
2521                 and then not Is_Universal_Numeric_Type (Typ)
2522                 and then Present (It.Abstract_Op)
2523               then
2524                  if Debug_Flag_V then
2525                     Write_Line ("Skip.");
2526                  end if;
2527
2528                  goto Continue;
2529               end if;
2530
2531               --  First matching interpretation
2532
2533               if not Found then
2534                  Found := True;
2535                  I1    := I;
2536                  Seen  := It.Nam;
2537                  Expr_Type := It.Typ;
2538
2539               --  Matching interpretation that is not the first, maybe an
2540               --  error, but there are some cases where preference rules are
2541               --  used to choose between the two possibilities. These and
2542               --  some more obscure cases are handled in Disambiguate.
2543
2544               else
2545                  --  If the current statement is part of a predefined library
2546                  --  unit, then all interpretations which come from user level
2547                  --  packages should not be considered. Check previous and
2548                  --  current one.
2549
2550                  if From_Lib then
2551                     if not Comes_From_Predefined_Lib_Unit (It.Nam) then
2552                        goto Continue;
2553
2554                     elsif not Comes_From_Predefined_Lib_Unit (Seen) then
2555
2556                        --  Previous interpretation must be discarded
2557
2558                        I1 := I;
2559                        Seen := It.Nam;
2560                        Expr_Type := It.Typ;
2561                        Set_Entity (N, Seen);
2562                        goto Continue;
2563                     end if;
2564                  end if;
2565
2566                  --  Otherwise apply further disambiguation steps
2567
2568                  Error_Msg_Sloc := Sloc (Seen);
2569                  It1 := Disambiguate (N, I1, I, Typ);
2570
2571                  --  Disambiguation has succeeded. Skip the remaining
2572                  --  interpretations.
2573
2574                  if It1 /= No_Interp then
2575                     Seen := It1.Nam;
2576                     Expr_Type := It1.Typ;
2577
2578                     while Present (It.Typ) loop
2579                        Get_Next_Interp (I, It);
2580                     end loop;
2581
2582                  else
2583                     --  Before we issue an ambiguity complaint, check for the
2584                     --  case of a subprogram call where at least one of the
2585                     --  arguments is Any_Type, and if so suppress the message,
2586                     --  since it is a cascaded error. This can also happen for
2587                     --  a generalized indexing operation.
2588
2589                     if Nkind (N) in N_Subprogram_Call
2590                       or else (Nkind (N) = N_Indexed_Component
2591                                 and then Present (Generalized_Indexing (N)))
2592                     then
2593                        declare
2594                           A : Node_Id;
2595                           E : Node_Id;
2596
2597                        begin
2598                           if Nkind (N) = N_Indexed_Component then
2599                              Rewrite (N, Generalized_Indexing (N));
2600                           end if;
2601
2602                           A := First_Actual (N);
2603                           while Present (A) loop
2604                              E := A;
2605
2606                              if Nkind (E) = N_Parameter_Association then
2607                                 E := Explicit_Actual_Parameter (E);
2608                              end if;
2609
2610                              if Etype (E) = Any_Type then
2611                                 if Debug_Flag_V then
2612                                    Write_Str ("Any_Type in call");
2613                                    Write_Eol;
2614                                 end if;
2615
2616                                 exit Interp_Loop;
2617                              end if;
2618
2619                              Next_Actual (A);
2620                           end loop;
2621                        end;
2622
2623                     elsif Nkind (N) in N_Binary_Op
2624                       and then (Etype (Left_Opnd (N)) = Any_Type
2625                                  or else Etype (Right_Opnd (N)) = Any_Type)
2626                     then
2627                        exit Interp_Loop;
2628
2629                     elsif Nkind (N) in N_Unary_Op
2630                       and then Etype (Right_Opnd (N)) = Any_Type
2631                     then
2632                        exit Interp_Loop;
2633                     end if;
2634
2635                     --  Not that special case, so issue message using the flag
2636                     --  Ambiguous to control printing of the header message
2637                     --  only at the start of an ambiguous set.
2638
2639                     if not Ambiguous then
2640                        if Nkind (N) = N_Function_Call
2641                          and then Nkind (Name (N)) = N_Explicit_Dereference
2642                        then
2643                           Error_Msg_N
2644                             ("ambiguous expression (cannot resolve indirect "
2645                              & "call)!", N);
2646                        else
2647                           Error_Msg_NE -- CODEFIX
2648                             ("ambiguous expression (cannot resolve&)!",
2649                              N, It.Nam);
2650                        end if;
2651
2652                        Ambiguous := True;
2653
2654                        if Nkind (Parent (Seen)) = N_Full_Type_Declaration then
2655                           Error_Msg_N
2656                             ("\\possible interpretation (inherited)#!", N);
2657                        else
2658                           Error_Msg_N -- CODEFIX
2659                             ("\\possible interpretation#!", N);
2660                        end if;
2661
2662                        if Nkind (N) in N_Subprogram_Call
2663                          and then Present (Parameter_Associations (N))
2664                        then
2665                           Report_Ambiguous_Argument;
2666                        end if;
2667                     end if;
2668
2669                     Error_Msg_Sloc := Sloc (It.Nam);
2670
2671                     --  By default, the error message refers to the candidate
2672                     --  interpretation. But if it is a predefined operator, it
2673                     --  is implicitly declared at the declaration of the type
2674                     --  of the operand. Recover the sloc of that declaration
2675                     --  for the error message.
2676
2677                     if Nkind (N) in N_Op
2678                       and then Scope (It.Nam) = Standard_Standard
2679                       and then not Is_Overloaded (Right_Opnd (N))
2680                       and then Scope (Base_Type (Etype (Right_Opnd (N)))) /=
2681                                                             Standard_Standard
2682                     then
2683                        Err_Type := First_Subtype (Etype (Right_Opnd (N)));
2684
2685                        if Comes_From_Source (Err_Type)
2686                          and then Present (Parent (Err_Type))
2687                        then
2688                           Error_Msg_Sloc := Sloc (Parent (Err_Type));
2689                        end if;
2690
2691                     elsif Nkind (N) in N_Binary_Op
2692                       and then Scope (It.Nam) = Standard_Standard
2693                       and then not Is_Overloaded (Left_Opnd (N))
2694                       and then Scope (Base_Type (Etype (Left_Opnd (N)))) /=
2695                                                             Standard_Standard
2696                     then
2697                        Err_Type := First_Subtype (Etype (Left_Opnd (N)));
2698
2699                        if Comes_From_Source (Err_Type)
2700                          and then Present (Parent (Err_Type))
2701                        then
2702                           Error_Msg_Sloc := Sloc (Parent (Err_Type));
2703                        end if;
2704
2705                     --  If this is an indirect call, use the subprogram_type
2706                     --  in the message, to have a meaningful location. Also
2707                     --  indicate if this is an inherited operation, created
2708                     --  by a type declaration.
2709
2710                     elsif Nkind (N) = N_Function_Call
2711                       and then Nkind (Name (N)) = N_Explicit_Dereference
2712                       and then Is_Type (It.Nam)
2713                     then
2714                        Err_Type := It.Nam;
2715                        Error_Msg_Sloc :=
2716                          Sloc (Associated_Node_For_Itype (Err_Type));
2717                     else
2718                        Err_Type := Empty;
2719                     end if;
2720
2721                     if Nkind (N) in N_Op
2722                       and then Scope (It.Nam) = Standard_Standard
2723                       and then Present (Err_Type)
2724                     then
2725                        --  Special-case the message for universal_fixed
2726                        --  operators, which are not declared with the type
2727                        --  of the operand, but appear forever in Standard.
2728
2729                        if It.Typ = Universal_Fixed
2730                          and then Scope (It.Nam) = Standard_Standard
2731                        then
2732                           Error_Msg_N
2733                             ("\\possible interpretation as universal_fixed "
2734                              & "operation (RM 4.5.5 (19))", N);
2735                        else
2736                           Error_Msg_N
2737                             ("\\possible interpretation (predefined)#!", N);
2738                        end if;
2739
2740                     elsif
2741                       Nkind (Parent (It.Nam)) = N_Full_Type_Declaration
2742                     then
2743                        Error_Msg_N
2744                          ("\\possible interpretation (inherited)#!", N);
2745                     else
2746                        Error_Msg_N -- CODEFIX
2747                          ("\\possible interpretation#!", N);
2748                     end if;
2749
2750                  end if;
2751               end if;
2752
2753               --  We have a matching interpretation, Expr_Type is the type
2754               --  from this interpretation, and Seen is the entity.
2755
2756               --  For an operator, just set the entity name. The type will be
2757               --  set by the specific operator resolution routine.
2758
2759               if Nkind (N) in N_Op then
2760                  Set_Entity (N, Seen);
2761                  Generate_Reference (Seen, N);
2762
2763               elsif Nkind (N) in N_Case_Expression
2764                                | N_Character_Literal
2765                                | N_Delta_Aggregate
2766                                | N_If_Expression
2767               then
2768                  Set_Etype (N, Expr_Type);
2769
2770               --  AI05-0139-2: Expression is overloaded because type has
2771               --  implicit dereference. The context may be the one that
2772               --  requires implicit dereferemce.
2773
2774               elsif Has_Implicit_Dereference (Expr_Type) then
2775                  Set_Etype (N, Expr_Type);
2776                  Set_Is_Overloaded (N, False);
2777
2778               --  If the expression is an entity, generate a reference
2779               --  to it, as this is not done for an overloaded construct
2780               --  during analysis.
2781
2782                  if Is_Entity_Name (N)
2783                    and then Comes_From_Source (N)
2784                  then
2785                     Generate_Reference (Entity (N), N);
2786
2787                     --  Examine access discriminants of entity type,
2788                     --  to check whether one of them yields the
2789                     --  expected type.
2790
2791                     declare
2792                        Disc : Entity_Id :=
2793                          First_Discriminant (Etype (Entity (N)));
2794
2795                     begin
2796                        while Present (Disc) loop
2797                           exit when Is_Access_Type (Etype (Disc))
2798                             and then Has_Implicit_Dereference (Disc)
2799                             and then Designated_Type (Etype (Disc)) = Typ;
2800
2801                           Next_Discriminant (Disc);
2802                        end loop;
2803
2804                        if Present (Disc) then
2805                           Build_Explicit_Dereference (N, Disc);
2806                        end if;
2807                     end;
2808                  end if;
2809
2810                  exit Interp_Loop;
2811
2812               elsif Is_Overloaded (N)
2813                 and then Present (It.Nam)
2814                 and then Ekind (It.Nam) = E_Discriminant
2815                 and then Has_Implicit_Dereference (It.Nam)
2816               then
2817                  --  If the node is a general indexing, the dereference is
2818                  --  is inserted when resolving the rewritten form, else
2819                  --  insert it now.
2820
2821                  if Nkind (N) /= N_Indexed_Component
2822                    or else No (Generalized_Indexing (N))
2823                  then
2824                     Build_Explicit_Dereference (N, It.Nam);
2825                  end if;
2826
2827               --  For an explicit dereference, attribute reference, range,
2828               --  short-circuit form (which is not an operator node), or call
2829               --  with a name that is an explicit dereference, there is
2830               --  nothing to be done at this point.
2831
2832               elsif Nkind (N) in N_Attribute_Reference
2833                                | N_And_Then
2834                                | N_Explicit_Dereference
2835                                | N_Identifier
2836                                | N_Indexed_Component
2837                                | N_Or_Else
2838                                | N_Range
2839                                | N_Selected_Component
2840                                | N_Slice
2841                 or else Nkind (Name (N)) = N_Explicit_Dereference
2842               then
2843                  null;
2844
2845               --  For procedure or function calls, set the type of the name,
2846               --  and also the entity pointer for the prefix.
2847
2848               elsif Nkind (N) in N_Subprogram_Call
2849                 and then Is_Entity_Name (Name (N))
2850               then
2851                  Set_Etype  (Name (N), Expr_Type);
2852                  Set_Entity (Name (N), Seen);
2853                  Generate_Reference (Seen, Name (N));
2854
2855               elsif Nkind (N) = N_Function_Call
2856                 and then Nkind (Name (N)) = N_Selected_Component
2857               then
2858                  Set_Etype (Name (N), Expr_Type);
2859                  Set_Entity (Selector_Name (Name (N)), Seen);
2860                  Generate_Reference (Seen, Selector_Name (Name (N)));
2861
2862               --  For all other cases, just set the type of the Name
2863
2864               else
2865                  Set_Etype (Name (N), Expr_Type);
2866               end if;
2867
2868            end if;
2869
2870            <<Continue>>
2871
2872            --  Move to next interpretation
2873
2874            exit Interp_Loop when No (It.Typ);
2875
2876            Get_Next_Interp (I, It);
2877         end loop Interp_Loop;
2878      end if;
2879
2880      --  At this stage Found indicates whether or not an acceptable
2881      --  interpretation exists. If not, then we have an error, except that if
2882      --  the context is Any_Type as a result of some other error, then we
2883      --  suppress the error report.
2884
2885      if not Found then
2886         if Typ /= Any_Type then
2887
2888            --  If type we are looking for is Void, then this is the procedure
2889            --  call case, and the error is simply that what we gave is not a
2890            --  procedure name (we think of procedure calls as expressions with
2891            --  types internally, but the user doesn't think of them this way).
2892
2893            if Typ = Standard_Void_Type then
2894
2895               --  Special case message if function used as a procedure
2896
2897               if Nkind (N) = N_Procedure_Call_Statement
2898                 and then Is_Entity_Name (Name (N))
2899                 and then Ekind (Entity (Name (N))) = E_Function
2900               then
2901                  Error_Msg_NE
2902                    ("cannot use call to function & as a statement",
2903                     Name (N), Entity (Name (N)));
2904                  Error_Msg_N
2905                    ("\return value of a function call cannot be ignored",
2906                     Name (N));
2907
2908               --  Otherwise give general message (not clear what cases this
2909               --  covers, but no harm in providing for them).
2910
2911               else
2912                  Error_Msg_N ("expect procedure name in procedure call", N);
2913               end if;
2914
2915               Found := True;
2916
2917            --  Otherwise we do have a subexpression with the wrong type
2918
2919            --  Check for the case of an allocator which uses an access type
2920            --  instead of the designated type. This is a common error and we
2921            --  specialize the message, posting an error on the operand of the
2922            --  allocator, complaining that we expected the designated type of
2923            --  the allocator.
2924
2925            elsif Nkind (N) = N_Allocator
2926              and then Is_Access_Type (Typ)
2927              and then Is_Access_Type (Etype (N))
2928              and then Designated_Type (Etype (N)) = Typ
2929            then
2930               Wrong_Type (Expression (N), Designated_Type (Typ));
2931               Found := True;
2932
2933            --  Check for view mismatch on Null in instances, for which the
2934            --  view-swapping mechanism has no identifier.
2935
2936            elsif (In_Instance or else In_Inlined_Body)
2937              and then (Nkind (N) = N_Null)
2938              and then Is_Private_Type (Typ)
2939              and then Is_Access_Type (Full_View (Typ))
2940            then
2941               Resolve (N, Full_View (Typ));
2942               Set_Etype (N, Typ);
2943               return;
2944
2945            --  Check for an aggregate. Sometimes we can get bogus aggregates
2946            --  from misuse of parentheses, and we are about to complain about
2947            --  the aggregate without even looking inside it.
2948
2949            --  Instead, if we have an aggregate of type Any_Composite, then
2950            --  analyze and resolve the component fields, and then only issue
2951            --  another message if we get no errors doing this (otherwise
2952            --  assume that the errors in the aggregate caused the problem).
2953
2954            elsif Nkind (N) = N_Aggregate
2955              and then Etype (N) = Any_Composite
2956            then
2957               if Ada_Version >= Ada_2022
2958                 and then Has_Aspect (Typ, Aspect_Aggregate)
2959               then
2960                  Resolve_Container_Aggregate (N, Typ);
2961
2962                  if Expander_Active then
2963                     Expand (N);
2964                  end if;
2965                  return;
2966               end if;
2967
2968               --  Disable expansion in any case. If there is a type mismatch
2969               --  it may be fatal to try to expand the aggregate. The flag
2970               --  would otherwise be set to false when the error is posted.
2971
2972               Expander_Active := False;
2973
2974               declare
2975                  procedure Check_Aggr (Aggr : Node_Id);
2976                  --  Check one aggregate, and set Found to True if we have a
2977                  --  definite error in any of its elements
2978
2979                  procedure Check_Elmt (Aelmt : Node_Id);
2980                  --  Check one element of aggregate and set Found to True if
2981                  --  we definitely have an error in the element.
2982
2983                  ----------------
2984                  -- Check_Aggr --
2985                  ----------------
2986
2987                  procedure Check_Aggr (Aggr : Node_Id) is
2988                     Elmt : Node_Id;
2989
2990                  begin
2991                     if Present (Expressions (Aggr)) then
2992                        Elmt := First (Expressions (Aggr));
2993                        while Present (Elmt) loop
2994                           Check_Elmt (Elmt);
2995                           Next (Elmt);
2996                        end loop;
2997                     end if;
2998
2999                     if Present (Component_Associations (Aggr)) then
3000                        Elmt := First (Component_Associations (Aggr));
3001                        while Present (Elmt) loop
3002
3003                           --  If this is a default-initialized component, then
3004                           --  there is nothing to check. The box will be
3005                           --  replaced by the appropriate call during late
3006                           --  expansion.
3007
3008                           if Nkind (Elmt) /= N_Iterated_Component_Association
3009                             and then not Box_Present (Elmt)
3010                           then
3011                              Check_Elmt (Expression (Elmt));
3012                           end if;
3013
3014                           Next (Elmt);
3015                        end loop;
3016                     end if;
3017                  end Check_Aggr;
3018
3019                  ----------------
3020                  -- Check_Elmt --
3021                  ----------------
3022
3023                  procedure Check_Elmt (Aelmt : Node_Id) is
3024                  begin
3025                     --  If we have a nested aggregate, go inside it (to
3026                     --  attempt a naked analyze-resolve of the aggregate can
3027                     --  cause undesirable cascaded errors). Do not resolve
3028                     --  expression if it needs a type from context, as for
3029                     --  integer * fixed expression.
3030
3031                     if Nkind (Aelmt) = N_Aggregate then
3032                        Check_Aggr (Aelmt);
3033
3034                     else
3035                        Analyze (Aelmt);
3036
3037                        if not Is_Overloaded (Aelmt)
3038                          and then Etype (Aelmt) /= Any_Fixed
3039                        then
3040                           Resolve (Aelmt);
3041                        end if;
3042
3043                        if Etype (Aelmt) = Any_Type then
3044                           Found := True;
3045                        end if;
3046                     end if;
3047                  end Check_Elmt;
3048
3049               begin
3050                  Check_Aggr (N);
3051               end;
3052            end if;
3053
3054            --  If node is a literal and context type has a user-defined
3055            --  literal aspect, rewrite node as a call to the corresponding
3056            --  function, which plays the role of an implicit conversion.
3057
3058            if Nkind (N) in
3059                N_Numeric_Or_String_Literal | N_Identifier
3060              and then Has_Applicable_User_Defined_Literal (N, Typ)
3061            then
3062               Analyze_And_Resolve (N, Typ);
3063               return;
3064            end if;
3065
3066            --  Looks like we have a type error, but check for special case
3067            --  of Address wanted, integer found, with the configuration pragma
3068            --  Allow_Integer_Address active. If we have this case, introduce
3069            --  an unchecked conversion to allow the integer expression to be
3070            --  treated as an Address. The reverse case of integer wanted,
3071            --  Address found, is treated in an analogous manner.
3072
3073            if Address_Integer_Convert_OK (Typ, Etype (N)) then
3074               Rewrite (N, Unchecked_Convert_To (Typ, Relocate_Node (N)));
3075               Analyze_And_Resolve (N, Typ);
3076               return;
3077
3078            --  Under relaxed RM semantics silently replace occurrences of null
3079            --  by System.Null_Address.
3080
3081            elsif Null_To_Null_Address_Convert_OK (N, Typ) then
3082               Replace_Null_By_Null_Address (N);
3083               Analyze_And_Resolve (N, Typ);
3084               return;
3085            end if;
3086
3087            --  That special Allow_Integer_Address check did not apply, so we
3088            --  have a real type error. If an error message was issued already,
3089            --  Found got reset to True, so if it's still False, issue standard
3090            --  Wrong_Type message.
3091
3092            if not Found then
3093               if Is_Overloaded (N) and then Nkind (N) = N_Function_Call then
3094                  declare
3095                     Subp_Name : Node_Id;
3096
3097                  begin
3098                     if Is_Entity_Name (Name (N)) then
3099                        Subp_Name := Name (N);
3100
3101                     elsif Nkind (Name (N)) = N_Selected_Component then
3102
3103                        --  Protected operation: retrieve operation name
3104
3105                        Subp_Name := Selector_Name (Name (N));
3106
3107                     else
3108                        raise Program_Error;
3109                     end if;
3110
3111                     Error_Msg_Node_2 := Typ;
3112                     Error_Msg_NE
3113                       ("no visible interpretation of& matches expected type&",
3114                        N, Subp_Name);
3115                  end;
3116
3117                  if All_Errors_Mode then
3118                     declare
3119                        Index : Interp_Index;
3120                        It    : Interp;
3121
3122                     begin
3123                        Error_Msg_N ("\\possible interpretations:", N);
3124
3125                        Get_First_Interp (Name (N), Index, It);
3126                        while Present (It.Nam) loop
3127                           Error_Msg_Sloc := Sloc (It.Nam);
3128                           Error_Msg_Node_2 := It.Nam;
3129                           Error_Msg_NE
3130                             ("\\  type& for & declared#", N, It.Typ);
3131                           Get_Next_Interp (Index, It);
3132                        end loop;
3133                     end;
3134
3135                  else
3136                     Error_Msg_N ("\use -gnatf for details", N);
3137                  end if;
3138
3139               --  Recognize the case of a quantified expression being mistaken
3140               --  for an iterated component association because the user
3141               --  forgot the "all" or "some" keyword after "for". Because the
3142               --  error message starts with "missing ALL", we automatically
3143               --  benefit from the associated CODEFIX, which requires that
3144               --  the message is located on the identifier following "for"
3145               --  in order for the CODEFIX to insert "all" in the right place.
3146
3147               elsif Nkind (N) = N_Aggregate
3148                 and then List_Length (Component_Associations (N)) = 1
3149                 and then Nkind (First (Component_Associations (N)))
3150                   = N_Iterated_Component_Association
3151                 and then Is_Boolean_Type (Typ)
3152               then
3153                  Error_Msg_N -- CODEFIX
3154                    ("missing ALL or SOME in quantified expression",
3155                     Defining_Identifier (First (Component_Associations (N))));
3156
3157               --  For an operator with no interpretation, check whether
3158               --  one of its operands may be a user-defined literal.
3159
3160               elsif Nkind (N) in N_Op
3161                 and then Try_User_Defined_Literal (N, Typ)
3162               then
3163                  return;
3164
3165               else
3166                  Wrong_Type (N, Typ);
3167               end if;
3168            end if;
3169         end if;
3170
3171         Resolution_Failed;
3172         return;
3173
3174      --  Test if we have more than one interpretation for the context
3175
3176      elsif Ambiguous then
3177         Resolution_Failed;
3178         return;
3179
3180      --  Only one interpretation
3181
3182      else
3183         --  Prevent implicit conversions between access-to-subprogram types
3184         --  with different strub modes. Explicit conversions are acceptable in
3185         --  some circumstances. We don't have to be concerned about data or
3186         --  access-to-data types. Conversions between data types can safely
3187         --  drop or add strub attributes from types, because strub effects are
3188         --  associated with the locations rather than values. E.g., converting
3189         --  a hypothetical Strub_Integer variable to Integer would load the
3190         --  value from the variable, enabling stack scrabbing for the
3191         --  enclosing subprogram, and then convert the value to Integer. As
3192         --  for conversions between access-to-data types, that's no different
3193         --  from any other case of type punning.
3194
3195         if Is_Access_Type (Typ)
3196           and then Ekind (Designated_Type (Typ)) = E_Subprogram_Type
3197           and then Is_Access_Type (Expr_Type)
3198           and then Ekind (Designated_Type (Expr_Type)) = E_Subprogram_Type
3199         then
3200            Check_Same_Strub_Mode
3201              (Designated_Type (Typ), Designated_Type (Expr_Type));
3202         end if;
3203
3204         --  In Ada 2005, if we have something like "X : T := 2 + 2;", where
3205         --  the "+" on T is abstract, and the operands are of universal type,
3206         --  the above code will have (incorrectly) resolved the "+" to the
3207         --  universal one in Standard. Therefore check for this case and give
3208         --  an error. We can't do this earlier, because it would cause legal
3209         --  cases to get errors (when some other type has an abstract "+").
3210
3211         if Ada_Version >= Ada_2005
3212           and then Nkind (N) in N_Op
3213           and then Is_Overloaded (N)
3214           and then Is_Universal_Numeric_Type (Etype (Entity (N)))
3215         then
3216            Get_First_Interp (N, I, It);
3217            while Present (It.Typ) loop
3218               if Present (It.Abstract_Op) and then
3219                 Etype (It.Abstract_Op) = Typ
3220               then
3221                  Error_Msg_NE
3222                    ("cannot call abstract subprogram &!", N, It.Abstract_Op);
3223                  return;
3224               end if;
3225
3226               Get_Next_Interp (I, It);
3227            end loop;
3228         end if;
3229
3230         --  Here we have an acceptable interpretation for the context
3231
3232         --  Propagate type information and normalize tree for various
3233         --  predefined operations. If the context only imposes a class of
3234         --  types, rather than a specific type, propagate the actual type
3235         --  downward.
3236
3237         if Typ = Any_Integer or else
3238            Typ = Any_Boolean or else
3239            Typ = Any_Modular or else
3240            Typ = Any_Real    or else
3241            Typ = Any_Discrete
3242         then
3243            Ctx_Type := Expr_Type;
3244
3245            --  Any_Fixed is legal in a real context only if a specific fixed-
3246            --  point type is imposed. If Norman Cohen can be confused by this,
3247            --  it deserves a separate message.
3248
3249            if Typ = Any_Real
3250              and then Expr_Type = Any_Fixed
3251            then
3252               Error_Msg_N ("illegal context for mixed mode operation", N);
3253               Set_Etype (N, Universal_Real);
3254               Ctx_Type := Universal_Real;
3255            end if;
3256         end if;
3257
3258         --  A user-defined operator is transformed into a function call at
3259         --  this point, so that further processing knows that operators are
3260         --  really operators (i.e. are predefined operators). User-defined
3261         --  operators that are intrinsic are just renamings of the predefined
3262         --  ones, and need not be turned into calls either, but if they rename
3263         --  a different operator, we must transform the node accordingly.
3264         --  Instantiations of Unchecked_Conversion are intrinsic but are
3265         --  treated as functions, even if given an operator designator.
3266
3267         if Nkind (N) in N_Op
3268           and then Present (Entity (N))
3269           and then Ekind (Entity (N)) /= E_Operator
3270         then
3271            if not Is_Predefined_Op (Entity (N)) then
3272               Rewrite_Operator_As_Call (N, Entity (N));
3273
3274            elsif Present (Alias (Entity (N)))
3275              and then
3276                Nkind (Parent (Parent (Entity (N)))) =
3277                                    N_Subprogram_Renaming_Declaration
3278            then
3279               Rewrite_Renamed_Operator (N, Alias (Entity (N)), Typ);
3280
3281               --  If the node is rewritten, it will be fully resolved in
3282               --  Rewrite_Renamed_Operator.
3283
3284               if Analyzed (N) then
3285                  return;
3286               end if;
3287            end if;
3288         end if;
3289
3290         case N_Subexpr'(Nkind (N)) is
3291            when N_Aggregate =>
3292               Resolve_Aggregate                 (N, Ctx_Type);
3293
3294            when N_Allocator =>
3295               Resolve_Allocator                 (N, Ctx_Type);
3296
3297            when N_Short_Circuit =>
3298               Resolve_Short_Circuit             (N, Ctx_Type);
3299
3300            when N_Attribute_Reference =>
3301               Resolve_Attribute                 (N, Ctx_Type);
3302
3303            when N_Case_Expression =>
3304               Resolve_Case_Expression           (N, Ctx_Type);
3305
3306            when N_Character_Literal =>
3307               Resolve_Character_Literal         (N, Ctx_Type);
3308
3309            when N_Delta_Aggregate =>
3310               Resolve_Delta_Aggregate           (N, Ctx_Type);
3311
3312            when N_Expanded_Name =>
3313               Resolve_Entity_Name               (N, Ctx_Type);
3314
3315            when N_Explicit_Dereference =>
3316               Resolve_Explicit_Dereference      (N, Ctx_Type);
3317
3318            when N_Expression_With_Actions =>
3319               Resolve_Expression_With_Actions   (N, Ctx_Type);
3320
3321            when N_Extension_Aggregate =>
3322               Resolve_Extension_Aggregate       (N, Ctx_Type);
3323
3324            when N_Function_Call =>
3325               Resolve_Call                      (N, Ctx_Type);
3326
3327            when N_Identifier =>
3328               Resolve_Entity_Name               (N, Ctx_Type);
3329
3330            when N_If_Expression =>
3331               Resolve_If_Expression             (N, Ctx_Type);
3332
3333            when N_Indexed_Component =>
3334               Resolve_Indexed_Component         (N, Ctx_Type);
3335
3336            when N_Integer_Literal =>
3337               Resolve_Integer_Literal           (N, Ctx_Type);
3338
3339            when N_Membership_Test =>
3340               Resolve_Membership_Op             (N, Ctx_Type);
3341
3342            when N_Null =>
3343               Resolve_Null                      (N, Ctx_Type);
3344
3345            when N_Op_And
3346               | N_Op_Or
3347               | N_Op_Xor
3348            =>
3349               Resolve_Logical_Op                (N, Ctx_Type);
3350
3351            when N_Op_Eq
3352               | N_Op_Ne
3353            =>
3354               Resolve_Equality_Op               (N, Ctx_Type);
3355
3356            when N_Op_Ge
3357               | N_Op_Gt
3358               | N_Op_Le
3359               | N_Op_Lt
3360            =>
3361               Resolve_Comparison_Op             (N, Ctx_Type);
3362
3363            when N_Op_Not =>
3364               Resolve_Op_Not                    (N, Ctx_Type);
3365
3366            when N_Op_Add
3367               | N_Op_Divide
3368               | N_Op_Mod
3369               | N_Op_Multiply
3370               | N_Op_Rem
3371               | N_Op_Subtract
3372            =>
3373               Resolve_Arithmetic_Op             (N, Ctx_Type);
3374
3375            when N_Op_Concat =>
3376               Resolve_Op_Concat                 (N, Ctx_Type);
3377
3378            when N_Op_Expon =>
3379               Resolve_Op_Expon                  (N, Ctx_Type);
3380
3381            when N_Op_Abs
3382               | N_Op_Minus
3383               | N_Op_Plus
3384            =>
3385               Resolve_Unary_Op                  (N, Ctx_Type);
3386
3387            when N_Op_Shift =>
3388               Resolve_Shift                     (N, Ctx_Type);
3389
3390            when N_Procedure_Call_Statement =>
3391               Resolve_Call                      (N, Ctx_Type);
3392
3393            when N_Operator_Symbol =>
3394               Resolve_Operator_Symbol           (N, Ctx_Type);
3395
3396            when N_Qualified_Expression =>
3397               Resolve_Qualified_Expression      (N, Ctx_Type);
3398
3399            --  Why is the following null, needs a comment ???
3400
3401            when N_Quantified_Expression =>
3402               null;
3403
3404            when N_Raise_Expression =>
3405               Resolve_Raise_Expression          (N, Ctx_Type);
3406
3407            when N_Raise_xxx_Error =>
3408               Set_Etype (N, Ctx_Type);
3409
3410            when N_Range =>
3411               Resolve_Range                     (N, Ctx_Type);
3412
3413            when N_Real_Literal =>
3414               Resolve_Real_Literal              (N, Ctx_Type);
3415
3416            when N_Reference =>
3417               Resolve_Reference                 (N, Ctx_Type);
3418
3419            when N_Selected_Component =>
3420               Resolve_Selected_Component        (N, Ctx_Type);
3421
3422            when N_Slice =>
3423               Resolve_Slice                     (N, Ctx_Type);
3424
3425            when N_String_Literal =>
3426               Resolve_String_Literal            (N, Ctx_Type);
3427
3428            when N_Target_Name =>
3429               Resolve_Target_Name               (N, Ctx_Type);
3430
3431            when N_Type_Conversion =>
3432               Resolve_Type_Conversion           (N, Ctx_Type);
3433
3434            when N_Unchecked_Expression =>
3435               Resolve_Unchecked_Expression      (N, Ctx_Type);
3436
3437            when N_Unchecked_Type_Conversion =>
3438               Resolve_Unchecked_Type_Conversion (N, Ctx_Type);
3439         end case;
3440
3441         --  Mark relevant use-type and use-package clauses as effective using
3442         --  the original node because constant folding may have occured and
3443         --  removed references that need to be examined.
3444
3445         if Nkind (Original_Node (N)) in N_Op then
3446            Mark_Use_Clauses (Original_Node (N));
3447         end if;
3448
3449         --  Ada 2012 (AI05-0149): Apply an (implicit) conversion to an
3450         --  expression of an anonymous access type that occurs in the context
3451         --  of a named general access type, except when the expression is that
3452         --  of a membership test. This ensures proper legality checking in
3453         --  terms of allowed conversions (expressions that would be illegal to
3454         --  convert implicitly are allowed in membership tests).
3455
3456         if Ada_Version >= Ada_2012
3457           and then Ekind (Base_Type (Ctx_Type)) = E_General_Access_Type
3458           and then Ekind (Etype (N)) = E_Anonymous_Access_Type
3459           and then Nkind (Parent (N)) not in N_Membership_Test
3460         then
3461            Rewrite (N, Convert_To (Ctx_Type, Relocate_Node (N)));
3462            Analyze_And_Resolve (N, Ctx_Type);
3463         end if;
3464
3465         --  If the subexpression was replaced by a non-subexpression, then
3466         --  all we do is to expand it. The only legitimate case we know of
3467         --  is converting procedure call statement to entry call statements,
3468         --  but there may be others, so we are making this test general.
3469
3470         if Nkind (N) not in N_Subexpr then
3471            Debug_A_Exit ("resolving  ", N, "  (done)");
3472            Expand (N);
3473            return;
3474         end if;
3475
3476         --  The expression is definitely NOT overloaded at this point, so
3477         --  we reset the Is_Overloaded flag to avoid any confusion when
3478         --  reanalyzing the node.
3479
3480         Set_Is_Overloaded (N, False);
3481
3482         --  Freeze expression type, entity if it is a name, and designated
3483         --  type if it is an allocator (RM 13.14(10,11,13)).
3484
3485         --  Now that the resolution of the type of the node is complete, and
3486         --  we did not detect an error, we can expand this node. We skip the
3487         --  expand call if we are in a default expression, see section
3488         --  "Handling of Default Expressions" in Sem spec.
3489
3490         Debug_A_Exit ("resolving  ", N, "  (done)");
3491
3492         --  We unconditionally freeze the expression, even if we are in
3493         --  default expression mode (the Freeze_Expression routine tests this
3494         --  flag and only freezes static types if it is set).
3495
3496         --  Ada 2012 (AI05-177): The declaration of an expression function
3497         --  does not cause freezing, but we never reach here in that case.
3498         --  Here we are resolving the corresponding expanded body, so we do
3499         --  need to perform normal freezing.
3500
3501         --  As elsewhere we do not emit freeze node within a generic.
3502
3503         if not Inside_A_Generic then
3504            Freeze_Expression (N);
3505         end if;
3506
3507         --  Now we can do the expansion
3508
3509         Expand (N);
3510      end if;
3511   end Resolve;
3512
3513   -------------
3514   -- Resolve --
3515   -------------
3516
3517   --  Version with check(s) suppressed
3518
3519   procedure Resolve (N : Node_Id; Typ : Entity_Id; Suppress : Check_Id) is
3520   begin
3521      if Suppress = All_Checks then
3522         declare
3523            Sva : constant Suppress_Array := Scope_Suppress.Suppress;
3524         begin
3525            Scope_Suppress.Suppress := (others => True);
3526            Resolve (N, Typ);
3527            Scope_Suppress.Suppress := Sva;
3528         end;
3529
3530      else
3531         declare
3532            Svg : constant Boolean := Scope_Suppress.Suppress (Suppress);
3533         begin
3534            Scope_Suppress.Suppress (Suppress) := True;
3535            Resolve (N, Typ);
3536            Scope_Suppress.Suppress (Suppress) := Svg;
3537         end;
3538      end if;
3539   end Resolve;
3540
3541   -------------
3542   -- Resolve --
3543   -------------
3544
3545   --  Version with implicit type
3546
3547   procedure Resolve (N : Node_Id) is
3548   begin
3549      Resolve (N, Etype (N));
3550   end Resolve;
3551
3552   ---------------------
3553   -- Resolve_Actuals --
3554   ---------------------
3555
3556   procedure Resolve_Actuals (N : Node_Id; Nam : Entity_Id) is
3557      Loc    : constant Source_Ptr := Sloc (N);
3558      A      : Node_Id;
3559      A_Typ  : Entity_Id := Empty; -- init to avoid warning
3560      F      : Entity_Id;
3561      F_Typ  : Entity_Id;
3562      Prev   : Node_Id := Empty;
3563      Orig_A : Node_Id;
3564      Real_F : Entity_Id := Empty; -- init to avoid warning
3565
3566      Real_Subp : Entity_Id;
3567      --  If the subprogram being called is an inherited operation for
3568      --  a formal derived type in an instance, Real_Subp is the subprogram
3569      --  that will be called. It may have different formal names than the
3570      --  operation of the formal in the generic, so after actual is resolved
3571      --  the name of the actual in a named association must carry the name
3572      --  of the actual of the subprogram being called.
3573
3574      procedure Check_Aliased_Parameter;
3575      --  Check rules on aliased parameters and related accessibility rules
3576      --  in (RM 3.10.2 (10.2-10.4)).
3577
3578      procedure Check_Argument_Order;
3579      --  Performs a check for the case where the actuals are all simple
3580      --  identifiers that correspond to the formal names, but in the wrong
3581      --  order, which is considered suspicious and cause for a warning.
3582
3583      procedure Check_Prefixed_Call;
3584      --  If the original node is an overloaded call in prefix notation,
3585      --  insert an 'Access or a dereference as needed over the first actual.
3586      --  Try_Object_Operation has already verified that there is a valid
3587      --  interpretation, but the form of the actual can only be determined
3588      --  once the primitive operation is identified.
3589
3590      procedure Flag_Effectively_Volatile_Objects (Expr : Node_Id);
3591      --  Emit an error concerning the illegal usage of an effectively volatile
3592      --  object for reading in interfering context (SPARK RM 7.1.3(10)).
3593
3594      procedure Insert_Default;
3595      --  If the actual is missing in a call, insert in the actuals list
3596      --  an instance of the default expression. The insertion is always
3597      --  a named association.
3598
3599      function Same_Ancestor (T1, T2 : Entity_Id) return Boolean;
3600      --  Check whether T1 and T2, or their full views, are derived from a
3601      --  common type. Used to enforce the restrictions on array conversions
3602      --  of AI95-00246.
3603
3604      function Static_Concatenation (N : Node_Id) return Boolean;
3605      --  Predicate to determine whether an actual that is a concatenation
3606      --  will be evaluated statically and does not need a transient scope.
3607      --  This must be determined before the actual is resolved and expanded
3608      --  because if needed the transient scope must be introduced earlier.
3609
3610      -----------------------------
3611      -- Check_Aliased_Parameter --
3612      -----------------------------
3613
3614      procedure Check_Aliased_Parameter is
3615         Nominal_Subt : Entity_Id;
3616
3617      begin
3618         if Is_Aliased (F) then
3619            if Is_Tagged_Type (A_Typ) then
3620               null;
3621
3622            elsif Is_Aliased_View (A) then
3623               if Is_Constr_Subt_For_U_Nominal (A_Typ) then
3624                  Nominal_Subt := Base_Type (A_Typ);
3625               else
3626                  Nominal_Subt := A_Typ;
3627               end if;
3628
3629               if Subtypes_Statically_Match (F_Typ, Nominal_Subt) then
3630                  null;
3631
3632               --  In a generic body assume the worst for generic formals:
3633               --  they can have a constrained partial view (AI05-041).
3634
3635               elsif Has_Discriminants (F_Typ)
3636                 and then not Is_Constrained (F_Typ)
3637                 and then not Object_Type_Has_Constrained_Partial_View
3638                                (Typ => F_Typ, Scop => Current_Scope)
3639               then
3640                  null;
3641
3642               else
3643                  Error_Msg_NE ("untagged actual does not statically match "
3644                                & "aliased formal&", A, F);
3645               end if;
3646
3647            else
3648               Error_Msg_NE ("actual for aliased formal& must be "
3649                             & "aliased object", A, F);
3650            end if;
3651
3652            if Ekind (Nam) = E_Procedure then
3653               null;
3654
3655            elsif Ekind (Etype (Nam)) = E_Anonymous_Access_Type then
3656               if Nkind (Parent (N)) = N_Type_Conversion
3657                 and then Type_Access_Level (Etype (Parent (N)))
3658                            < Static_Accessibility_Level (A, Object_Decl_Level)
3659               then
3660                  Error_Msg_N ("aliased actual has wrong accessibility", A);
3661               end if;
3662
3663            elsif Nkind (Parent (N)) = N_Qualified_Expression
3664              and then Nkind (Parent (Parent (N))) = N_Allocator
3665              and then Type_Access_Level (Etype (Parent (Parent (N))))
3666                         < Static_Accessibility_Level (A, Object_Decl_Level)
3667            then
3668               Error_Msg_N
3669                 ("aliased actual in allocator has wrong accessibility", A);
3670            end if;
3671         end if;
3672      end Check_Aliased_Parameter;
3673
3674      --------------------------
3675      -- Check_Argument_Order --
3676      --------------------------
3677
3678      procedure Check_Argument_Order is
3679      begin
3680         --  Nothing to do if no parameters, or original node is neither a
3681         --  function call nor a procedure call statement (happens in the
3682         --  operator-transformed-to-function call case), or the call is to an
3683         --  operator symbol (which is usually in infix form), or the call does
3684         --  not come from source, or this warning is off.
3685
3686         if not Warn_On_Parameter_Order
3687           or else No (Parameter_Associations (N))
3688           or else Nkind (Original_Node (N)) not in N_Subprogram_Call
3689           or else (Nkind (Name (N)) = N_Identifier
3690                     and then Present (Entity (Name (N)))
3691                     and then Nkind (Entity (Name (N))) =
3692                                N_Defining_Operator_Symbol)
3693           or else not Comes_From_Source (N)
3694         then
3695            return;
3696         end if;
3697
3698         declare
3699            Nargs : constant Nat := List_Length (Parameter_Associations (N));
3700
3701         begin
3702            --  Nothing to do if only one parameter
3703
3704            if Nargs < 2 then
3705               return;
3706            end if;
3707
3708            --  Here if at least two arguments
3709
3710            declare
3711               Actuals : array (1 .. Nargs) of Node_Id;
3712               Actual  : Node_Id;
3713               Formal  : Node_Id;
3714
3715               Wrong_Order : Boolean := False;
3716               --  Set True if an out of order case is found
3717
3718            begin
3719               --  Collect identifier names of actuals, fail if any actual is
3720               --  not a simple identifier, and record max length of name.
3721
3722               Actual := First (Parameter_Associations (N));
3723               for J in Actuals'Range loop
3724                  if Nkind (Actual) /= N_Identifier then
3725                     return;
3726                  else
3727                     Actuals (J) := Actual;
3728                     Next (Actual);
3729                  end if;
3730               end loop;
3731
3732               --  If we got this far, all actuals are identifiers and the list
3733               --  of their names is stored in the Actuals array.
3734
3735               Formal := First_Formal (Nam);
3736               for J in Actuals'Range loop
3737
3738                  --  If we ran out of formals, that's odd, probably an error
3739                  --  which will be detected elsewhere, but abandon the search.
3740
3741                  if No (Formal) then
3742                     return;
3743                  end if;
3744
3745                  --  If name matches and is in order OK
3746
3747                  if Chars (Formal) = Chars (Actuals (J)) then
3748                     null;
3749
3750                  else
3751                     --  If no match, see if it is elsewhere in list and if so
3752                     --  flag potential wrong order if type is compatible.
3753
3754                     for K in Actuals'Range loop
3755                        if Chars (Formal) = Chars (Actuals (K))
3756                          and then
3757                            Has_Compatible_Type (Actuals (K), Etype (Formal))
3758                        then
3759                           Wrong_Order := True;
3760                           goto Continue;
3761                        end if;
3762                     end loop;
3763
3764                     --  No match
3765
3766                     return;
3767                  end if;
3768
3769                  <<Continue>> Next_Formal (Formal);
3770               end loop;
3771
3772               --  If Formals left over, also probably an error, skip warning
3773
3774               if Present (Formal) then
3775                  return;
3776               end if;
3777
3778               --  Here we give the warning if something was out of order
3779
3780               if Wrong_Order then
3781                  Error_Msg_N
3782                    ("?.p?actuals for this call may be in wrong order", N);
3783               end if;
3784            end;
3785         end;
3786      end Check_Argument_Order;
3787
3788      -------------------------
3789      -- Check_Prefixed_Call --
3790      -------------------------
3791
3792      procedure Check_Prefixed_Call is
3793         Act    : constant Node_Id   := First_Actual (N);
3794         A_Type : constant Entity_Id := Etype (Act);
3795         F_Type : constant Entity_Id := Etype (First_Formal (Nam));
3796         Orig   : constant Node_Id := Original_Node (N);
3797         New_A  : Node_Id;
3798
3799      begin
3800         --  Check whether the call is a prefixed call, with or without
3801         --  additional actuals.
3802
3803         if Nkind (Orig) = N_Selected_Component
3804           or else
3805             (Nkind (Orig) = N_Indexed_Component
3806               and then Nkind (Prefix (Orig)) = N_Selected_Component
3807               and then Is_Entity_Name (Prefix (Prefix (Orig)))
3808               and then Is_Entity_Name (Act)
3809               and then Chars (Act) = Chars (Prefix (Prefix (Orig))))
3810         then
3811            if Is_Access_Type (A_Type)
3812              and then not Is_Access_Type (F_Type)
3813            then
3814               --  Introduce dereference on object in prefix
3815
3816               New_A :=
3817                 Make_Explicit_Dereference (Sloc (Act),
3818                   Prefix => Relocate_Node (Act));
3819               Rewrite (Act, New_A);
3820               Analyze (Act);
3821
3822            elsif Is_Access_Type (F_Type)
3823              and then not Is_Access_Type (A_Type)
3824            then
3825               --  Introduce an implicit 'Access in prefix
3826
3827               if not Is_Aliased_View (Act) then
3828                  Error_Msg_NE
3829                    ("object in prefixed call to& must be aliased "
3830                     & "(RM 4.1.3 (13 1/2))",
3831                    Prefix (Act), Nam);
3832               end if;
3833
3834               Rewrite (Act,
3835                 Make_Attribute_Reference (Loc,
3836                   Attribute_Name => Name_Access,
3837                   Prefix         => Relocate_Node (Act)));
3838            end if;
3839
3840            Analyze (Act);
3841         end if;
3842      end Check_Prefixed_Call;
3843
3844      ---------------------------------------
3845      -- Flag_Effectively_Volatile_Objects --
3846      ---------------------------------------
3847
3848      procedure Flag_Effectively_Volatile_Objects (Expr : Node_Id) is
3849         function Flag_Object (N : Node_Id) return Traverse_Result;
3850         --  Determine whether arbitrary node N denotes an effectively volatile
3851         --  object for reading and if it does, emit an error.
3852
3853         -----------------
3854         -- Flag_Object --
3855         -----------------
3856
3857         function Flag_Object (N : Node_Id) return Traverse_Result is
3858            Id : Entity_Id;
3859
3860         begin
3861            case Nkind (N) is
3862               --  Do not consider nested function calls because they have
3863               --  already been processed during their own resolution.
3864
3865               when N_Function_Call =>
3866                  return Skip;
3867
3868               when N_Identifier | N_Expanded_Name =>
3869                  Id := Entity (N);
3870
3871                  if Present (Id)
3872                    and then Is_Object (Id)
3873                    and then Is_Effectively_Volatile_For_Reading (Id)
3874                    and then
3875                      not Is_OK_Volatile_Context (Context       => Parent (N),
3876                                                  Obj_Ref       => N,
3877                                                  Check_Actuals => True)
3878                  then
3879                     Error_Msg_N
3880                       ("volatile object cannot appear in this context"
3881                        & " (SPARK RM 7.1.3(10))", N);
3882                  end if;
3883
3884                  return Skip;
3885
3886               when others =>
3887                  return OK;
3888            end case;
3889         end Flag_Object;
3890
3891         procedure Flag_Objects is new Traverse_Proc (Flag_Object);
3892
3893      --  Start of processing for Flag_Effectively_Volatile_Objects
3894
3895      begin
3896         Flag_Objects (Expr);
3897      end Flag_Effectively_Volatile_Objects;
3898
3899      --------------------
3900      -- Insert_Default --
3901      --------------------
3902
3903      procedure Insert_Default is
3904         Actval : Node_Id;
3905         Assoc  : Node_Id;
3906
3907      begin
3908         --  Missing argument in call, nothing to insert
3909
3910         if No (Default_Value (F)) then
3911            return;
3912
3913         else
3914            --  Note that we do a full New_Copy_Tree, so that any associated
3915            --  Itypes are properly copied. This may not be needed any more,
3916            --  but it does no harm as a safety measure. Defaults of a generic
3917            --  formal may be out of bounds of the corresponding actual (see
3918            --  cc1311b) and an additional check may be required.
3919
3920            Actval :=
3921              New_Copy_Tree
3922                (Default_Value (F),
3923                 New_Scope => Current_Scope,
3924                 New_Sloc  => Loc);
3925
3926            --  Propagate dimension information, if any.
3927
3928            Copy_Dimensions (Default_Value (F), Actval);
3929
3930            if Is_Concurrent_Type (Scope (Nam))
3931              and then Has_Discriminants (Scope (Nam))
3932            then
3933               Replace_Actual_Discriminants (N, Actval);
3934            end if;
3935
3936            if Is_Overloadable (Nam)
3937              and then Present (Alias (Nam))
3938            then
3939               if Base_Type (Etype (F)) /= Base_Type (Etype (Actval))
3940                 and then not Is_Tagged_Type (Etype (F))
3941               then
3942                  --  If default is a real literal, do not introduce a
3943                  --  conversion whose effect may depend on the run-time
3944                  --  size of universal real.
3945
3946                  if Nkind (Actval) = N_Real_Literal then
3947                     Set_Etype (Actval, Base_Type (Etype (F)));
3948                  else
3949                     Actval := Unchecked_Convert_To (Etype (F), Actval);
3950                  end if;
3951               end if;
3952
3953               if Is_Scalar_Type (Etype (F)) then
3954                  Enable_Range_Check (Actval);
3955               end if;
3956
3957               Set_Parent (Actval, N);
3958
3959               --  Resolve aggregates with their base type, to avoid scope
3960               --  anomalies: the subtype was first built in the subprogram
3961               --  declaration, and the current call may be nested.
3962
3963               if Nkind (Actval) = N_Aggregate then
3964                  Analyze_And_Resolve (Actval, Etype (F));
3965               else
3966                  Analyze_And_Resolve (Actval, Etype (Actval));
3967               end if;
3968
3969            else
3970               Set_Parent (Actval, N);
3971
3972               --  See note above concerning aggregates
3973
3974               if Nkind (Actval) = N_Aggregate
3975                 and then Has_Discriminants (Etype (Actval))
3976               then
3977                  Analyze_And_Resolve (Actval, Base_Type (Etype (Actval)));
3978
3979               --  Resolve entities with their own type, which may differ from
3980               --  the type of a reference in a generic context (the view
3981               --  swapping mechanism did not anticipate the re-analysis of
3982               --  default values in calls).
3983
3984               elsif Is_Entity_Name (Actval) then
3985                  Analyze_And_Resolve (Actval, Etype (Entity (Actval)));
3986
3987               else
3988                  Analyze_And_Resolve (Actval, Etype (Actval));
3989               end if;
3990            end if;
3991
3992            --  If default is a tag indeterminate function call, propagate tag
3993            --  to obtain proper dispatching.
3994
3995            if Is_Controlling_Formal (F)
3996              and then Nkind (Default_Value (F)) = N_Function_Call
3997            then
3998               Set_Is_Controlling_Actual (Actval);
3999            end if;
4000         end if;
4001
4002         --  If the default expression raises constraint error, then just
4003         --  silently replace it with an N_Raise_Constraint_Error node, since
4004         --  we already gave the warning on the subprogram spec. If node is
4005         --  already a Raise_Constraint_Error leave as is, to prevent loops in
4006         --  the warnings removal machinery.
4007
4008         if Raises_Constraint_Error (Actval)
4009           and then Nkind (Actval) /= N_Raise_Constraint_Error
4010         then
4011            Rewrite (Actval,
4012              Make_Raise_Constraint_Error (Loc,
4013                Reason => CE_Range_Check_Failed));
4014
4015            Set_Raises_Constraint_Error (Actval);
4016            Set_Etype (Actval, Etype (F));
4017         end if;
4018
4019         Assoc :=
4020           Make_Parameter_Association (Loc,
4021             Explicit_Actual_Parameter => Actval,
4022             Selector_Name             => Make_Identifier (Loc, Chars (F)));
4023
4024         --  Case of insertion is first named actual
4025
4026         if No (Prev)
4027           or else Nkind (Parent (Prev)) /= N_Parameter_Association
4028         then
4029            Set_Next_Named_Actual (Assoc, First_Named_Actual (N));
4030            Set_First_Named_Actual (N, Actval);
4031
4032            if No (Prev) then
4033               if No (Parameter_Associations (N)) then
4034                  Set_Parameter_Associations (N, New_List (Assoc));
4035               else
4036                  Append (Assoc, Parameter_Associations (N));
4037               end if;
4038
4039            else
4040               Insert_After (Prev, Assoc);
4041            end if;
4042
4043         --  Case of insertion is not first named actual
4044
4045         else
4046            Set_Next_Named_Actual
4047              (Assoc, Next_Named_Actual (Parent (Prev)));
4048            Set_Next_Named_Actual (Parent (Prev), Actval);
4049            Append (Assoc, Parameter_Associations (N));
4050         end if;
4051
4052         Mark_Rewrite_Insertion (Assoc);
4053         Mark_Rewrite_Insertion (Actval);
4054
4055         Prev := Actval;
4056      end Insert_Default;
4057
4058      -------------------
4059      -- Same_Ancestor --
4060      -------------------
4061
4062      function Same_Ancestor (T1, T2 : Entity_Id) return Boolean is
4063         FT1 : Entity_Id := T1;
4064         FT2 : Entity_Id := T2;
4065
4066      begin
4067         if Is_Private_Type (T1)
4068           and then Present (Full_View (T1))
4069         then
4070            FT1 := Full_View (T1);
4071         end if;
4072
4073         if Is_Private_Type (T2)
4074           and then Present (Full_View (T2))
4075         then
4076            FT2 := Full_View (T2);
4077         end if;
4078
4079         return Root_Type (Base_Type (FT1)) = Root_Type (Base_Type (FT2));
4080      end Same_Ancestor;
4081
4082      --------------------------
4083      -- Static_Concatenation --
4084      --------------------------
4085
4086      function Static_Concatenation (N : Node_Id) return Boolean is
4087      begin
4088         case Nkind (N) is
4089            when N_String_Literal =>
4090               return True;
4091
4092            when N_Op_Concat =>
4093
4094               --  Concatenation is static when both operands are static and
4095               --  the concatenation operator is a predefined one.
4096
4097               return Scope (Entity (N)) = Standard_Standard
4098                        and then
4099                      Static_Concatenation (Left_Opnd (N))
4100                        and then
4101                      Static_Concatenation (Right_Opnd (N));
4102
4103            when others =>
4104               if Is_Entity_Name (N) then
4105                  declare
4106                     Ent : constant Entity_Id := Entity (N);
4107                  begin
4108                     return Ekind (Ent) = E_Constant
4109                              and then Present (Constant_Value (Ent))
4110                              and then
4111                                Is_OK_Static_Expression (Constant_Value (Ent));
4112                  end;
4113
4114               else
4115                  return False;
4116               end if;
4117         end case;
4118      end Static_Concatenation;
4119
4120   --  Start of processing for Resolve_Actuals
4121
4122   begin
4123      Check_Argument_Order;
4124
4125      if Is_Overloadable (Nam)
4126        and then Is_Inherited_Operation (Nam)
4127        and then In_Instance
4128        and then Present (Alias (Nam))
4129        and then Present (Overridden_Operation (Alias (Nam)))
4130      then
4131         Real_Subp := Alias (Nam);
4132      else
4133         Real_Subp := Empty;
4134      end if;
4135
4136      if Present (First_Actual (N)) then
4137         Check_Prefixed_Call;
4138      end if;
4139
4140      A := First_Actual (N);
4141      F := First_Formal (Nam);
4142
4143      if Present (Real_Subp) then
4144         Real_F := First_Formal (Real_Subp);
4145      end if;
4146
4147      while Present (F) loop
4148         if No (A) and then Needs_No_Actuals (Nam) then
4149            null;
4150
4151         --  If we have an error in any actual or formal, indicated by a type
4152         --  of Any_Type, then abandon resolution attempt, and set result type
4153         --  to Any_Type. Skip this if the actual is a Raise_Expression, whose
4154         --  type is imposed from context.
4155
4156         elsif (Present (A) and then Etype (A) = Any_Type)
4157           or else Etype (F) = Any_Type
4158         then
4159            if Nkind (A) /= N_Raise_Expression then
4160               Set_Etype (N, Any_Type);
4161               return;
4162            end if;
4163         end if;
4164
4165         --  Case where actual is present
4166
4167         --  If the actual is an entity, generate a reference to it now. We
4168         --  do this before the actual is resolved, because a formal of some
4169         --  protected subprogram, or a task discriminant, will be rewritten
4170         --  during expansion, and the source entity reference may be lost.
4171
4172         if Present (A)
4173           and then Is_Entity_Name (A)
4174           and then Comes_From_Source (A)
4175         then
4176            --  Annotate the tree by creating a variable reference marker when
4177            --  the actual denotes a variable reference, in case the reference
4178            --  is folded or optimized away. The variable reference marker is
4179            --  automatically saved for later examination by the ABE Processing
4180            --  phase. The status of the reference is set as follows:
4181
4182            --    status   mode
4183            --    read     IN, IN OUT
4184            --    write    IN OUT, OUT
4185
4186            if Needs_Variable_Reference_Marker
4187                 (N        => A,
4188                  Calls_OK => True)
4189            then
4190               Build_Variable_Reference_Marker
4191                 (N     => A,
4192                  Read  => Ekind (F) /= E_Out_Parameter,
4193                  Write => Ekind (F) /= E_In_Parameter);
4194            end if;
4195
4196            Orig_A := Entity (A);
4197
4198            if Present (Orig_A) then
4199               if Is_Formal (Orig_A)
4200                 and then Ekind (F) /= E_In_Parameter
4201               then
4202                  Generate_Reference (Orig_A, A, 'm');
4203
4204               elsif not Is_Overloaded (A) then
4205                  if Ekind (F) /= E_Out_Parameter then
4206                     Generate_Reference (Orig_A, A);
4207
4208                  --  RM 6.4.1(12): For an out parameter that is passed by
4209                  --  copy, the formal parameter object is created, and:
4210
4211                  --  * For an access type, the formal parameter is initialized
4212                  --    from the value of the actual, without checking that the
4213                  --    value satisfies any constraint, any predicate, or any
4214                  --    exclusion of the null value.
4215
4216                  --  * For a scalar type that has the Default_Value aspect
4217                  --    specified, the formal parameter is initialized from the
4218                  --    value of the actual, without checking that the value
4219                  --    satisfies any constraint or any predicate.
4220                  --  I do not understand why this case is included??? this is
4221                  --  not a case where an OUT parameter is treated as IN OUT.
4222
4223                  --  * For a composite type with discriminants or that has
4224                  --    implicit initial values for any subcomponents, the
4225                  --    behavior is as for an in out parameter passed by copy.
4226
4227                  --  Hence for these cases we generate the read reference now
4228                  --  (the write reference will be generated later by
4229                  --   Note_Possible_Modification).
4230
4231                  elsif Is_By_Copy_Type (Etype (F))
4232                    and then
4233                      (Is_Access_Type (Etype (F))
4234                         or else
4235                           (Is_Scalar_Type (Etype (F))
4236                              and then
4237                                Present (Default_Aspect_Value (Etype (F))))
4238                         or else
4239                           (Is_Composite_Type (Etype (F))
4240                              and then (Has_Discriminants (Etype (F))
4241                                         or else Is_Partially_Initialized_Type
4242                                                   (Etype (F)))))
4243                  then
4244                     Generate_Reference (Orig_A, A);
4245                  end if;
4246               end if;
4247            end if;
4248         end if;
4249
4250         if Present (A)
4251           and then (Nkind (Parent (A)) /= N_Parameter_Association
4252                      or else Chars (Selector_Name (Parent (A))) = Chars (F))
4253         then
4254            --  If style checking mode on, check match of formal name
4255
4256            if Style_Check then
4257               if Nkind (Parent (A)) = N_Parameter_Association then
4258                  Check_Identifier (Selector_Name (Parent (A)), F);
4259               end if;
4260            end if;
4261
4262            --  If the formal is Out or In_Out, do not resolve and expand the
4263            --  conversion, because it is subsequently expanded into explicit
4264            --  temporaries and assignments. However, the object of the
4265            --  conversion can be resolved. An exception is the case of tagged
4266            --  type conversion with a class-wide actual. In that case we want
4267            --  the tag check to occur and no temporary will be needed (no
4268            --  representation change can occur) and the parameter is passed by
4269            --  reference, so we go ahead and resolve the type conversion.
4270            --  Another exception is the case of reference to component or
4271            --  subcomponent of a bit-packed array, in which case we want to
4272            --  defer expansion to the point the in and out assignments are
4273            --  performed.
4274
4275            if Ekind (F) /= E_In_Parameter
4276              and then Nkind (A) = N_Type_Conversion
4277              and then not Is_Class_Wide_Type (Etype (Expression (A)))
4278              and then not Is_Interface (Etype (A))
4279            then
4280               declare
4281                  Expr_Typ : constant Entity_Id := Etype (Expression (A));
4282
4283               begin
4284                  --  Check RM 4.6 (24.2/2)
4285
4286                  if Is_Array_Type (Etype (F))
4287                    and then Is_View_Conversion (A)
4288                  then
4289                     --  In a view conversion, the conversion must be legal in
4290                     --  both directions, and thus both component types must be
4291                     --  aliased, or neither (4.6 (8)).
4292
4293                     --  Check RM 4.6 (24.8/2)
4294
4295                     if Has_Aliased_Components (Expr_Typ) /=
4296                        Has_Aliased_Components (Etype (F))
4297                     then
4298                        --  This normally illegal conversion is legal in an
4299                        --  expanded instance body because of RM 12.3(11).
4300                        --  At runtime, conversion must create a new object.
4301
4302                        if not In_Instance then
4303                           Error_Msg_N
4304                             ("both component types in a view conversion must"
4305                              & " be aliased, or neither", A);
4306                        end if;
4307
4308                     --  Check RM 4.6 (24/3)
4309
4310                     elsif not Same_Ancestor (Etype (F), Expr_Typ) then
4311                        --  Check view conv between unrelated by ref array
4312                        --  types.
4313
4314                        if Is_By_Reference_Type (Etype (F))
4315                          or else Is_By_Reference_Type (Expr_Typ)
4316                        then
4317                           Error_Msg_N
4318                             ("view conversion between unrelated by reference "
4319                              & "array types not allowed ('A'I-00246)", A);
4320
4321                        --  In Ada 2005 mode, check view conversion component
4322                        --  type cannot be private, tagged, or volatile. Note
4323                        --  that we only apply this to source conversions. The
4324                        --  generated code can contain conversions which are
4325                        --  not subject to this test, and we cannot extract the
4326                        --  component type in such cases since it is not
4327                        --  present.
4328
4329                        elsif Comes_From_Source (A)
4330                          and then Ada_Version >= Ada_2005
4331                        then
4332                           declare
4333                              Comp_Type : constant Entity_Id :=
4334                                            Component_Type (Expr_Typ);
4335                           begin
4336                              if (Is_Private_Type (Comp_Type)
4337                                    and then not Is_Generic_Type (Comp_Type))
4338                                or else Is_Tagged_Type (Comp_Type)
4339                                or else Is_Volatile (Comp_Type)
4340                              then
4341                                 Error_Msg_N
4342                                   ("component type of a view conversion " &
4343                                    "cannot be private, tagged, or volatile" &
4344                                    " (RM 4.6 (24))",
4345                                    Expression (A));
4346                              end if;
4347                           end;
4348                        end if;
4349                     end if;
4350
4351                  --  AI12-0074 & AI12-0377
4352                  --  Check 6.4.1: If the mode is out, the actual parameter is
4353                  --  a view conversion, and the type of the formal parameter
4354                  --  is a scalar type, then either:
4355                  --    - the target and operand type both do not have the
4356                  --      Default_Value aspect specified; or
4357                  --    - the target and operand type both have the
4358                  --      Default_Value aspect specified, and there shall exist
4359                  --      a type (other than a root numeric type) that is an
4360                  --      ancestor of both the target type and the operand
4361                  --      type.
4362
4363                  elsif Ekind (F) = E_Out_Parameter
4364                    and then Is_Scalar_Type (Etype (F))
4365                  then
4366                     if Has_Default_Aspect (Etype (F)) /=
4367                        Has_Default_Aspect (Expr_Typ)
4368                     then
4369                        Error_Msg_N
4370                          ("view conversion requires Default_Value on both " &
4371                           "types (RM 6.4.1)", A);
4372                     elsif Has_Default_Aspect (Expr_Typ)
4373                       and then not Same_Ancestor (Etype (F), Expr_Typ)
4374                     then
4375                        Error_Msg_N
4376                          ("view conversion between unrelated types with "
4377                           & "Default_Value not allowed (RM 6.4.1)", A);
4378                     end if;
4379                  end if;
4380               end;
4381
4382               --  Resolve expression if conversion is all OK
4383
4384               if (Conversion_OK (A)
4385                    or else Valid_Conversion (A, Etype (A), Expression (A)))
4386                 and then not Is_Ref_To_Bit_Packed_Array (Expression (A))
4387               then
4388                  Resolve (Expression (A));
4389               end if;
4390
4391            --  If the actual is a function call that returns a limited
4392            --  unconstrained object that needs finalization, create a
4393            --  transient scope for it, so that it can receive the proper
4394            --  finalization list.
4395
4396            elsif Expander_Active
4397              and then Nkind (A) = N_Function_Call
4398              and then Is_Limited_Record (Etype (F))
4399              and then not Is_Constrained (Etype (F))
4400              and then (Needs_Finalization (Etype (F))
4401                         or else Has_Task (Etype (F)))
4402            then
4403               Establish_Transient_Scope (A, Manage_Sec_Stack => False);
4404               Resolve (A, Etype (F));
4405
4406            --  A small optimization: if one of the actuals is a concatenation
4407            --  create a block around a procedure call to recover stack space.
4408            --  This alleviates stack usage when several procedure calls in
4409            --  the same statement list use concatenation. We do not perform
4410            --  this wrapping for code statements, where the argument is a
4411            --  static string, and we want to preserve warnings involving
4412            --  sequences of such statements.
4413
4414            elsif Expander_Active
4415              and then Nkind (A) = N_Op_Concat
4416              and then Nkind (N) = N_Procedure_Call_Statement
4417              and then not (Is_Intrinsic_Subprogram (Nam)
4418                             and then Chars (Nam) = Name_Asm)
4419              and then not Static_Concatenation (A)
4420            then
4421               Establish_Transient_Scope (A, Manage_Sec_Stack => False);
4422               Resolve (A, Etype (F));
4423
4424            else
4425               if Nkind (A) = N_Type_Conversion
4426                 and then Is_Array_Type (Etype (F))
4427                 and then not Same_Ancestor (Etype (F), Etype (Expression (A)))
4428                 and then
4429                   (Is_Limited_Type (Etype (F))
4430                     or else Is_Limited_Type (Etype (Expression (A))))
4431               then
4432                  Error_Msg_N
4433                    ("conversion between unrelated limited array types not "
4434                     & "allowed ('A'I-00246)", A);
4435
4436                  if Is_Limited_Type (Etype (F)) then
4437                     Explain_Limited_Type (Etype (F), A);
4438                  end if;
4439
4440                  if Is_Limited_Type (Etype (Expression (A))) then
4441                     Explain_Limited_Type (Etype (Expression (A)), A);
4442                  end if;
4443               end if;
4444
4445               --  (Ada 2005: AI-251): If the actual is an allocator whose
4446               --  directly designated type is a class-wide interface, we build
4447               --  an anonymous access type to use it as the type of the
4448               --  allocator. Later, when the subprogram call is expanded, if
4449               --  the interface has a secondary dispatch table the expander
4450               --  will add a type conversion to force the correct displacement
4451               --  of the pointer.
4452
4453               if Nkind (A) = N_Allocator then
4454                  declare
4455                     DDT : constant Entity_Id :=
4456                             Directly_Designated_Type (Base_Type (Etype (F)));
4457
4458                  begin
4459                     --  Displace the pointer to the object to reference its
4460                     --  secondary dispatch table.
4461
4462                     if Is_Class_Wide_Type (DDT)
4463                       and then Is_Interface (DDT)
4464                     then
4465                        Rewrite (A, Convert_To (Etype (F), Relocate_Node (A)));
4466                        Analyze_And_Resolve (A, Etype (F),
4467                          Suppress => Access_Check);
4468                     end if;
4469
4470                     --  Ada 2005, AI-162:If the actual is an allocator, the
4471                     --  innermost enclosing statement is the master of the
4472                     --  created object. This needs to be done with expansion
4473                     --  enabled only, otherwise the transient scope will not
4474                     --  be removed in the expansion of the wrapped construct.
4475
4476                     if Expander_Active
4477                       and then (Needs_Finalization (DDT)
4478                                  or else Has_Task (DDT))
4479                     then
4480                        Establish_Transient_Scope
4481                          (A, Manage_Sec_Stack => False);
4482                     end if;
4483                  end;
4484
4485                  if Ekind (Etype (F)) = E_Anonymous_Access_Type then
4486                     Check_Restriction (No_Access_Parameter_Allocators, A);
4487                  end if;
4488               end if;
4489
4490               --  (Ada 2005): The call may be to a primitive operation of a
4491               --  tagged synchronized type, declared outside of the type. In
4492               --  this case the controlling actual must be converted to its
4493               --  corresponding record type, which is the formal type. The
4494               --  actual may be a subtype, either because of a constraint or
4495               --  because it is a generic actual, so use base type to locate
4496               --  concurrent type.
4497
4498               F_Typ := Base_Type (Etype (F));
4499
4500               if Is_Tagged_Type (F_Typ)
4501                 and then (Is_Concurrent_Type (F_Typ)
4502                            or else Is_Concurrent_Record_Type (F_Typ))
4503               then
4504                  --  If the actual is overloaded, look for an interpretation
4505                  --  that has a synchronized type.
4506
4507                  if not Is_Overloaded (A) then
4508                     A_Typ := Base_Type (Etype (A));
4509
4510                  else
4511                     declare
4512                        Index : Interp_Index;
4513                        It    : Interp;
4514
4515                     begin
4516                        Get_First_Interp (A, Index, It);
4517                        while Present (It.Typ) loop
4518                           if Is_Concurrent_Type (It.Typ)
4519                             or else Is_Concurrent_Record_Type (It.Typ)
4520                           then
4521                              A_Typ := Base_Type (It.Typ);
4522                              exit;
4523                           end if;
4524
4525                           Get_Next_Interp (Index, It);
4526                        end loop;
4527                     end;
4528                  end if;
4529
4530                  declare
4531                     Full_A_Typ : Entity_Id;
4532
4533                  begin
4534                     if Present (Full_View (A_Typ)) then
4535                        Full_A_Typ := Base_Type (Full_View (A_Typ));
4536                     else
4537                        Full_A_Typ := A_Typ;
4538                     end if;
4539
4540                     --  Tagged synchronized type (case 1): the actual is a
4541                     --  concurrent type.
4542
4543                     if Is_Concurrent_Type (A_Typ)
4544                       and then Corresponding_Record_Type (A_Typ) = F_Typ
4545                     then
4546                        Rewrite (A,
4547                          Unchecked_Convert_To
4548                            (Corresponding_Record_Type (A_Typ), A));
4549                        Resolve (A, Etype (F));
4550
4551                     --  Tagged synchronized type (case 2): the formal is a
4552                     --  concurrent type.
4553
4554                     elsif Ekind (Full_A_Typ) = E_Record_Type
4555                       and then Present
4556                               (Corresponding_Concurrent_Type (Full_A_Typ))
4557                       and then Is_Concurrent_Type (F_Typ)
4558                       and then Present (Corresponding_Record_Type (F_Typ))
4559                       and then Full_A_Typ = Corresponding_Record_Type (F_Typ)
4560                     then
4561                        Resolve (A, Corresponding_Record_Type (F_Typ));
4562
4563                     --  Common case
4564
4565                     else
4566                        Resolve (A, Etype (F));
4567                     end if;
4568                  end;
4569
4570               --  Not a synchronized operation
4571
4572               else
4573                  Resolve (A, Etype (F));
4574               end if;
4575            end if;
4576
4577            A_Typ := Etype (A);
4578            F_Typ := Etype (F);
4579
4580            --  An actual cannot be an untagged formal incomplete type
4581
4582            if Ekind (A_Typ) = E_Incomplete_Type
4583              and then not Is_Tagged_Type (A_Typ)
4584              and then Is_Generic_Type (A_Typ)
4585            then
4586               Error_Msg_N
4587                 ("invalid use of untagged formal incomplete type", A);
4588            end if;
4589
4590            --  has warnings suppressed, then we reset Never_Set_In_Source for
4591            --  the calling entity. The reason for this is to catch cases like
4592            --  GNAT.Spitbol.Patterns.Vstring_Var where the called subprogram
4593            --  uses trickery to modify an IN parameter.
4594
4595            if Ekind (F) = E_In_Parameter
4596              and then Is_Entity_Name (A)
4597              and then Present (Entity (A))
4598              and then Ekind (Entity (A)) = E_Variable
4599              and then Has_Warnings_Off (F_Typ)
4600            then
4601               Set_Never_Set_In_Source (Entity (A), False);
4602            end if;
4603
4604            --  Perform error checks for IN and IN OUT parameters
4605
4606            if Ekind (F) /= E_Out_Parameter then
4607
4608               --  Check unset reference. For scalar parameters, it is clearly
4609               --  wrong to pass an uninitialized value as either an IN or
4610               --  IN-OUT parameter. For composites, it is also clearly an
4611               --  error to pass a completely uninitialized value as an IN
4612               --  parameter, but the case of IN OUT is trickier. We prefer
4613               --  not to give a warning here. For example, suppose there is
4614               --  a routine that sets some component of a record to False.
4615               --  It is perfectly reasonable to make this IN-OUT and allow
4616               --  either initialized or uninitialized records to be passed
4617               --  in this case.
4618
4619               --  For partially initialized composite values, we also avoid
4620               --  warnings, since it is quite likely that we are passing a
4621               --  partially initialized value and only the initialized fields
4622               --  will in fact be read in the subprogram.
4623
4624               if Is_Scalar_Type (A_Typ)
4625                 or else (Ekind (F) = E_In_Parameter
4626                           and then not Is_Partially_Initialized_Type (A_Typ))
4627               then
4628                  Check_Unset_Reference (A);
4629               end if;
4630
4631               --  In Ada 83 we cannot pass an OUT parameter as an IN or IN OUT
4632               --  actual to a nested call, since this constitutes a reading of
4633               --  the parameter, which is not allowed.
4634
4635               if Ada_Version = Ada_83
4636                 and then Is_Entity_Name (A)
4637                 and then Ekind (Entity (A)) = E_Out_Parameter
4638               then
4639                  Error_Msg_N ("(Ada 83) illegal reading of out parameter", A);
4640               end if;
4641            end if;
4642
4643            --  In -gnatd.q mode, forget that a given array is constant when
4644            --  it is passed as an IN parameter to a foreign-convention
4645            --  subprogram. This is in case the subprogram evilly modifies the
4646            --  object. Of course, correct code would use IN OUT.
4647
4648            if Debug_Flag_Dot_Q
4649              and then Ekind (F) = E_In_Parameter
4650              and then Has_Foreign_Convention (Nam)
4651              and then Is_Array_Type (F_Typ)
4652              and then Nkind (A) in N_Has_Entity
4653              and then Present (Entity (A))
4654            then
4655               Set_Is_True_Constant (Entity (A), False);
4656            end if;
4657
4658            --  Case of OUT or IN OUT parameter
4659
4660            if Ekind (F) /= E_In_Parameter then
4661
4662               --  For an Out parameter, check for useless assignment. Note
4663               --  that we can't set Last_Assignment this early, because we may
4664               --  kill current values in Resolve_Call, and that call would
4665               --  clobber the Last_Assignment field.
4666
4667               --  Note: call Warn_On_Useless_Assignment before doing the check
4668               --  below for Is_OK_Variable_For_Out_Formal so that the setting
4669               --  of Referenced_As_LHS/Referenced_As_Out_Formal properly
4670               --  reflects the last assignment, not this one.
4671
4672               if Ekind (F) = E_Out_Parameter then
4673                  if Warn_On_Modified_As_Out_Parameter (F)
4674                    and then Is_Entity_Name (A)
4675                    and then Present (Entity (A))
4676                    and then Comes_From_Source (N)
4677                  then
4678                     Warn_On_Useless_Assignment (Entity (A), A);
4679                  end if;
4680               end if;
4681
4682               --  Validate the form of the actual. Note that the call to
4683               --  Is_OK_Variable_For_Out_Formal generates the required
4684               --  reference in this case.
4685
4686               --  A call to an initialization procedure for an aggregate
4687               --  component may initialize a nested component of a constant
4688               --  designated object. In this context the object is variable.
4689
4690               if not Is_OK_Variable_For_Out_Formal (A)
4691                 and then not Is_Init_Proc (Nam)
4692               then
4693                  Error_Msg_NE ("actual for& must be a variable", A, F);
4694
4695                  if Is_Subprogram (Current_Scope) then
4696                     if Is_Invariant_Procedure (Current_Scope)
4697                       or else Is_Partial_Invariant_Procedure (Current_Scope)
4698                     then
4699                        Error_Msg_N
4700                          ("function used in invariant cannot modify its "
4701                           & "argument", F);
4702
4703                     elsif Is_Predicate_Function (Current_Scope) then
4704                        Error_Msg_N
4705                          ("function used in predicate cannot modify its "
4706                           & "argument", F);
4707                     end if;
4708                  end if;
4709               end if;
4710
4711               --  What's the following about???
4712
4713               if Is_Entity_Name (A) then
4714                  Kill_Checks (Entity (A));
4715               else
4716                  Kill_All_Checks;
4717               end if;
4718            end if;
4719
4720            if A_Typ = Any_Type then
4721               Set_Etype (N, Any_Type);
4722               return;
4723            end if;
4724
4725            --  Apply appropriate constraint/predicate checks for IN [OUT] case
4726
4727            if Ekind (F) in E_In_Parameter | E_In_Out_Parameter then
4728
4729               --  Apply predicate tests except in certain special cases. Note
4730               --  that it might be more consistent to apply these only when
4731               --  expansion is active (in Exp_Ch6.Expand_Actuals), as we do
4732               --  for the outbound predicate tests ??? In any case indicate
4733               --  the function being called, for better warnings if the call
4734               --  leads to an infinite recursion.
4735
4736               if Predicate_Tests_On_Arguments (Nam) then
4737                  Apply_Predicate_Check (A, F_Typ, Nam);
4738               end if;
4739
4740               --  Apply required constraint checks
4741
4742               if Is_Scalar_Type (A_Typ) then
4743                  Apply_Scalar_Range_Check (A, F_Typ);
4744
4745               elsif Is_Array_Type (A_Typ) then
4746                  Apply_Length_Check (A, F_Typ);
4747
4748               elsif Is_Record_Type (F_Typ)
4749                 and then Has_Discriminants (F_Typ)
4750                 and then Is_Constrained (F_Typ)
4751                 and then (not Is_Derived_Type (F_Typ)
4752                            or else Comes_From_Source (Nam))
4753               then
4754                  Apply_Discriminant_Check (A, F_Typ);
4755
4756                  --  For view conversions of a discriminated object, apply
4757                  --  check to object itself, the conversion alreay has the
4758                  --  proper type.
4759
4760                  if Nkind (A) = N_Type_Conversion
4761                    and then Is_Constrained (Etype (Expression (A)))
4762                  then
4763                     Apply_Discriminant_Check (Expression (A), F_Typ);
4764                  end if;
4765
4766               elsif Is_Access_Type (F_Typ)
4767                 and then Is_Array_Type (Designated_Type (F_Typ))
4768                 and then Is_Constrained (Designated_Type (F_Typ))
4769               then
4770                  Apply_Length_Check (A, F_Typ);
4771
4772               elsif Is_Access_Type (F_Typ)
4773                 and then Has_Discriminants (Designated_Type (F_Typ))
4774                 and then Is_Constrained (Designated_Type (F_Typ))
4775               then
4776                  Apply_Discriminant_Check (A, F_Typ);
4777
4778               else
4779                  Apply_Range_Check (A, F_Typ);
4780               end if;
4781
4782               --  Ada 2005 (AI-231): Note that the controlling parameter case
4783               --  already existed in Ada 95, which is partially checked
4784               --  elsewhere (see Checks), and we don't want the warning
4785               --  message to differ.
4786
4787               if Is_Access_Type (F_Typ)
4788                 and then Can_Never_Be_Null (F_Typ)
4789                 and then Known_Null (A)
4790               then
4791                  if Is_Controlling_Formal (F) then
4792                     Apply_Compile_Time_Constraint_Error
4793                       (N      => A,
4794                        Msg    => "null value not allowed here??",
4795                        Reason => CE_Access_Check_Failed);
4796
4797                  elsif Ada_Version >= Ada_2005 then
4798                     Apply_Compile_Time_Constraint_Error
4799                       (N      => A,
4800                        Msg    => "(Ada 2005) NULL not allowed in "
4801                                  & "null-excluding formal??",
4802                        Reason => CE_Null_Not_Allowed);
4803                  end if;
4804               end if;
4805            end if;
4806
4807            --  Checks for OUT parameters and IN OUT parameters
4808
4809            if Ekind (F) in E_Out_Parameter | E_In_Out_Parameter then
4810
4811               --  If there is a type conversion, make sure the return value
4812               --  meets the constraints of the variable before the conversion.
4813
4814               if Nkind (A) = N_Type_Conversion then
4815                  if Is_Scalar_Type (A_Typ) then
4816
4817                     --  Special case here tailored to Exp_Ch6.Is_Legal_Copy,
4818                     --  which would prevent the check from being generated.
4819                     --  This is for Starlet only though, so long obsolete.
4820
4821                     if Mechanism (F) = By_Reference
4822                       and then Ekind (Nam) = E_Procedure
4823                       and then Is_Valued_Procedure (Nam)
4824                     then
4825                        null;
4826                     else
4827                        Apply_Scalar_Range_Check
4828                          (Expression (A), Etype (Expression (A)), A_Typ);
4829                     end if;
4830
4831                     --  In addition the return value must meet the constraints
4832                     --  of the object type (see the comment below).
4833
4834                     Apply_Scalar_Range_Check (A, A_Typ, F_Typ);
4835
4836                  else
4837                     Apply_Range_Check
4838                       (Expression (A), Etype (Expression (A)), A_Typ);
4839                  end if;
4840
4841               --  If no conversion, apply scalar range checks and length check
4842               --  based on the subtype of the actual (NOT that of the formal).
4843               --  This indicates that the check takes place on return from the
4844               --  call. During expansion the required constraint checks are
4845               --  inserted. In GNATprove mode, in the absence of expansion,
4846               --  the flag indicates that the returned value is valid.
4847
4848               else
4849                  if Is_Scalar_Type (F_Typ) then
4850                     Apply_Scalar_Range_Check (A, A_Typ, F_Typ);
4851
4852                  elsif Is_Array_Type (F_Typ)
4853                    and then Ekind (F) = E_Out_Parameter
4854                  then
4855                     Apply_Length_Check (A, F_Typ);
4856
4857                  else
4858                     Apply_Range_Check (A, A_Typ, F_Typ);
4859                  end if;
4860               end if;
4861
4862               --  Note: we do not apply the predicate checks for the case of
4863               --  OUT and IN OUT parameters. They are instead applied in the
4864               --  Expand_Actuals routine in Exp_Ch6.
4865            end if;
4866
4867            --  If the formal is of an unconstrained array subtype with fixed
4868            --  lower bound, then sliding to that bound may be needed.
4869
4870            if Is_Fixed_Lower_Bound_Array_Subtype (F_Typ) then
4871               Expand_Sliding_Conversion (A, F_Typ);
4872            end if;
4873
4874            --  An actual associated with an access parameter is implicitly
4875            --  converted to the anonymous access type of the formal and must
4876            --  satisfy the legality checks for access conversions.
4877
4878            if Ekind (F_Typ) = E_Anonymous_Access_Type then
4879               if not Valid_Conversion (A, F_Typ, A) then
4880                  Error_Msg_N
4881                    ("invalid implicit conversion for access parameter", A);
4882               end if;
4883
4884               --  If the actual is an access selected component of a variable,
4885               --  the call may modify its designated object. It is reasonable
4886               --  to treat this as a potential modification of the enclosing
4887               --  record, to prevent spurious warnings that it should be
4888               --  declared as a constant, because intuitively programmers
4889               --  regard the designated subcomponent as part of the record.
4890
4891               if Nkind (A) = N_Selected_Component
4892                 and then Is_Entity_Name (Prefix (A))
4893                 and then not Is_Constant_Object (Entity (Prefix (A)))
4894               then
4895                  Note_Possible_Modification (A, Sure => False);
4896               end if;
4897            end if;
4898
4899            --  Check illegal cases of atomic/volatile/VFA actual (RM C.6(12))
4900
4901            if (Is_By_Reference_Type (F_Typ) or else Is_Aliased (F))
4902              and then Comes_From_Source (N)
4903            then
4904               if Is_Atomic_Object (A)
4905                 and then not Is_Atomic (F_Typ)
4906               then
4907                  Error_Msg_NE
4908                    ("cannot pass atomic object to nonatomic formal&",
4909                     A, F);
4910                  Error_Msg_N
4911                    ("\which is passed by reference (RM C.6(12))", A);
4912
4913               elsif Is_Volatile_Object_Ref (A)
4914                 and then not Is_Volatile (F_Typ)
4915               then
4916                  Error_Msg_NE
4917                    ("cannot pass volatile object to nonvolatile formal&",
4918                     A, F);
4919                  Error_Msg_N
4920                    ("\which is passed by reference (RM C.6(12))", A);
4921
4922               elsif Is_Volatile_Full_Access_Object_Ref (A)
4923                 and then not Is_Volatile_Full_Access (F_Typ)
4924               then
4925                  Error_Msg_NE
4926                    ("cannot pass full access object to nonfull access "
4927                     & "formal&", A, F);
4928                  Error_Msg_N
4929                    ("\which is passed by reference (RM C.6(12))", A);
4930               end if;
4931
4932               --  Check for nonatomic subcomponent of a full access object
4933               --  in Ada 2022 (RM C.6 (12)).
4934
4935               if Ada_Version >= Ada_2022
4936                 and then Is_Subcomponent_Of_Full_Access_Object (A)
4937                 and then not Is_Atomic_Object (A)
4938               then
4939                  Error_Msg_N
4940                    ("cannot pass nonatomic subcomponent of full access "
4941                     & "object", A);
4942                  Error_Msg_NE
4943                    ("\to formal & which is passed by reference (RM C.6(12))",
4944                     A, F);
4945               end if;
4946            end if;
4947
4948            --  Check that subprograms don't have improper controlling
4949            --  arguments (RM 3.9.2 (9)).
4950
4951            --  A primitive operation may have an access parameter of an
4952            --  incomplete tagged type, but a dispatching call is illegal
4953            --  if the type is still incomplete.
4954
4955            if Is_Controlling_Formal (F) then
4956               Set_Is_Controlling_Actual (A);
4957
4958               if Ekind (F_Typ) = E_Anonymous_Access_Type then
4959                  declare
4960                     Desig : constant Entity_Id := Designated_Type (F_Typ);
4961                  begin
4962                     if Ekind (Desig) = E_Incomplete_Type
4963                       and then No (Full_View (Desig))
4964                       and then No (Non_Limited_View (Desig))
4965                     then
4966                        Error_Msg_NE
4967                          ("premature use of incomplete type& "
4968                           & "in dispatching call", A, Desig);
4969                     end if;
4970                  end;
4971               end if;
4972
4973            elsif Nkind (A) = N_Explicit_Dereference then
4974               Validate_Remote_Access_To_Class_Wide_Type (A);
4975            end if;
4976
4977            --  Apply legality rule 3.9.2  (9/1)
4978
4979            --  Skip this check on helpers and indirect-call wrappers built to
4980            --  support class-wide preconditions.
4981
4982            if (Is_Class_Wide_Type (A_Typ) or else Is_Dynamically_Tagged (A))
4983              and then not Is_Class_Wide_Type (F_Typ)
4984              and then not Is_Controlling_Formal (F)
4985              and then not In_Instance
4986              and then (not Is_Subprogram (Nam)
4987                         or else No (Class_Preconditions_Subprogram (Nam)))
4988            then
4989               Error_Msg_N ("class-wide argument not allowed here!", A);
4990
4991               if Is_Subprogram (Nam) and then Comes_From_Source (Nam) then
4992                  Error_Msg_Node_2 := F_Typ;
4993                  Error_Msg_NE
4994                    ("& is not a dispatching operation of &!", A, Nam);
4995               end if;
4996
4997            --  Apply the checks described in 3.10.2(27): if the context is a
4998            --  specific access-to-object, the actual cannot be class-wide.
4999            --  Use base type to exclude access_to_subprogram cases.
5000
5001            elsif Is_Access_Type (A_Typ)
5002              and then Is_Access_Type (F_Typ)
5003              and then not Is_Access_Subprogram_Type (Base_Type (F_Typ))
5004              and then (Is_Class_Wide_Type (Designated_Type (A_Typ))
5005                         or else (Nkind (A) = N_Attribute_Reference
5006                                   and then
5007                                     Is_Class_Wide_Type (Etype (Prefix (A)))))
5008              and then not Is_Class_Wide_Type (Designated_Type (F_Typ))
5009              and then not Is_Controlling_Formal (F)
5010
5011              --  Disable these checks for call to imported C++ subprograms
5012
5013              and then not
5014                (Is_Entity_Name (Name (N))
5015                  and then Is_Imported (Entity (Name (N)))
5016                  and then Convention (Entity (Name (N))) = Convention_CPP)
5017            then
5018               Error_Msg_N
5019                 ("access to class-wide argument not allowed here!", A);
5020
5021               if Is_Subprogram (Nam) and then Comes_From_Source (Nam) then
5022                  Error_Msg_Node_2 := Designated_Type (F_Typ);
5023                  Error_Msg_NE
5024                    ("& is not a dispatching operation of &!", A, Nam);
5025               end if;
5026            end if;
5027
5028            Check_Aliased_Parameter;
5029
5030            Eval_Actual (A);
5031
5032            --  If it is a named association, treat the selector_name as a
5033            --  proper identifier, and mark the corresponding entity.
5034
5035            if Nkind (Parent (A)) = N_Parameter_Association
5036
5037              --  Ignore reference in SPARK mode, as it refers to an entity not
5038              --  in scope at the point of reference, so the reference should
5039              --  be ignored for computing effects of subprograms.
5040
5041              and then not GNATprove_Mode
5042            then
5043               --  If subprogram is overridden, use name of formal that
5044               --  is being called.
5045
5046               if Present (Real_Subp) then
5047                  Set_Entity (Selector_Name (Parent (A)), Real_F);
5048                  Set_Etype (Selector_Name (Parent (A)), Etype (Real_F));
5049
5050               else
5051                  Set_Entity (Selector_Name (Parent (A)), F);
5052                  Generate_Reference (F, Selector_Name (Parent (A)));
5053                  Set_Etype (Selector_Name (Parent (A)), F_Typ);
5054                  Generate_Reference (F_Typ, N, ' ');
5055               end if;
5056            end if;
5057
5058            Prev := A;
5059
5060            if Ekind (F) /= E_Out_Parameter then
5061               Check_Unset_Reference (A);
5062            end if;
5063
5064            --  The following checks are only relevant when SPARK_Mode is on as
5065            --  they are not standard Ada legality rule. Internally generated
5066            --  temporaries are ignored.
5067
5068            if SPARK_Mode = On and then Comes_From_Source (A) then
5069
5070               --  Inspect the expression and flag each effectively volatile
5071               --  object for reading as illegal because it appears within
5072               --  an interfering context. Note that this is usually done
5073               --  in Resolve_Entity_Name, but when the effectively volatile
5074               --  object for reading appears as an actual in a call, the call
5075               --  must be resolved first.
5076
5077               Flag_Effectively_Volatile_Objects (A);
5078            end if;
5079
5080            --  A formal parameter of a specific tagged type whose related
5081            --  subprogram is subject to pragma Extensions_Visible with value
5082            --  "False" cannot act as an actual in a subprogram with value
5083            --  "True" (SPARK RM 6.1.7(3)).
5084
5085            --  No check needed for helpers and indirect-call wrappers built to
5086            --  support class-wide preconditions.
5087
5088            if Is_EVF_Expression (A)
5089              and then Extensions_Visible_Status (Nam) =
5090                       Extensions_Visible_True
5091              and then No (Class_Preconditions_Subprogram (Current_Scope))
5092            then
5093               Error_Msg_N
5094                 ("formal parameter cannot act as actual parameter when "
5095                  & "Extensions_Visible is False", A);
5096               Error_Msg_NE
5097                 ("\subprogram & has Extensions_Visible True", A, Nam);
5098            end if;
5099
5100            --  The actual parameter of a Ghost subprogram whose formal is of
5101            --  mode IN OUT or OUT must be a Ghost variable (SPARK RM 6.9(12)).
5102
5103            if Comes_From_Source (Nam)
5104              and then Is_Ghost_Entity (Nam)
5105              and then Ekind (F) in E_In_Out_Parameter | E_Out_Parameter
5106              and then Is_Entity_Name (A)
5107              and then Present (Entity (A))
5108              and then not Is_Ghost_Entity (Entity (A))
5109            then
5110               Error_Msg_NE
5111                 ("non-ghost variable & cannot appear as actual in call to "
5112                  & "ghost procedure", A, Entity (A));
5113
5114               if Ekind (F) = E_In_Out_Parameter then
5115                  Error_Msg_N ("\corresponding formal has mode `IN OUT`", A);
5116               else
5117                  Error_Msg_N ("\corresponding formal has mode OUT", A);
5118               end if;
5119            end if;
5120
5121            --  (AI12-0397): The target of a subprogram call that occurs within
5122            --  the expression of an Default_Initial_Condition aspect and has
5123            --  an actual that is the current instance of the type must be
5124            --  either a primitive of the type or a class-wide subprogram,
5125            --  because the type of the current instance in such an aspect is
5126            --  considered to be a notional formal derived type whose only
5127            --  operations correspond to the primitives of the enclosing type.
5128            --  Nonprimitives can be called, but the current instance must be
5129            --  converted rather than passed directly. Note that a current
5130            --  instance of a type with DIC will occur as a reference to an
5131            --  in-mode formal of an enclosing DIC procedure or partial DIC
5132            --  procedure. (It seems that this check should perhaps also apply
5133            --  to calls within Type_Invariant'Class, but not Type_Invariant,
5134            --  aspects???)
5135
5136            if Nkind (A) = N_Identifier
5137              and then Ekind (Entity (A)) = E_In_Parameter
5138
5139              and then Is_Subprogram (Scope (Entity (A)))
5140              and then Is_DIC_Procedure (Scope (Entity (A)))
5141
5142              --  We check Comes_From_Source to exclude inherited primitives
5143              --  from being flagged, because such subprograms turn out to not
5144              --  always have the Is_Primitive flag set. ???
5145
5146              and then Comes_From_Source (Nam)
5147
5148              and then not Is_Primitive (Nam)
5149              and then not Is_Class_Wide_Type (F_Typ)
5150            then
5151               Error_Msg_NE
5152                 ("call to nonprimitive & with current instance not allowed " &
5153                  "for aspect", A, Nam);
5154            end if;
5155
5156            Next_Actual (A);
5157
5158         --  Case where actual is not present
5159
5160         else
5161            Insert_Default;
5162         end if;
5163
5164         Next_Formal (F);
5165
5166         if Present (Real_Subp) then
5167            Next_Formal (Real_F);
5168         end if;
5169      end loop;
5170   end Resolve_Actuals;
5171
5172   -----------------------
5173   -- Resolve_Allocator --
5174   -----------------------
5175
5176   procedure Resolve_Allocator (N : Node_Id; Typ : Entity_Id) is
5177      Desig_T  : constant Entity_Id := Designated_Type (Typ);
5178      E        : constant Node_Id   := Expression (N);
5179      Subtyp   : Entity_Id;
5180      Discrim  : Entity_Id;
5181      Constr   : Node_Id;
5182      Aggr     : Node_Id;
5183      Assoc    : Node_Id := Empty;
5184      Disc_Exp : Node_Id;
5185
5186      procedure Check_Allocator_Discrim_Accessibility
5187        (Disc_Exp  : Node_Id;
5188         Alloc_Typ : Entity_Id);
5189      --  Check that accessibility level associated with an access discriminant
5190      --  initialized in an allocator by the expression Disc_Exp is not deeper
5191      --  than the level of the allocator type Alloc_Typ. An error message is
5192      --  issued if this condition is violated. Specialized checks are done for
5193      --  the cases of a constraint expression which is an access attribute or
5194      --  an access discriminant.
5195
5196      procedure Check_Allocator_Discrim_Accessibility_Exprs
5197        (Curr_Exp  : Node_Id;
5198         Alloc_Typ : Entity_Id);
5199      --  Dispatch checks performed by Check_Allocator_Discrim_Accessibility
5200      --  across all expressions within a given conditional expression.
5201
5202      function In_Dispatching_Context return Boolean;
5203      --  If the allocator is an actual in a call, it is allowed to be class-
5204      --  wide when the context is not because it is a controlling actual.
5205
5206      -------------------------------------------
5207      -- Check_Allocator_Discrim_Accessibility --
5208      -------------------------------------------
5209
5210      procedure Check_Allocator_Discrim_Accessibility
5211        (Disc_Exp  : Node_Id;
5212         Alloc_Typ : Entity_Id)
5213      is
5214      begin
5215         if Type_Access_Level (Etype (Disc_Exp)) >
5216            Deepest_Type_Access_Level (Alloc_Typ)
5217         then
5218            Error_Msg_N
5219              ("operand type has deeper level than allocator type", Disc_Exp);
5220
5221         --  When the expression is an Access attribute the level of the prefix
5222         --  object must not be deeper than that of the allocator's type.
5223
5224         elsif Nkind (Disc_Exp) = N_Attribute_Reference
5225           and then Get_Attribute_Id (Attribute_Name (Disc_Exp)) =
5226                      Attribute_Access
5227           and then Static_Accessibility_Level
5228                      (Disc_Exp, Zero_On_Dynamic_Level)
5229                        > Deepest_Type_Access_Level (Alloc_Typ)
5230         then
5231            Error_Msg_N
5232              ("prefix of attribute has deeper level than allocator type",
5233               Disc_Exp);
5234
5235         --  When the expression is an access discriminant the check is against
5236         --  the level of the prefix object.
5237
5238         elsif Ekind (Etype (Disc_Exp)) = E_Anonymous_Access_Type
5239           and then Nkind (Disc_Exp) = N_Selected_Component
5240           and then Static_Accessibility_Level
5241                      (Disc_Exp, Zero_On_Dynamic_Level)
5242                        > Deepest_Type_Access_Level (Alloc_Typ)
5243         then
5244            Error_Msg_N
5245              ("access discriminant has deeper level than allocator type",
5246               Disc_Exp);
5247
5248         --  All other cases are legal
5249
5250         else
5251            null;
5252         end if;
5253      end Check_Allocator_Discrim_Accessibility;
5254
5255      -------------------------------------------------
5256      -- Check_Allocator_Discrim_Accessibility_Exprs --
5257      -------------------------------------------------
5258
5259      procedure Check_Allocator_Discrim_Accessibility_Exprs
5260        (Curr_Exp  : Node_Id;
5261         Alloc_Typ : Entity_Id)
5262      is
5263         Alt      : Node_Id;
5264         Expr     : Node_Id;
5265         Disc_Exp : constant Node_Id := Original_Node (Curr_Exp);
5266      begin
5267         --  When conditional expressions are constant folded we know at
5268         --  compile time which expression to check - so don't bother with
5269         --  the rest of the cases.
5270
5271         if Nkind (Curr_Exp) = N_Attribute_Reference then
5272            Check_Allocator_Discrim_Accessibility (Curr_Exp, Alloc_Typ);
5273
5274         --  Non-constant-folded if expressions
5275
5276         elsif Nkind (Disc_Exp) = N_If_Expression then
5277            --  Check both expressions if they are still present in the face
5278            --  of expansion.
5279
5280            Expr := Next (First (Expressions (Disc_Exp)));
5281            if Present (Expr) then
5282               Check_Allocator_Discrim_Accessibility_Exprs (Expr, Alloc_Typ);
5283               Next (Expr);
5284               if Present (Expr) then
5285                  Check_Allocator_Discrim_Accessibility_Exprs
5286                    (Expr, Alloc_Typ);
5287               end if;
5288            end if;
5289
5290         --  Non-constant-folded case expressions
5291
5292         elsif Nkind (Disc_Exp) = N_Case_Expression then
5293            --  Check all alternatives
5294
5295            Alt := First (Alternatives (Disc_Exp));
5296            while Present (Alt) loop
5297               Check_Allocator_Discrim_Accessibility_Exprs
5298                 (Expression (Alt), Alloc_Typ);
5299
5300               Next (Alt);
5301            end loop;
5302
5303         --  Base case, check the accessibility of the original node of the
5304         --  expression.
5305
5306         else
5307            Check_Allocator_Discrim_Accessibility (Disc_Exp, Alloc_Typ);
5308         end if;
5309      end Check_Allocator_Discrim_Accessibility_Exprs;
5310
5311      ----------------------------
5312      -- In_Dispatching_Context --
5313      ----------------------------
5314
5315      function In_Dispatching_Context return Boolean is
5316         Par : constant Node_Id := Parent (N);
5317
5318      begin
5319         return Nkind (Par) in N_Subprogram_Call
5320           and then Is_Entity_Name (Name (Par))
5321           and then Is_Dispatching_Operation (Entity (Name (Par)));
5322      end In_Dispatching_Context;
5323
5324   --  Start of processing for Resolve_Allocator
5325
5326   begin
5327      --  Replace general access with specific type
5328
5329      if Ekind (Etype (N)) = E_Allocator_Type then
5330         Set_Etype (N, Base_Type (Typ));
5331      end if;
5332
5333      if Is_Abstract_Type (Typ) then
5334         Error_Msg_N ("type of allocator cannot be abstract",  N);
5335      end if;
5336
5337      --  For qualified expression, resolve the expression using the given
5338      --  subtype (nothing to do for type mark, subtype indication)
5339
5340      if Nkind (E) = N_Qualified_Expression then
5341         if Is_Class_Wide_Type (Etype (E))
5342           and then not Is_Class_Wide_Type (Desig_T)
5343           and then not In_Dispatching_Context
5344         then
5345            Error_Msg_N
5346              ("class-wide allocator not allowed for this access type", N);
5347         end if;
5348
5349         --  Do a full resolution to apply constraint and predicate checks
5350
5351         Resolve_Qualified_Expression (E, Etype (E));
5352         Check_Unset_Reference (Expression (E));
5353
5354         --  Allocators generated by the build-in-place expansion mechanism
5355         --  are explicitly marked as coming from source but do not need to be
5356         --  checked for limited initialization. To exclude this case, ensure
5357         --  that the parent of the allocator is a source node.
5358         --  The return statement constructed for an Expression_Function does
5359         --  not come from source but requires a limited check.
5360
5361         if Is_Limited_Type (Etype (E))
5362           and then Comes_From_Source (N)
5363           and then
5364             (Comes_From_Source (Parent (N))
5365               or else
5366                 (Ekind (Current_Scope) = E_Function
5367                   and then Nkind (Original_Node (Unit_Declaration_Node
5368                              (Current_Scope))) = N_Expression_Function))
5369           and then not In_Instance_Body
5370         then
5371            if not OK_For_Limited_Init (Etype (E), Expression (E)) then
5372               if Nkind (Parent (N)) = N_Assignment_Statement then
5373                  Error_Msg_N
5374                    ("illegal expression for initialized allocator of a "
5375                     & "limited type (RM 7.5 (2.7/2))", N);
5376               else
5377                  Error_Msg_N
5378                    ("initialization not allowed for limited types", N);
5379               end if;
5380
5381               Explain_Limited_Type (Etype (E), N);
5382            end if;
5383         end if;
5384
5385         --  Calls to build-in-place functions are not currently supported in
5386         --  allocators for access types associated with a simple storage pool.
5387         --  Supporting such allocators may require passing additional implicit
5388         --  parameters to build-in-place functions (or a significant revision
5389         --  of the current b-i-p implementation to unify the handling for
5390         --  multiple kinds of storage pools). ???
5391
5392         if Is_Limited_View (Desig_T)
5393           and then Nkind (Expression (E)) = N_Function_Call
5394         then
5395            declare
5396               Pool : constant Entity_Id :=
5397                        Associated_Storage_Pool (Root_Type (Typ));
5398            begin
5399               if Present (Pool)
5400                 and then
5401                   Present (Get_Rep_Pragma
5402                              (Etype (Pool), Name_Simple_Storage_Pool_Type))
5403               then
5404                  Error_Msg_N
5405                    ("limited function calls not yet supported in simple "
5406                     & "storage pool allocators", Expression (E));
5407               end if;
5408            end;
5409         end if;
5410
5411         --  A special accessibility check is needed for allocators that
5412         --  constrain access discriminants. The level of the type of the
5413         --  expression used to constrain an access discriminant cannot be
5414         --  deeper than the type of the allocator (in contrast to access
5415         --  parameters, where the level of the actual can be arbitrary).
5416
5417         --  We can't use Valid_Conversion to perform this check because in
5418         --  general the type of the allocator is unrelated to the type of
5419         --  the access discriminant.
5420
5421         if Ekind (Typ) /= E_Anonymous_Access_Type
5422           or else Is_Local_Anonymous_Access (Typ)
5423         then
5424            Subtyp := Entity (Subtype_Mark (E));
5425
5426            Aggr := Original_Node (Expression (E));
5427
5428            if Has_Discriminants (Subtyp)
5429              and then Nkind (Aggr) in N_Aggregate | N_Extension_Aggregate
5430            then
5431               Discrim := First_Discriminant (Base_Type (Subtyp));
5432
5433               --  Get the first component expression of the aggregate
5434
5435               if Present (Expressions (Aggr)) then
5436                  Disc_Exp := First (Expressions (Aggr));
5437
5438               elsif Present (Component_Associations (Aggr)) then
5439                  Assoc := First (Component_Associations (Aggr));
5440
5441                  if Present (Assoc) then
5442                     Disc_Exp := Expression (Assoc);
5443                  else
5444                     Disc_Exp := Empty;
5445                  end if;
5446
5447               else
5448                  Disc_Exp := Empty;
5449               end if;
5450
5451               while Present (Discrim) and then Present (Disc_Exp) loop
5452                  if Ekind (Etype (Discrim)) = E_Anonymous_Access_Type then
5453                     Check_Allocator_Discrim_Accessibility_Exprs
5454                       (Disc_Exp, Typ);
5455                  end if;
5456
5457                  Next_Discriminant (Discrim);
5458
5459                  if Present (Discrim) then
5460                     if Present (Assoc) then
5461                        Next (Assoc);
5462                        Disc_Exp := Expression (Assoc);
5463
5464                     elsif Present (Next (Disc_Exp)) then
5465                        Next (Disc_Exp);
5466
5467                     else
5468                        Assoc := First (Component_Associations (Aggr));
5469
5470                        if Present (Assoc) then
5471                           Disc_Exp := Expression (Assoc);
5472                        else
5473                           Disc_Exp := Empty;
5474                        end if;
5475                     end if;
5476                  end if;
5477               end loop;
5478            end if;
5479         end if;
5480
5481      --  For a subtype mark or subtype indication, freeze the subtype
5482
5483      else
5484         Freeze_Expression (E);
5485
5486         if Is_Access_Constant (Typ) and then not No_Initialization (N) then
5487            Error_Msg_N
5488              ("initialization required for access-to-constant allocator", N);
5489         end if;
5490
5491         --  A special accessibility check is needed for allocators that
5492         --  constrain access discriminants. The level of the type of the
5493         --  expression used to constrain an access discriminant cannot be
5494         --  deeper than the type of the allocator (in contrast to access
5495         --  parameters, where the level of the actual can be arbitrary).
5496         --  We can't use Valid_Conversion to perform this check because
5497         --  in general the type of the allocator is unrelated to the type
5498         --  of the access discriminant.
5499
5500         if Nkind (Original_Node (E)) = N_Subtype_Indication
5501           and then (Ekind (Typ) /= E_Anonymous_Access_Type
5502                      or else Is_Local_Anonymous_Access (Typ))
5503         then
5504            Subtyp := Entity (Subtype_Mark (Original_Node (E)));
5505
5506            if Has_Discriminants (Subtyp) then
5507               Discrim := First_Discriminant (Base_Type (Subtyp));
5508               Constr := First (Constraints (Constraint (Original_Node (E))));
5509               while Present (Discrim) and then Present (Constr) loop
5510                  if Ekind (Etype (Discrim)) = E_Anonymous_Access_Type then
5511                     if Nkind (Constr) = N_Discriminant_Association then
5512                        Disc_Exp := Expression (Constr);
5513                     else
5514                        Disc_Exp := Constr;
5515                     end if;
5516
5517                     Check_Allocator_Discrim_Accessibility_Exprs
5518                       (Disc_Exp, Typ);
5519                  end if;
5520
5521                  Next_Discriminant (Discrim);
5522                  Next (Constr);
5523               end loop;
5524            end if;
5525         end if;
5526      end if;
5527
5528      --  Ada 2005 (AI-344): A class-wide allocator requires an accessibility
5529      --  check that the level of the type of the created object is not deeper
5530      --  than the level of the allocator's access type, since extensions can
5531      --  now occur at deeper levels than their ancestor types. This is a
5532      --  static accessibility level check; a run-time check is also needed in
5533      --  the case of an initialized allocator with a class-wide argument (see
5534      --  Expand_Allocator_Expression).
5535
5536      if Ada_Version >= Ada_2005
5537        and then Is_Class_Wide_Type (Desig_T)
5538      then
5539         declare
5540            Exp_Typ : Entity_Id;
5541
5542         begin
5543            if Nkind (E) = N_Qualified_Expression then
5544               Exp_Typ := Etype (E);
5545            elsif Nkind (E) = N_Subtype_Indication then
5546               Exp_Typ := Entity (Subtype_Mark (Original_Node (E)));
5547            else
5548               Exp_Typ := Entity (E);
5549            end if;
5550
5551            if Type_Access_Level (Exp_Typ) >
5552                 Deepest_Type_Access_Level (Typ)
5553            then
5554               if In_Instance_Body then
5555                  Error_Msg_Warn := SPARK_Mode /= On;
5556                  Error_Msg_N
5557                    ("type in allocator has deeper level than designated "
5558                     & "class-wide type<<", E);
5559                  Error_Msg_N ("\Program_Error [<<", E);
5560
5561                  Rewrite (N,
5562                    Make_Raise_Program_Error (Sloc (N),
5563                      Reason => PE_Accessibility_Check_Failed));
5564                  Set_Etype (N, Typ);
5565
5566               --  Do not apply Ada 2005 accessibility checks on a class-wide
5567               --  allocator if the type given in the allocator is a formal
5568               --  type or within a formal package. A run-time check will be
5569               --  performed in the instance.
5570
5571               elsif not Is_Generic_Type (Exp_Typ)
5572                 and then not In_Generic_Formal_Package (Exp_Typ)
5573               then
5574                  Error_Msg_N
5575                    ("type in allocator has deeper level than designated "
5576                     & "class-wide type", E);
5577               end if;
5578            end if;
5579         end;
5580      end if;
5581
5582      --  Check for allocation from an empty storage pool. But do not complain
5583      --  if it's a return statement for a build-in-place function, because the
5584      --  allocator is there just in case the caller uses an allocator. If the
5585      --  caller does use an allocator, it will be caught at the call site.
5586
5587      if No_Pool_Assigned (Typ)
5588        and then not Alloc_For_BIP_Return (N)
5589      then
5590         Error_Msg_N ("allocation from empty storage pool!", N);
5591
5592      --  If the context is an unchecked conversion, as may happen within an
5593      --  inlined subprogram, the allocator is being resolved with its own
5594      --  anonymous type. In that case, if the target type has a specific
5595      --  storage pool, it must be inherited explicitly by the allocator type.
5596
5597      elsif Nkind (Parent (N)) = N_Unchecked_Type_Conversion
5598        and then No (Associated_Storage_Pool (Typ))
5599      then
5600         Set_Associated_Storage_Pool
5601           (Typ, Associated_Storage_Pool (Etype (Parent (N))));
5602      end if;
5603
5604      if Ekind (Etype (N)) = E_Anonymous_Access_Type then
5605         Check_Restriction (No_Anonymous_Allocators, N);
5606      end if;
5607
5608      --  Check that an allocator with task parts isn't for a nested access
5609      --  type when restriction No_Task_Hierarchy applies.
5610
5611      if not Is_Library_Level_Entity (Base_Type (Typ))
5612        and then Has_Task (Base_Type (Desig_T))
5613      then
5614         Check_Restriction (No_Task_Hierarchy, N);
5615      end if;
5616
5617      --  An illegal allocator may be rewritten as a raise Program_Error
5618      --  statement.
5619
5620      if Nkind (N) = N_Allocator then
5621
5622         --  Avoid coextension processing for an allocator that is the
5623         --  expansion of a build-in-place function call.
5624
5625         if Nkind (Original_Node (N)) = N_Allocator
5626           and then Nkind (Expression (Original_Node (N))) =
5627                      N_Qualified_Expression
5628           and then Nkind (Expression (Expression (Original_Node (N)))) =
5629                      N_Function_Call
5630           and then Is_Expanded_Build_In_Place_Call
5631                      (Expression (Expression (Original_Node (N))))
5632         then
5633            null; -- b-i-p function call case
5634
5635         else
5636            --  An anonymous access discriminant is the definition of a
5637            --  coextension.
5638
5639            if Ekind (Typ) = E_Anonymous_Access_Type
5640              and then Nkind (Associated_Node_For_Itype (Typ)) =
5641                         N_Discriminant_Specification
5642            then
5643               declare
5644                  Discr : constant Entity_Id :=
5645                    Defining_Identifier (Associated_Node_For_Itype (Typ));
5646
5647               begin
5648                  Check_Restriction (No_Coextensions, N);
5649
5650                  --  Ada 2012 AI05-0052: If the designated type of the
5651                  --  allocator is limited, then the allocator shall not
5652                  --  be used to define the value of an access discriminant
5653                  --  unless the discriminated type is immutably limited.
5654
5655                  if Ada_Version >= Ada_2012
5656                    and then Is_Limited_Type (Desig_T)
5657                    and then not Is_Limited_View (Scope (Discr))
5658                  then
5659                     Error_Msg_N
5660                       ("only immutably limited types can have anonymous "
5661                        & "access discriminants designating a limited type",
5662                        N);
5663                  end if;
5664               end;
5665
5666               --  Avoid marking an allocator as a dynamic coextension if it is
5667               --  within a static construct.
5668
5669               if not Is_Static_Coextension (N) then
5670                  Set_Is_Dynamic_Coextension (N);
5671
5672                  --  Finalization and deallocation of coextensions utilizes an
5673                  --  approximate implementation which does not directly adhere
5674                  --  to the semantic rules. Warn on potential issues involving
5675                  --  coextensions.
5676
5677                  if Is_Controlled (Desig_T) then
5678                     Error_Msg_N
5679                       ("??coextension will not be finalized when its "
5680                        & "associated owner is deallocated or finalized", N);
5681                  else
5682                     Error_Msg_N
5683                       ("??coextension will not be deallocated when its "
5684                        & "associated owner is deallocated", N);
5685                  end if;
5686               end if;
5687
5688            --  Cleanup for potential static coextensions
5689
5690            else
5691               Set_Is_Dynamic_Coextension (N, False);
5692               Set_Is_Static_Coextension  (N, False);
5693
5694               --  Anonymous access-to-controlled objects are not finalized on
5695               --  time because this involves run-time ownership and currently
5696               --  this property is not available. In rare cases the object may
5697               --  not be finalized at all. Warn on potential issues involving
5698               --  anonymous access-to-controlled objects.
5699
5700               if Ekind (Typ) = E_Anonymous_Access_Type
5701                 and then Is_Controlled_Active (Desig_T)
5702               then
5703                  Error_Msg_N
5704                    ("??object designated by anonymous access object might "
5705                     & "not be finalized until its enclosing library unit "
5706                     & "goes out of scope", N);
5707                  Error_Msg_N ("\use named access type instead", N);
5708               end if;
5709            end if;
5710         end if;
5711      end if;
5712
5713      --  Report a simple error: if the designated object is a local task,
5714      --  its body has not been seen yet, and its activation will fail an
5715      --  elaboration check.
5716
5717      if Is_Task_Type (Desig_T)
5718        and then Scope (Base_Type (Desig_T)) = Current_Scope
5719        and then Is_Compilation_Unit (Current_Scope)
5720        and then Ekind (Current_Scope) = E_Package
5721        and then not In_Package_Body (Current_Scope)
5722      then
5723         Error_Msg_Warn := SPARK_Mode /= On;
5724         Error_Msg_N ("cannot activate task before body seen<<", N);
5725         Error_Msg_N ("\Program_Error [<<", N);
5726      end if;
5727
5728      --  Ada 2012 (AI05-0111-3): Detect an attempt to allocate a task or a
5729      --  type with a task component on a subpool. This action must raise
5730      --  Program_Error at runtime.
5731
5732      if Ada_Version >= Ada_2012
5733        and then Nkind (N) = N_Allocator
5734        and then Present (Subpool_Handle_Name (N))
5735        and then Has_Task (Desig_T)
5736      then
5737         Error_Msg_Warn := SPARK_Mode /= On;
5738         Error_Msg_N ("cannot allocate task on subpool<<", N);
5739         Error_Msg_N ("\Program_Error [<<", N);
5740
5741         Rewrite (N,
5742           Make_Raise_Program_Error (Sloc (N),
5743             Reason => PE_Explicit_Raise));
5744         Set_Etype (N, Typ);
5745      end if;
5746   end Resolve_Allocator;
5747
5748   ---------------------------
5749   -- Resolve_Arithmetic_Op --
5750   ---------------------------
5751
5752   --  Used for resolving all arithmetic operators except exponentiation
5753
5754   procedure Resolve_Arithmetic_Op (N : Node_Id; Typ : Entity_Id) is
5755      L   : constant Node_Id := Left_Opnd (N);
5756      R   : constant Node_Id := Right_Opnd (N);
5757      TL  : constant Entity_Id := Base_Type (Etype (L));
5758      TR  : constant Entity_Id := Base_Type (Etype (R));
5759      T   : Entity_Id;
5760      Rop : Node_Id;
5761
5762      B_Typ : constant Entity_Id := Base_Type (Typ);
5763      --  We do the resolution using the base type, because intermediate values
5764      --  in expressions always are of the base type, not a subtype of it.
5765
5766      function Expected_Type_Is_Any_Real (N : Node_Id) return Boolean;
5767      --  Returns True if N is in a context that expects "any real type"
5768
5769      function Is_Integer_Or_Universal (N : Node_Id) return Boolean;
5770      --  Return True iff given type is Integer or universal real/integer
5771
5772      procedure Set_Mixed_Mode_Operand (N : Node_Id; T : Entity_Id);
5773      --  Choose type of integer literal in fixed-point operation to conform
5774      --  to available fixed-point type. T is the type of the other operand,
5775      --  which is needed to determine the expected type of N.
5776
5777      procedure Set_Operand_Type (N : Node_Id);
5778      --  Set operand type to T if universal
5779
5780      -------------------------------
5781      -- Expected_Type_Is_Any_Real --
5782      -------------------------------
5783
5784      function Expected_Type_Is_Any_Real (N : Node_Id) return Boolean is
5785      begin
5786         --  N is the expression after "delta" in a fixed_point_definition;
5787         --  see RM-3.5.9(6):
5788
5789         return Nkind (Parent (N)) in N_Ordinary_Fixed_Point_Definition
5790                                    | N_Decimal_Fixed_Point_Definition
5791
5792         --  N is one of the bounds in a real_range_specification;
5793         --  see RM-3.5.7(5):
5794
5795                                    | N_Real_Range_Specification
5796
5797         --  N is the expression of a delta_constraint;
5798         --  see RM-J.3(3):
5799
5800                                    | N_Delta_Constraint;
5801      end Expected_Type_Is_Any_Real;
5802
5803      -----------------------------
5804      -- Is_Integer_Or_Universal --
5805      -----------------------------
5806
5807      function Is_Integer_Or_Universal (N : Node_Id) return Boolean is
5808         T     : Entity_Id;
5809         Index : Interp_Index;
5810         It    : Interp;
5811
5812      begin
5813         if not Is_Overloaded (N) then
5814            T := Etype (N);
5815            return Base_Type (T) = Base_Type (Standard_Integer)
5816              or else Is_Universal_Numeric_Type (T);
5817         else
5818            Get_First_Interp (N, Index, It);
5819            while Present (It.Typ) loop
5820               if Base_Type (It.Typ) = Base_Type (Standard_Integer)
5821                 or else Is_Universal_Numeric_Type (It.Typ)
5822               then
5823                  return True;
5824               end if;
5825
5826               Get_Next_Interp (Index, It);
5827            end loop;
5828         end if;
5829
5830         return False;
5831      end Is_Integer_Or_Universal;
5832
5833      ----------------------------
5834      -- Set_Mixed_Mode_Operand --
5835      ----------------------------
5836
5837      procedure Set_Mixed_Mode_Operand (N : Node_Id; T : Entity_Id) is
5838         Index : Interp_Index;
5839         It    : Interp;
5840
5841      begin
5842         if Universal_Interpretation (N) = Universal_Integer then
5843
5844            --  A universal integer literal is resolved as standard integer
5845            --  except in the case of a fixed-point result, where we leave it
5846            --  as universal (to be handled by Exp_Fixd later on)
5847
5848            if Is_Fixed_Point_Type (T) then
5849               Resolve (N, Universal_Integer);
5850            else
5851               Resolve (N, Standard_Integer);
5852            end if;
5853
5854         elsif Universal_Interpretation (N) = Universal_Real
5855           and then (T = Base_Type (Standard_Integer)
5856                      or else Is_Universal_Numeric_Type (T))
5857         then
5858            --  A universal real can appear in a fixed-type context. We resolve
5859            --  the literal with that context, even though this might raise an
5860            --  exception prematurely (the other operand may be zero).
5861
5862            Resolve (N, B_Typ);
5863
5864         elsif Etype (N) = Base_Type (Standard_Integer)
5865           and then T = Universal_Real
5866           and then Is_Overloaded (N)
5867         then
5868            --  Integer arg in mixed-mode operation. Resolve with universal
5869            --  type, in case preference rule must be applied.
5870
5871            Resolve (N, Universal_Integer);
5872
5873         elsif Etype (N) = T and then B_Typ /= Universal_Fixed then
5874
5875            --  If the operand is part of a fixed multiplication operation,
5876            --  a conversion will be applied to each operand, so resolve it
5877            --  with its own type.
5878
5879            if Nkind (Parent (N)) in N_Op_Divide | N_Op_Multiply then
5880               Resolve (N);
5881
5882            else
5883               --  Not a mixed-mode operation, resolve with context
5884
5885               Resolve (N, B_Typ);
5886            end if;
5887
5888         elsif Etype (N) = Any_Fixed then
5889
5890            --  N may itself be a mixed-mode operation, so use context type
5891
5892            Resolve (N, B_Typ);
5893
5894         elsif Is_Fixed_Point_Type (T)
5895           and then B_Typ = Universal_Fixed
5896           and then Is_Overloaded (N)
5897         then
5898            --  Must be (fixed * fixed) operation, operand must have one
5899            --  compatible interpretation.
5900
5901            Resolve (N, Any_Fixed);
5902
5903         elsif Is_Fixed_Point_Type (B_Typ)
5904           and then (T = Universal_Real or else Is_Fixed_Point_Type (T))
5905           and then Is_Overloaded (N)
5906         then
5907            --  C * F(X) in a fixed context, where C is a real literal or a
5908            --  fixed-point expression. F must have either a fixed type
5909            --  interpretation or an integer interpretation, but not both.
5910
5911            Get_First_Interp (N, Index, It);
5912            while Present (It.Typ) loop
5913               if Base_Type (It.Typ) = Base_Type (Standard_Integer) then
5914                  if Analyzed (N) then
5915                     Error_Msg_N ("ambiguous operand in fixed operation", N);
5916                  else
5917                     Resolve (N, Standard_Integer);
5918                  end if;
5919
5920               elsif Is_Fixed_Point_Type (It.Typ) then
5921                  if Analyzed (N) then
5922                     Error_Msg_N ("ambiguous operand in fixed operation", N);
5923                  else
5924                     Resolve (N, It.Typ);
5925                  end if;
5926               end if;
5927
5928               Get_Next_Interp (Index, It);
5929            end loop;
5930
5931            --  Reanalyze the literal with the fixed type of the context. If
5932            --  context is Universal_Fixed, we are within a conversion, leave
5933            --  the literal as a universal real because there is no usable
5934            --  fixed type, and the target of the conversion plays no role in
5935            --  the resolution.
5936
5937            declare
5938               Op2 : Node_Id;
5939               T2  : Entity_Id;
5940
5941            begin
5942               if N = L then
5943                  Op2 := R;
5944               else
5945                  Op2 := L;
5946               end if;
5947
5948               if B_Typ = Universal_Fixed
5949                  and then Nkind (Op2) = N_Real_Literal
5950               then
5951                  T2 := Universal_Real;
5952               else
5953                  T2 := B_Typ;
5954               end if;
5955
5956               Set_Analyzed (Op2, False);
5957               Resolve (Op2, T2);
5958            end;
5959
5960         --  A universal real conditional expression can appear in a fixed-type
5961         --  context and must be resolved with that context to facilitate the
5962         --  code generation in the back end. However, If the context is
5963         --  Universal_fixed (i.e. as an operand of a multiplication/division
5964         --  involving a fixed-point operand) the conditional expression must
5965         --  resolve to a unique visible fixed_point type, normally Duration.
5966
5967         elsif Nkind (N) in N_Case_Expression | N_If_Expression
5968           and then Etype (N) = Universal_Real
5969           and then Is_Fixed_Point_Type (B_Typ)
5970         then
5971            if B_Typ = Universal_Fixed then
5972               Resolve (N, Unique_Fixed_Point_Type (N));
5973
5974            else
5975               Resolve (N, B_Typ);
5976            end if;
5977
5978         else
5979            Resolve (N);
5980         end if;
5981      end Set_Mixed_Mode_Operand;
5982
5983      ----------------------
5984      -- Set_Operand_Type --
5985      ----------------------
5986
5987      procedure Set_Operand_Type (N : Node_Id) is
5988      begin
5989         if Is_Universal_Numeric_Type (Etype (N)) then
5990            Set_Etype (N, T);
5991         end if;
5992      end Set_Operand_Type;
5993
5994   --  Start of processing for Resolve_Arithmetic_Op
5995
5996   begin
5997      if Comes_From_Source (N)
5998        and then Ekind (Entity (N)) = E_Function
5999        and then Is_Imported (Entity (N))
6000        and then Is_Intrinsic_Subprogram (Entity (N))
6001      then
6002         Resolve_Intrinsic_Operator (N, Typ);
6003         return;
6004
6005      --  Special-case for mixed-mode universal expressions or fixed point type
6006      --  operation: each argument is resolved separately. The same treatment
6007      --  is required if one of the operands of a fixed point operation is
6008      --  universal real, since in this case we don't do a conversion to a
6009      --  specific fixed-point type (instead the expander handles the case).
6010
6011      --  Set the type of the node to its universal interpretation because
6012      --  legality checks on an exponentiation operand need the context.
6013
6014      elsif Is_Universal_Numeric_Type (B_Typ)
6015        and then Present (Universal_Interpretation (L))
6016        and then Present (Universal_Interpretation (R))
6017      then
6018         Set_Etype (N, B_Typ);
6019         Resolve (L, Universal_Interpretation (L));
6020         Resolve (R, Universal_Interpretation (R));
6021
6022      elsif (B_Typ = Universal_Real
6023              or else Etype (N) = Universal_Fixed
6024              or else (Etype (N) = Any_Fixed
6025                        and then Is_Fixed_Point_Type (B_Typ))
6026              or else (Is_Fixed_Point_Type (B_Typ)
6027                        and then (Is_Integer_Or_Universal (L)
6028                                    or else
6029                                  Is_Integer_Or_Universal (R))))
6030        and then Nkind (N) in N_Op_Multiply | N_Op_Divide
6031      then
6032         if TL = Universal_Integer or else TR = Universal_Integer then
6033            Check_For_Visible_Operator (N, B_Typ);
6034         end if;
6035
6036         --  If context is a fixed type and one operand is integer, the other
6037         --  is resolved with the type of the context.
6038
6039         if Is_Fixed_Point_Type (B_Typ)
6040           and then (Base_Type (TL) = Base_Type (Standard_Integer)
6041                      or else TL = Universal_Integer)
6042         then
6043            Resolve (R, B_Typ);
6044            Resolve (L, TL);
6045
6046         elsif Is_Fixed_Point_Type (B_Typ)
6047           and then (Base_Type (TR) = Base_Type (Standard_Integer)
6048                      or else TR = Universal_Integer)
6049         then
6050            Resolve (L, B_Typ);
6051            Resolve (R, TR);
6052
6053         --  If both operands are universal and the context is a floating
6054         --  point type, the operands are resolved to the type of the context.
6055
6056         elsif Is_Floating_Point_Type (B_Typ) then
6057            Resolve (L, B_Typ);
6058            Resolve (R, B_Typ);
6059
6060         else
6061            Set_Mixed_Mode_Operand (L, TR);
6062            Set_Mixed_Mode_Operand (R, TL);
6063         end if;
6064
6065         --  Check the rule in RM05-4.5.5(19.1/2) disallowing universal_fixed
6066         --  multiplying operators from being used when the expected type is
6067         --  also universal_fixed. Note that B_Typ will be Universal_Fixed in
6068         --  some cases where the expected type is actually Any_Real;
6069         --  Expected_Type_Is_Any_Real takes care of that case.
6070
6071         if Etype (N) = Universal_Fixed
6072           or else Etype (N) = Any_Fixed
6073         then
6074            if B_Typ = Universal_Fixed
6075              and then not Expected_Type_Is_Any_Real (N)
6076              and then Nkind (Parent (N)) not in
6077                         N_Type_Conversion | N_Unchecked_Type_Conversion
6078            then
6079               Error_Msg_N ("type cannot be determined from context!", N);
6080               Error_Msg_N ("\explicit conversion to result type required", N);
6081
6082               Set_Etype (L, Any_Type);
6083               Set_Etype (R, Any_Type);
6084
6085            else
6086               if Ada_Version = Ada_83
6087                 and then Etype (N) = Universal_Fixed
6088                 and then Nkind (Parent (N)) not in
6089                            N_Type_Conversion | N_Unchecked_Type_Conversion
6090               then
6091                  Error_Msg_N
6092                    ("(Ada 83) fixed-point operation needs explicit "
6093                     & "conversion", N);
6094               end if;
6095
6096               --  The expected type is "any real type" in contexts like
6097
6098               --    type T is delta <universal_fixed-expression> ...
6099
6100               --  in which case we need to set the type to Universal_Real
6101               --  so that static expression evaluation will work properly.
6102
6103               if Expected_Type_Is_Any_Real (N) then
6104                  Set_Etype (N, Universal_Real);
6105               else
6106                  Set_Etype (N, B_Typ);
6107               end if;
6108            end if;
6109
6110         elsif Is_Fixed_Point_Type (B_Typ)
6111           and then (Is_Integer_Or_Universal (L)
6112                       or else Nkind (L) = N_Real_Literal
6113                       or else Nkind (R) = N_Real_Literal
6114                       or else Is_Integer_Or_Universal (R))
6115         then
6116            Set_Etype (N, B_Typ);
6117
6118         elsif Etype (N) = Any_Fixed then
6119
6120            --  If no previous errors, this is only possible if one operand is
6121            --  overloaded and the context is universal. Resolve as such.
6122
6123            Set_Etype (N, B_Typ);
6124         end if;
6125
6126      else
6127         if Is_Universal_Numeric_Type (TL)
6128               and then
6129            Is_Universal_Numeric_Type (TR)
6130         then
6131            Check_For_Visible_Operator (N, B_Typ);
6132         end if;
6133
6134         --  If the context is Universal_Fixed and the operands are also
6135         --  universal fixed, this is an error, unless there is only one
6136         --  applicable fixed_point type (usually Duration).
6137
6138         if B_Typ = Universal_Fixed and then Etype (L) = Universal_Fixed then
6139            T := Unique_Fixed_Point_Type (N);
6140
6141            if T  = Any_Type then
6142               Set_Etype (N, T);
6143               return;
6144            else
6145               Resolve (L, T);
6146               Resolve (R, T);
6147            end if;
6148
6149         else
6150            Resolve (L, B_Typ);
6151            Resolve (R, B_Typ);
6152         end if;
6153
6154         --  If one of the arguments was resolved to a non-universal type.
6155         --  label the result of the operation itself with the same type.
6156         --  Do the same for the universal argument, if any.
6157
6158         T := Intersect_Types (L, R);
6159         Set_Etype (N, Base_Type (T));
6160         Set_Operand_Type (L);
6161         Set_Operand_Type (R);
6162      end if;
6163
6164      Generate_Operator_Reference (N, Typ);
6165      Analyze_Dimension (N);
6166      Eval_Arithmetic_Op (N);
6167
6168      --  Set overflow and division checking bit
6169
6170      if Nkind (N) in N_Op then
6171         if not Overflow_Checks_Suppressed (Etype (N)) then
6172            Enable_Overflow_Check (N);
6173         end if;
6174
6175         --  Give warning if explicit division by zero
6176
6177         if Nkind (N) in N_Op_Divide | N_Op_Rem | N_Op_Mod
6178           and then not Division_Checks_Suppressed (Etype (N))
6179         then
6180            Rop := Right_Opnd (N);
6181
6182            if Compile_Time_Known_Value (Rop)
6183              and then ((Is_Integer_Type (Etype (Rop))
6184                          and then Expr_Value (Rop) = Uint_0)
6185                         or else
6186                           (Is_Real_Type (Etype (Rop))
6187                             and then Expr_Value_R (Rop) = Ureal_0))
6188            then
6189               --  Specialize the warning message according to the operation.
6190               --  When SPARK_Mode is On, force a warning instead of an error
6191               --  in that case, as this likely corresponds to deactivated
6192               --  code. The following warnings are for the case
6193
6194               case Nkind (N) is
6195                  when N_Op_Divide =>
6196
6197                     --  For division, we have two cases, for float division
6198                     --  of an unconstrained float type, on a machine where
6199                     --  Machine_Overflows is false, we don't get an exception
6200                     --  at run-time, but rather an infinity or Nan. The Nan
6201                     --  case is pretty obscure, so just warn about infinities.
6202
6203                     if Is_Floating_Point_Type (Typ)
6204                       and then not Is_Constrained (Typ)
6205                       and then not Machine_Overflows_On_Target
6206                     then
6207                        Error_Msg_N
6208                          ("float division by zero, may generate "
6209                           & "'+'/'- infinity??", Right_Opnd (N));
6210
6211                     --  For all other cases, we get a Constraint_Error
6212
6213                     else
6214                        Apply_Compile_Time_Constraint_Error
6215                          (N, "division by zero??", CE_Divide_By_Zero,
6216                           Loc  => Sloc (Right_Opnd (N)),
6217                           Warn => SPARK_Mode = On);
6218                     end if;
6219
6220                  when N_Op_Rem =>
6221                     Apply_Compile_Time_Constraint_Error
6222                       (N, "rem with zero divisor??", CE_Divide_By_Zero,
6223                        Loc  => Sloc (Right_Opnd (N)),
6224                        Warn => SPARK_Mode = On);
6225
6226                  when N_Op_Mod =>
6227                     Apply_Compile_Time_Constraint_Error
6228                       (N, "mod with zero divisor??", CE_Divide_By_Zero,
6229                        Loc  => Sloc (Right_Opnd (N)),
6230                        Warn => SPARK_Mode = On);
6231
6232                  --  Division by zero can only happen with division, rem,
6233                  --  and mod operations.
6234
6235                  when others =>
6236                     raise Program_Error;
6237               end case;
6238
6239            --  Otherwise just set the flag to check at run time
6240
6241            else
6242               Activate_Division_Check (N);
6243            end if;
6244         end if;
6245
6246         --  If Restriction No_Implicit_Conditionals is active, then it is
6247         --  violated if either operand can be negative for mod, or for rem
6248         --  if both operands can be negative.
6249
6250         if Restriction_Check_Required (No_Implicit_Conditionals)
6251           and then Nkind (N) in N_Op_Rem | N_Op_Mod
6252         then
6253            declare
6254               Lo : Uint;
6255               Hi : Uint;
6256               OK : Boolean;
6257
6258               LNeg : Boolean;
6259               RNeg : Boolean;
6260               --  Set if corresponding operand might be negative
6261
6262            begin
6263               Determine_Range
6264                 (Left_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
6265               LNeg := (not OK) or else Lo < 0;
6266
6267               Determine_Range
6268                 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
6269               RNeg := (not OK) or else Lo < 0;
6270
6271               --  Check if we will be generating conditionals. There are two
6272               --  cases where that can happen, first for REM, the only case
6273               --  is largest negative integer mod -1, where the division can
6274               --  overflow, but we still have to give the right result. The
6275               --  front end generates a test for this annoying case. Here we
6276               --  just test if both operands can be negative (that's what the
6277               --  expander does, so we match its logic here).
6278
6279               --  The second case is mod where either operand can be negative.
6280               --  In this case, the back end has to generate additional tests.
6281
6282               if (Nkind (N) = N_Op_Rem and then (LNeg and RNeg))
6283                     or else
6284                  (Nkind (N) = N_Op_Mod and then (LNeg or RNeg))
6285               then
6286                  Check_Restriction (No_Implicit_Conditionals, N);
6287               end if;
6288            end;
6289         end if;
6290      end if;
6291
6292      Check_Unset_Reference (L);
6293      Check_Unset_Reference (R);
6294   end Resolve_Arithmetic_Op;
6295
6296   ------------------
6297   -- Resolve_Call --
6298   ------------------
6299
6300   procedure Resolve_Call (N : Node_Id; Typ : Entity_Id) is
6301      Loc      : constant Source_Ptr := Sloc (N);
6302      Subp     : constant Node_Id    := Name (N);
6303      Body_Id  : Entity_Id;
6304      I        : Interp_Index;
6305      It       : Interp;
6306      Nam      : Entity_Id;
6307      Nam_Decl : Node_Id;
6308      Nam_UA   : Entity_Id;
6309      Norm_OK  : Boolean;
6310      Rtype    : Entity_Id;
6311      Scop     : Entity_Id;
6312
6313   begin
6314      --  Preserve relevant elaboration-related attributes of the context which
6315      --  are no longer available or very expensive to recompute once analysis,
6316      --  resolution, and expansion are over.
6317
6318      Mark_Elaboration_Attributes
6319        (N_Id     => N,
6320         Checks   => True,
6321         Modes    => True,
6322         Warnings => True);
6323
6324      --  The context imposes a unique interpretation with type Typ on a
6325      --  procedure or function call. Find the entity of the subprogram that
6326      --  yields the expected type, and propagate the corresponding formal
6327      --  constraints on the actuals. The caller has established that an
6328      --  interpretation exists, and emitted an error if not unique.
6329
6330      --  First deal with the case of a call to an access-to-subprogram,
6331      --  dereference made explicit in Analyze_Call.
6332
6333      if Ekind (Etype (Subp)) = E_Subprogram_Type then
6334         if not Is_Overloaded (Subp) then
6335            Nam := Etype (Subp);
6336
6337         else
6338            --  Find the interpretation whose type (a subprogram type) has a
6339            --  return type that is compatible with the context. Analysis of
6340            --  the node has established that one exists.
6341
6342            Nam := Empty;
6343
6344            Get_First_Interp (Subp,  I, It);
6345            while Present (It.Typ) loop
6346               if Covers (Typ, Etype (It.Typ)) then
6347                  Nam := It.Typ;
6348                  exit;
6349               end if;
6350
6351               Get_Next_Interp (I, It);
6352            end loop;
6353
6354            if No (Nam) then
6355               raise Program_Error;
6356            end if;
6357         end if;
6358
6359         --  If the prefix is not an entity, then resolve it
6360
6361         if not Is_Entity_Name (Subp) then
6362            Resolve (Subp, Nam);
6363         end if;
6364
6365         --  For an indirect call, we always invalidate checks, since we do not
6366         --  know whether the subprogram is local or global. Yes we could do
6367         --  better here, e.g. by knowing that there are no local subprograms,
6368         --  but it does not seem worth the effort. Similarly, we kill all
6369         --  knowledge of current constant values.
6370
6371         Kill_Current_Values;
6372
6373      --  If this is a procedure call which is really an entry call, do
6374      --  the conversion of the procedure call to an entry call. Protected
6375      --  operations use the same circuitry because the name in the call
6376      --  can be an arbitrary expression with special resolution rules.
6377
6378      elsif Nkind (Subp) in N_Selected_Component | N_Indexed_Component
6379        or else (Is_Entity_Name (Subp) and then Is_Entry (Entity (Subp)))
6380      then
6381         Resolve_Entry_Call (N, Typ);
6382
6383         if Legacy_Elaboration_Checks then
6384            Check_Elab_Call (N);
6385         end if;
6386
6387         --  Annotate the tree by creating a call marker in case the original
6388         --  call is transformed by expansion. The call marker is automatically
6389         --  saved for later examination by the ABE Processing phase.
6390
6391         Build_Call_Marker (N);
6392
6393         --  Kill checks and constant values, as above for indirect case
6394         --  Who knows what happens when another task is activated?
6395
6396         Kill_Current_Values;
6397         return;
6398
6399      --  Normal subprogram call with name established in Resolve
6400
6401      elsif not Is_Type (Entity (Subp)) then
6402         Nam := Entity (Subp);
6403         Set_Entity_With_Checks (Subp, Nam);
6404
6405      --  Otherwise we must have the case of an overloaded call
6406
6407      else
6408         pragma Assert (Is_Overloaded (Subp));
6409
6410         --  Initialize Nam to prevent warning (we know it will be assigned
6411         --  in the loop below, but the compiler does not know that).
6412
6413         Nam := Empty;
6414
6415         Get_First_Interp (Subp,  I, It);
6416         while Present (It.Typ) loop
6417            if Covers (Typ, It.Typ) then
6418               Nam := It.Nam;
6419               Set_Entity_With_Checks (Subp, Nam);
6420               exit;
6421            end if;
6422
6423            Get_Next_Interp (I, It);
6424         end loop;
6425      end if;
6426
6427      --  Check that a call to Current_Task does not occur in an entry body
6428
6429      if Is_RTE (Nam, RE_Current_Task) then
6430         declare
6431            P : Node_Id;
6432
6433         begin
6434            P := N;
6435            loop
6436               P := Parent (P);
6437
6438               --  Exclude calls that occur within the default of a formal
6439               --  parameter of the entry, since those are evaluated outside
6440               --  of the body.
6441
6442               exit when No (P) or else Nkind (P) = N_Parameter_Specification;
6443
6444               if Nkind (P) = N_Entry_Body
6445                 or else (Nkind (P) = N_Subprogram_Body
6446                           and then Is_Entry_Barrier_Function (P))
6447               then
6448                  Rtype := Etype (N);
6449                  Error_Msg_Warn := SPARK_Mode /= On;
6450                  Error_Msg_NE
6451                    ("& should not be used in entry body (RM C.7(17))<<",
6452                     N, Nam);
6453                  Error_Msg_NE ("\Program_Error [<<", N, Nam);
6454                  Rewrite (N,
6455                    Make_Raise_Program_Error (Loc,
6456                      Reason => PE_Current_Task_In_Entry_Body));
6457                  Set_Etype (N, Rtype);
6458                  return;
6459               end if;
6460            end loop;
6461         end;
6462      end if;
6463
6464      --  Check that a procedure call does not occur in the context of the
6465      --  entry call statement of a conditional or timed entry call. Note that
6466      --  the case of a call to a subprogram renaming of an entry will also be
6467      --  rejected. The test for N not being an N_Entry_Call_Statement is
6468      --  defensive, covering the possibility that the processing of entry
6469      --  calls might reach this point due to later modifications of the code
6470      --  above.
6471
6472      if Nkind (Parent (N)) = N_Entry_Call_Alternative
6473        and then Nkind (N) /= N_Entry_Call_Statement
6474        and then Entry_Call_Statement (Parent (N)) = N
6475      then
6476         if Ada_Version < Ada_2005 then
6477            Error_Msg_N ("entry call required in select statement", N);
6478
6479         --  Ada 2005 (AI-345): If a procedure_call_statement is used
6480         --  for a procedure_or_entry_call, the procedure_name or
6481         --  procedure_prefix of the procedure_call_statement shall denote
6482         --  an entry renamed by a procedure, or (a view of) a primitive
6483         --  subprogram of a limited interface whose first parameter is
6484         --  a controlling parameter.
6485
6486         elsif Nkind (N) = N_Procedure_Call_Statement
6487           and then not Is_Renamed_Entry (Nam)
6488           and then not Is_Controlling_Limited_Procedure (Nam)
6489         then
6490            Error_Msg_N
6491             ("entry call or dispatching primitive of interface required", N);
6492         end if;
6493      end if;
6494
6495      --  Check that this is not a call to a protected procedure or entry from
6496      --  within a protected function.
6497
6498      Check_Internal_Protected_Use (N, Nam);
6499
6500      --  Freeze the subprogram name if not in a spec-expression. Note that
6501      --  we freeze procedure calls as well as function calls. Procedure calls
6502      --  are not frozen according to the rules (RM 13.14(14)) because it is
6503      --  impossible to have a procedure call to a non-frozen procedure in
6504      --  pure Ada, but in the code that we generate in the expander, this
6505      --  rule needs extending because we can generate procedure calls that
6506      --  need freezing.
6507
6508      --  In Ada 2012, expression functions may be called within pre/post
6509      --  conditions of subsequent functions or expression functions. Such
6510      --  calls do not freeze when they appear within generated bodies,
6511      --  (including the body of another expression function) which would
6512      --  place the freeze node in the wrong scope. An expression function
6513      --  is frozen in the usual fashion, by the appearance of a real body,
6514      --  or at the end of a declarative part. However an implicit call to
6515      --  an expression function may appear when it is part of a default
6516      --  expression in a call to an initialization procedure, and must be
6517      --  frozen now, even if the body is inserted at a later point.
6518      --  Otherwise, the call freezes the expression if expander is active,
6519      --  for example as part of an object declaration.
6520
6521      if Is_Entity_Name (Subp)
6522        and then not In_Spec_Expression
6523        and then not Is_Expression_Function_Or_Completion (Current_Scope)
6524        and then
6525          (not Is_Expression_Function_Or_Completion (Entity (Subp))
6526            or else Expander_Active)
6527      then
6528         if Is_Expression_Function (Entity (Subp)) then
6529
6530            --  Force freeze of expression function in call
6531
6532            Set_Comes_From_Source (Subp, True);
6533            Set_Must_Not_Freeze   (Subp, False);
6534         end if;
6535
6536         Freeze_Expression (Subp);
6537      end if;
6538
6539      --  For a predefined operator, the type of the result is the type imposed
6540      --  by context, except for a predefined operation on universal fixed.
6541      --  Otherwise the type of the call is the type returned by the subprogram
6542      --  being called.
6543
6544      if Is_Predefined_Op (Nam) then
6545         if Etype (N) /= Universal_Fixed then
6546            Set_Etype (N, Typ);
6547         end if;
6548
6549      --  If the subprogram returns an array type, and the context requires the
6550      --  component type of that array type, the node is really an indexing of
6551      --  the parameterless call. Resolve as such. A pathological case occurs
6552      --  when the type of the component is an access to the array type. In
6553      --  this case the call is truly ambiguous. If the call is to an intrinsic
6554      --  subprogram, it can't be an indexed component. This check is necessary
6555      --  because if it's Unchecked_Conversion, and we have "type T_Ptr is
6556      --  access T;" and "type T is array (...) of T_Ptr;" (i.e. an array of
6557      --  pointers to the same array), the compiler gets confused and does an
6558      --  infinite recursion.
6559
6560      elsif (Needs_No_Actuals (Nam) or else Needs_One_Actual (Nam))
6561        and then
6562          ((Is_Array_Type (Etype (Nam))
6563             and then Covers (Typ, Component_Type (Etype (Nam))))
6564           or else
6565             (Is_Access_Type (Etype (Nam))
6566               and then Is_Array_Type (Designated_Type (Etype (Nam)))
6567               and then
6568                 Covers (Typ, Component_Type (Designated_Type (Etype (Nam))))
6569               and then not Is_Intrinsic_Subprogram (Entity (Subp))))
6570      then
6571         declare
6572            Index_Node : Node_Id;
6573            New_Subp   : Node_Id;
6574            Ret_Type   : constant Entity_Id := Etype (Nam);
6575
6576         begin
6577            --  If this is a parameterless call there is no ambiguity and the
6578            --  call has the type of the function.
6579
6580            if No (First_Actual (N)) then
6581               Set_Etype (N, Etype (Nam));
6582
6583               if Present (First_Formal (Nam)) then
6584                  Resolve_Actuals (N, Nam);
6585               end if;
6586
6587               --  Annotate the tree by creating a call marker in case the
6588               --  original call is transformed by expansion. The call marker
6589               --  is automatically saved for later examination by the ABE
6590               --  Processing phase.
6591
6592               Build_Call_Marker (N);
6593
6594            elsif Is_Access_Type (Ret_Type)
6595
6596              and then Ret_Type = Component_Type (Designated_Type (Ret_Type))
6597            then
6598               Error_Msg_N
6599                 ("cannot disambiguate function call and indexing", N);
6600            else
6601               New_Subp := Relocate_Node (Subp);
6602
6603               --  The called entity may be an explicit dereference, in which
6604               --  case there is no entity to set.
6605
6606               if Nkind (New_Subp) /= N_Explicit_Dereference then
6607                  Set_Entity (Subp, Nam);
6608               end if;
6609
6610               if (Is_Array_Type (Ret_Type)
6611                    and then Component_Type (Ret_Type) /= Any_Type)
6612                 or else
6613                  (Is_Access_Type (Ret_Type)
6614                    and then
6615                      Component_Type (Designated_Type (Ret_Type)) /= Any_Type)
6616               then
6617                  if Needs_No_Actuals (Nam) then
6618
6619                     --  Indexed call to a parameterless function
6620
6621                     Index_Node :=
6622                       Make_Indexed_Component (Loc,
6623                         Prefix      =>
6624                           Make_Function_Call (Loc, Name => New_Subp),
6625                         Expressions => Parameter_Associations (N));
6626                  else
6627                     --  An Ada 2005 prefixed call to a primitive operation
6628                     --  whose first parameter is the prefix. This prefix was
6629                     --  prepended to the parameter list, which is actually a
6630                     --  list of indexes. Remove the prefix in order to build
6631                     --  the proper indexed component.
6632
6633                     Index_Node :=
6634                       Make_Indexed_Component (Loc,
6635                         Prefix      =>
6636                           Make_Function_Call (Loc,
6637                             Name                   => New_Subp,
6638                             Parameter_Associations =>
6639                               New_List
6640                                 (Remove_Head (Parameter_Associations (N)))),
6641                         Expressions => Parameter_Associations (N));
6642                  end if;
6643
6644                  --  Preserve the parenthesis count of the node
6645
6646                  Set_Paren_Count (Index_Node, Paren_Count (N));
6647
6648                  --  Since we are correcting a node classification error made
6649                  --  by the parser, we call Replace rather than Rewrite.
6650
6651                  Replace (N, Index_Node);
6652
6653                  Set_Etype (Prefix (N), Ret_Type);
6654                  Set_Etype (N, Typ);
6655
6656                  if Legacy_Elaboration_Checks then
6657                     Check_Elab_Call (Prefix (N));
6658                  end if;
6659
6660                  --  Annotate the tree by creating a call marker in case
6661                  --  the original call is transformed by expansion. The call
6662                  --  marker is automatically saved for later examination by
6663                  --  the ABE Processing phase.
6664
6665                  Build_Call_Marker (Prefix (N));
6666
6667                  Resolve_Indexed_Component (N, Typ);
6668               end if;
6669            end if;
6670
6671            return;
6672         end;
6673
6674      else
6675         --  If the called function is not declared in the main unit and it
6676         --  returns the limited view of type then use the available view (as
6677         --  is done in Try_Object_Operation) to prevent back-end confusion;
6678         --  for the function entity itself. The call must appear in a context
6679         --  where the nonlimited view is available. If the function entity is
6680         --  in the extended main unit then no action is needed, because the
6681         --  back end handles this case. In either case the type of the call
6682         --  is the nonlimited view.
6683
6684         if From_Limited_With (Etype (Nam))
6685           and then Present (Available_View (Etype (Nam)))
6686         then
6687            Set_Etype (N, Available_View (Etype (Nam)));
6688
6689            if not In_Extended_Main_Code_Unit (Nam) then
6690               Set_Etype (Nam, Available_View (Etype (Nam)));
6691            end if;
6692
6693         else
6694            Set_Etype (N, Etype (Nam));
6695         end if;
6696      end if;
6697
6698      --  In the case where the call is to an overloaded subprogram, Analyze
6699      --  calls Normalize_Actuals once per overloaded subprogram. Therefore in
6700      --  such a case Normalize_Actuals needs to be called once more to order
6701      --  the actuals correctly. Otherwise the call will have the ordering
6702      --  given by the last overloaded subprogram whether this is the correct
6703      --  one being called or not.
6704
6705      if Is_Overloaded (Subp) then
6706         Normalize_Actuals (N, Nam, False, Norm_OK);
6707         pragma Assert (Norm_OK);
6708      end if;
6709
6710      --  In any case, call is fully resolved now. Reset Overload flag, to
6711      --  prevent subsequent overload resolution if node is analyzed again
6712
6713      Set_Is_Overloaded (Subp, False);
6714      Set_Is_Overloaded (N, False);
6715
6716      --  A Ghost entity must appear in a specific context
6717
6718      if Is_Ghost_Entity (Nam) and then Comes_From_Source (N) then
6719         Check_Ghost_Context (Nam, N);
6720      end if;
6721
6722      --  If we are calling the current subprogram from immediately within its
6723      --  body, then that is the case where we can sometimes detect cases of
6724      --  infinite recursion statically. Do not try this in case restriction
6725      --  No_Recursion is in effect anyway, and do it only for source calls.
6726
6727      if Comes_From_Source (N) then
6728         Scop := Current_Scope;
6729
6730         --  Issue warning for possible infinite recursion in the absence
6731         --  of the No_Recursion restriction.
6732
6733         if Same_Or_Aliased_Subprograms (Nam, Scop)
6734           and then not Restriction_Active (No_Recursion)
6735           and then not Is_Static_Function (Scop)
6736           and then Check_Infinite_Recursion (N)
6737         then
6738            --  Here we detected and flagged an infinite recursion, so we do
6739            --  not need to test the case below for further warnings. Also we
6740            --  are all done if we now have a raise SE node.
6741
6742            if Nkind (N) = N_Raise_Storage_Error then
6743               return;
6744            end if;
6745
6746         --  If call is to immediately containing subprogram, then check for
6747         --  the case of a possible run-time detectable infinite recursion.
6748
6749         else
6750            Scope_Loop : while Scop /= Standard_Standard loop
6751               if Same_Or_Aliased_Subprograms (Nam, Scop) then
6752
6753                  --  Ada 2022 (AI12-0075): Static functions are never allowed
6754                  --  to make a recursive call, as specified by 6.8(5.4/5).
6755
6756                  if Is_Static_Function (Scop) then
6757                     Error_Msg_N
6758                       ("recursive call not allowed in static expression "
6759                          & "function", N);
6760
6761                     Set_Error_Posted (Scop);
6762
6763                     exit Scope_Loop;
6764                  end if;
6765
6766                  --  Although in general case, recursion is not statically
6767                  --  checkable, the case of calling an immediately containing
6768                  --  subprogram is easy to catch.
6769
6770                  if not Is_Ignored_Ghost_Entity (Nam) then
6771                     Check_Restriction (No_Recursion, N);
6772                  end if;
6773
6774                  --  If the recursive call is to a parameterless subprogram,
6775                  --  then even if we can't statically detect infinite
6776                  --  recursion, this is pretty suspicious, and we output a
6777                  --  warning. Furthermore, we will try later to detect some
6778                  --  cases here at run time by expanding checking code (see
6779                  --  Detect_Infinite_Recursion in package Exp_Ch6).
6780
6781                  --  If the recursive call is within a handler, do not emit a
6782                  --  warning, because this is a common idiom: loop until input
6783                  --  is correct, catch illegal input in handler and restart.
6784
6785                  if No (First_Formal (Nam))
6786                    and then Etype (Nam) = Standard_Void_Type
6787                    and then not Error_Posted (N)
6788                    and then Nkind (Parent (N)) /= N_Exception_Handler
6789                  then
6790                     --  For the case of a procedure call. We give the message
6791                     --  only if the call is the first statement in a sequence
6792                     --  of statements, or if all previous statements are
6793                     --  simple assignments. This is simply a heuristic to
6794                     --  decrease false positives, without losing too many good
6795                     --  warnings. The idea is that these previous statements
6796                     --  may affect global variables the procedure depends on.
6797                     --  We also exclude raise statements, that may arise from
6798                     --  constraint checks and are probably unrelated to the
6799                     --  intended control flow.
6800
6801                     if Nkind (N) = N_Procedure_Call_Statement
6802                       and then Is_List_Member (N)
6803                     then
6804                        declare
6805                           P : Node_Id;
6806                        begin
6807                           P := Prev (N);
6808                           while Present (P) loop
6809                              if Nkind (P) not in N_Assignment_Statement
6810                                                | N_Raise_Constraint_Error
6811                              then
6812                                 exit Scope_Loop;
6813                              end if;
6814
6815                              Prev (P);
6816                           end loop;
6817                        end;
6818                     end if;
6819
6820                     --  Do not give warning if we are in a conditional context
6821
6822                     declare
6823                        K : constant Node_Kind := Nkind (Parent (N));
6824                     begin
6825                        if (K = N_Loop_Statement
6826                             and then Present (Iteration_Scheme (Parent (N))))
6827                          or else K = N_If_Statement
6828                          or else K = N_Elsif_Part
6829                          or else K = N_Case_Statement_Alternative
6830                        then
6831                           exit Scope_Loop;
6832                        end if;
6833                     end;
6834
6835                     --  Here warning is to be issued
6836
6837                     Set_Has_Recursive_Call (Nam);
6838                     Error_Msg_Warn := SPARK_Mode /= On;
6839                     Error_Msg_N ("possible infinite recursion<<!", N);
6840                     Error_Msg_N ("\Storage_Error ]<<!", N);
6841                  end if;
6842
6843                  exit Scope_Loop;
6844               end if;
6845
6846               Scop := Scope (Scop);
6847            end loop Scope_Loop;
6848         end if;
6849      end if;
6850
6851      --  Check obsolescent reference to Ada.Characters.Handling subprogram
6852
6853      Check_Obsolescent_2005_Entity (Nam, Subp);
6854
6855      --  If subprogram name is a predefined operator, it was given in
6856      --  functional notation. Replace call node with operator node, so
6857      --  that actuals can be resolved appropriately.
6858
6859      if Is_Predefined_Op (Nam) or else Ekind (Nam) = E_Operator then
6860         Make_Call_Into_Operator (N, Typ, Entity (Name (N)));
6861         return;
6862
6863      elsif Present (Alias (Nam))
6864        and then Is_Predefined_Op (Alias (Nam))
6865      then
6866         Resolve_Actuals (N, Nam);
6867         Make_Call_Into_Operator (N, Typ, Alias (Nam));
6868         return;
6869      end if;
6870
6871      --  Create a transient scope if the resulting type requires it
6872
6873      --  There are several notable exceptions:
6874
6875      --  a) In init procs, the transient scope overhead is not needed, and is
6876      --  even incorrect when the call is a nested initialization call for a
6877      --  component whose expansion may generate adjust calls. However, if the
6878      --  call is some other procedure call within an initialization procedure
6879      --  (for example a call to Create_Task in the init_proc of the task
6880      --  run-time record) a transient scope must be created around this call.
6881
6882      --  b) Enumeration literal pseudo-calls need no transient scope
6883
6884      --  c) Intrinsic subprograms (Unchecked_Conversion and source info
6885      --  functions) do not use the secondary stack even though the return
6886      --  type may be unconstrained.
6887
6888      --  d) Calls to a build-in-place function, since such functions may
6889      --  allocate their result directly in a target object, and cases where
6890      --  the result does get allocated in the secondary stack are checked for
6891      --  within the specialized Exp_Ch6 procedures for expanding those
6892      --  build-in-place calls.
6893
6894      --  e) Calls to inlinable expression functions do not use the secondary
6895      --  stack (since the call will be replaced by its returned object).
6896
6897      --  f) If the subprogram is marked Inline_Always, then even if it returns
6898      --  an unconstrained type the call does not require use of the secondary
6899      --  stack. However, inlining will only take place if the body to inline
6900      --  is already present. It may not be available if e.g. the subprogram is
6901      --  declared in a child instance.
6902
6903      --  g) If the subprogram is a static expression function and the call is
6904      --  a static call (the actuals are all static expressions), then we never
6905      --  want to create a transient scope (this could occur in the case of a
6906      --  static string-returning call).
6907
6908      if Is_Inlined (Nam)
6909        and then Has_Pragma_Inline (Nam)
6910        and then Nkind (Unit_Declaration_Node (Nam)) = N_Subprogram_Declaration
6911        and then Present (Body_To_Inline (Unit_Declaration_Node (Nam)))
6912      then
6913         null;
6914
6915      elsif Ekind (Nam) = E_Enumeration_Literal
6916        or else Is_Build_In_Place_Function (Nam)
6917        or else Is_Intrinsic_Subprogram (Nam)
6918        or else Is_Inlinable_Expression_Function (Nam)
6919        or else Is_Static_Function_Call (N)
6920      then
6921         null;
6922
6923      --  A return statement from an ignored Ghost function does not use the
6924      --  secondary stack (or any other one).
6925
6926      elsif Expander_Active
6927        and then Ekind (Nam) in E_Function | E_Subprogram_Type
6928        and then Requires_Transient_Scope (Etype (Nam))
6929        and then not Is_Ignored_Ghost_Entity (Nam)
6930      then
6931         Establish_Transient_Scope (N, Manage_Sec_Stack => True);
6932
6933         --  If the call appears within the bounds of a loop, it will be
6934         --  rewritten and reanalyzed, nothing left to do here.
6935
6936         if Nkind (N) /= N_Function_Call then
6937            return;
6938         end if;
6939      end if;
6940
6941      --  A protected function cannot be called within the definition of the
6942      --  enclosing protected type, unless it is part of a pre/postcondition
6943      --  on another protected operation. This may appear in the entry wrapper
6944      --  created for an entry with preconditions.
6945
6946      if Is_Protected_Type (Scope (Nam))
6947        and then In_Open_Scopes (Scope (Nam))
6948        and then not Has_Completion (Scope (Nam))
6949        and then not In_Spec_Expression
6950        and then not Is_Entry_Wrapper (Current_Scope)
6951      then
6952         Error_Msg_NE
6953           ("& cannot be called before end of protected definition", N, Nam);
6954      end if;
6955
6956      --  Propagate interpretation to actuals, and add default expressions
6957      --  where needed.
6958
6959      if Present (First_Formal (Nam)) then
6960         Resolve_Actuals (N, Nam);
6961
6962      --  Overloaded literals are rewritten as function calls, for purpose of
6963      --  resolution. After resolution, we can replace the call with the
6964      --  literal itself.
6965
6966      elsif Ekind (Nam) = E_Enumeration_Literal then
6967         Copy_Node (Subp, N);
6968         Resolve_Entity_Name (N, Typ);
6969
6970         --  Avoid validation, since it is a static function call
6971
6972         Generate_Reference (Nam, Subp);
6973         return;
6974      end if;
6975
6976      --  If the subprogram is not global, then kill all saved values and
6977      --  checks. This is a bit conservative, since in many cases we could do
6978      --  better, but it is not worth the effort. Similarly, we kill constant
6979      --  values. However we do not need to do this for internal entities
6980      --  (unless they are inherited user-defined subprograms), since they
6981      --  are not in the business of molesting local values.
6982
6983      --  If the flag Suppress_Value_Tracking_On_Calls is set, then we also
6984      --  kill all checks and values for calls to global subprograms. This
6985      --  takes care of the case where an access to a local subprogram is
6986      --  taken, and could be passed directly or indirectly and then called
6987      --  from almost any context.
6988
6989      --  Note: we do not do this step till after resolving the actuals. That
6990      --  way we still take advantage of the current value information while
6991      --  scanning the actuals.
6992
6993      --  We suppress killing values if we are processing the nodes associated
6994      --  with N_Freeze_Entity nodes. Otherwise the declaration of a tagged
6995      --  type kills all the values as part of analyzing the code that
6996      --  initializes the dispatch tables.
6997
6998      if Inside_Freezing_Actions = 0
6999        and then (not Is_Library_Level_Entity (Nam)
7000                   or else Suppress_Value_Tracking_On_Call
7001                             (Nearest_Dynamic_Scope (Current_Scope)))
7002        and then (Comes_From_Source (Nam)
7003                   or else (Present (Alias (Nam))
7004                             and then Comes_From_Source (Alias (Nam))))
7005      then
7006         Kill_Current_Values;
7007      end if;
7008
7009      --  If we are warning about unread OUT parameters, this is the place to
7010      --  set Last_Assignment for OUT and IN OUT parameters. We have to do this
7011      --  after the above call to Kill_Current_Values (since that call clears
7012      --  the Last_Assignment field of all local variables).
7013
7014      if (Warn_On_Modified_Unread or Warn_On_All_Unread_Out_Parameters)
7015        and then Comes_From_Source (N)
7016        and then In_Extended_Main_Source_Unit (N)
7017      then
7018         declare
7019            F : Entity_Id;
7020            A : Node_Id;
7021
7022         begin
7023            F := First_Formal (Nam);
7024            A := First_Actual (N);
7025            while Present (F) and then Present (A) loop
7026               if Ekind (F) in E_Out_Parameter | E_In_Out_Parameter
7027                 and then Warn_On_Modified_As_Out_Parameter (F)
7028                 and then Is_Entity_Name (A)
7029                 and then Present (Entity (A))
7030                 and then Comes_From_Source (N)
7031                 and then Safe_To_Capture_Value (N, Entity (A))
7032               then
7033                  Set_Last_Assignment (Entity (A), A);
7034               end if;
7035
7036               Next_Formal (F);
7037               Next_Actual (A);
7038            end loop;
7039         end;
7040      end if;
7041
7042      --  If the subprogram is a primitive operation, check whether or not
7043      --  it is a correct dispatching call.
7044
7045      if Is_Overloadable (Nam)
7046        and then Is_Dispatching_Operation (Nam)
7047      then
7048         Check_Dispatching_Call (N);
7049
7050      elsif Ekind (Nam) /= E_Subprogram_Type
7051        and then Is_Abstract_Subprogram (Nam)
7052        and then not In_Instance
7053      then
7054         Error_Msg_NE ("cannot call abstract subprogram &!", N, Nam);
7055      end if;
7056
7057      --  If this is a dispatching call, generate the appropriate reference,
7058      --  for better source navigation in GNAT Studio.
7059
7060      if Is_Overloadable (Nam)
7061        and then Present (Controlling_Argument (N))
7062      then
7063         Generate_Reference (Nam, Subp, 'R');
7064
7065      --  Normal case, not a dispatching call: generate a call reference
7066
7067      else
7068         Generate_Reference (Nam, Subp, 's');
7069      end if;
7070
7071      if Is_Intrinsic_Subprogram (Nam) then
7072         Check_Intrinsic_Call (N);
7073      end if;
7074
7075      --  Check for violation of restriction No_Specific_Termination_Handlers
7076      --  and warn on a potentially blocking call to Abort_Task.
7077
7078      if Restriction_Check_Required (No_Specific_Termination_Handlers)
7079        and then (Is_RTE (Nam, RE_Set_Specific_Handler)
7080                    or else
7081                  Is_RTE (Nam, RE_Specific_Handler))
7082      then
7083         Check_Restriction (No_Specific_Termination_Handlers, N);
7084
7085      elsif Is_RTE (Nam, RE_Abort_Task) then
7086         Check_Potentially_Blocking_Operation (N);
7087      end if;
7088
7089      --  A call to Ada.Real_Time.Timing_Events.Set_Handler to set a relative
7090      --  timing event violates restriction No_Relative_Delay (AI-0211). We
7091      --  need to check the second argument to determine whether it is an
7092      --  absolute or relative timing event.
7093
7094      if Restriction_Check_Required (No_Relative_Delay)
7095        and then Is_RTE (Nam, RE_Set_Handler)
7096        and then Is_RTE (Etype (Next_Actual (First_Actual (N))), RE_Time_Span)
7097      then
7098         Check_Restriction (No_Relative_Delay, N);
7099      end if;
7100
7101      --  Issue an error for a call to an eliminated subprogram. This routine
7102      --  will not perform the check if the call appears within a default
7103      --  expression.
7104
7105      Check_For_Eliminated_Subprogram (Subp, Nam);
7106
7107      --  Implement rule in 12.5.1 (23.3/2): In an instance, if the actual is
7108      --  class-wide and the call dispatches on result in a context that does
7109      --  not provide a tag, the call raises Program_Error.
7110
7111      if Nkind (N) = N_Function_Call
7112        and then In_Instance
7113        and then Is_Generic_Actual_Type (Typ)
7114        and then Is_Class_Wide_Type (Typ)
7115        and then Has_Controlling_Result (Nam)
7116        and then Nkind (Parent (N)) = N_Object_Declaration
7117      then
7118         --  Verify that none of the formals are controlling
7119
7120         declare
7121            Call_OK : Boolean := False;
7122            F       : Entity_Id;
7123
7124         begin
7125            F := First_Formal (Nam);
7126            while Present (F) loop
7127               if Is_Controlling_Formal (F) then
7128                  Call_OK := True;
7129                  exit;
7130               end if;
7131
7132               Next_Formal (F);
7133            end loop;
7134
7135            if not Call_OK then
7136               Error_Msg_Warn := SPARK_Mode /= On;
7137               Error_Msg_N ("!cannot determine tag of result<<", N);
7138               Error_Msg_N ("\Program_Error [<<!", N);
7139               Insert_Action (N,
7140                 Make_Raise_Program_Error (Sloc (N),
7141                    Reason => PE_Explicit_Raise));
7142            end if;
7143         end;
7144      end if;
7145
7146      --  Check for calling a function with OUT or IN OUT parameter when the
7147      --  calling context (us right now) is not Ada 2012, so does not allow
7148      --  OUT or IN OUT parameters in function calls. Functions declared in
7149      --  a predefined unit are OK, as they may be called indirectly from a
7150      --  user-declared instantiation.
7151
7152      if Ada_Version < Ada_2012
7153        and then Ekind (Nam) = E_Function
7154        and then Has_Out_Or_In_Out_Parameter (Nam)
7155        and then not In_Predefined_Unit (Nam)
7156      then
7157         Error_Msg_NE ("& has at least one OUT or `IN OUT` parameter", N, Nam);
7158         Error_Msg_N ("\call to this function only allowed in Ada 2012", N);
7159      end if;
7160
7161      --  Check the dimensions of the actuals in the call. For function calls,
7162      --  propagate the dimensions from the returned type to N.
7163
7164      Analyze_Dimension_Call (N, Nam);
7165
7166      --  All done, evaluate call and deal with elaboration issues
7167
7168      Eval_Call (N);
7169
7170      if Legacy_Elaboration_Checks then
7171         Check_Elab_Call (N);
7172      end if;
7173
7174      --  Annotate the tree by creating a call marker in case the original call
7175      --  is transformed by expansion. The call marker is automatically saved
7176      --  for later examination by the ABE Processing phase.
7177
7178      Build_Call_Marker (N);
7179
7180      Mark_Use_Clauses (Subp);
7181
7182      Warn_On_Overlapping_Actuals (Nam, N);
7183
7184      --  Ada 2022 (AI12-0075): If the call is a static call to a static
7185      --  expression function, then we want to "inline" the call, replacing
7186      --  it with the folded static result. This is not done if the checking
7187      --  for a potentially static expression is enabled or if an error has
7188      --  been posted on the call (which may be due to the check for recursive
7189      --  calls, in which case we don't want to fall into infinite recursion
7190      --  when doing the inlining).
7191
7192      if not Checking_Potentially_Static_Expression
7193        and then Is_Static_Function_Call (N)
7194        and then not Is_Intrinsic_Subprogram (Ultimate_Alias (Nam))
7195        and then not Error_Posted (Ultimate_Alias (Nam))
7196      then
7197         Inline_Static_Function_Call (N, Ultimate_Alias (Nam));
7198
7199      --  In GNATprove mode, expansion is disabled, but we want to inline some
7200      --  subprograms to facilitate formal verification. Indirect calls through
7201      --  a subprogram type or within a generic cannot be inlined. Inlining is
7202      --  performed only for calls subject to SPARK_Mode on.
7203
7204      elsif GNATprove_Mode
7205        and then SPARK_Mode = On
7206        and then Is_Overloadable (Nam)
7207        and then not Inside_A_Generic
7208      then
7209         Nam_UA   := Ultimate_Alias (Nam);
7210         Nam_Decl := Unit_Declaration_Node (Nam_UA);
7211
7212         if Nkind (Nam_Decl) = N_Subprogram_Declaration then
7213            Body_Id := Corresponding_Body (Nam_Decl);
7214
7215            --  Nothing to do if the subprogram is not eligible for inlining in
7216            --  GNATprove mode, or inlining is disabled with switch -gnatdm
7217
7218            if not Is_Inlined_Always (Nam_UA)
7219              or else not Can_Be_Inlined_In_GNATprove_Mode (Nam_UA, Body_Id)
7220              or else Debug_Flag_M
7221            then
7222               null;
7223
7224            --  Calls cannot be inlined inside assertions, as GNATprove treats
7225            --  assertions as logic expressions. Only issue a message when the
7226            --  body has been seen, otherwise this leads to spurious messages
7227            --  on expression functions.
7228
7229            elsif In_Assertion_Expr /= 0 then
7230               Cannot_Inline
7231                 ("cannot inline & (in assertion expression)?", N, Nam_UA,
7232                  Suppress_Info => No (Body_Id));
7233
7234            --  Calls cannot be inlined inside default expressions
7235
7236            elsif In_Default_Expr then
7237               Cannot_Inline
7238                 ("cannot inline & (in default expression)?", N, Nam_UA);
7239
7240            --  Calls cannot be inlined inside quantified expressions, which
7241            --  are left in expression form for GNATprove. Since these
7242            --  expressions are only preanalyzed, we need to detect the failure
7243            --  to inline outside of the case for Full_Analysis below.
7244
7245            elsif In_Quantified_Expression (N) then
7246               Cannot_Inline
7247                 ("cannot inline & (in quantified expression)?", N, Nam_UA);
7248
7249            --  Inlining should not be performed during preanalysis
7250
7251            elsif Full_Analysis then
7252
7253               --  Do not inline calls inside expression functions or functions
7254               --  generated by the front end for subtype predicates, as this
7255               --  would prevent interpreting them as logical formulas in
7256               --  GNATprove. Only issue a message when the body has been seen,
7257               --  otherwise this leads to spurious messages on callees that
7258               --  are themselves expression functions.
7259
7260               if Present (Current_Subprogram)
7261                 and then
7262                   (Is_Expression_Function_Or_Completion (Current_Subprogram)
7263                     or else Is_Predicate_Function (Current_Subprogram)
7264                     or else Is_Invariant_Procedure (Current_Subprogram)
7265                     or else Is_DIC_Procedure (Current_Subprogram))
7266               then
7267                  if Present (Body_Id)
7268                    and then Present (Body_To_Inline (Nam_Decl))
7269                  then
7270                     if Is_Predicate_Function (Current_Subprogram) then
7271                        Cannot_Inline
7272                          ("cannot inline & (inside predicate)?",
7273                           N, Nam_UA);
7274
7275                     elsif Is_Invariant_Procedure (Current_Subprogram) then
7276                        Cannot_Inline
7277                          ("cannot inline & (inside invariant)?",
7278                           N, Nam_UA);
7279
7280                     elsif Is_DIC_Procedure (Current_Subprogram) then
7281                        Cannot_Inline
7282                        ("cannot inline & (inside Default_Initial_Condition)?",
7283                         N, Nam_UA);
7284
7285                     else
7286                        Cannot_Inline
7287                          ("cannot inline & (inside expression function)?",
7288                           N, Nam_UA);
7289                     end if;
7290                  end if;
7291
7292               --  Cannot inline a call inside the definition of a record type,
7293               --  typically inside the constraints of the type. Calls in
7294               --  default expressions are also not inlined, but this is
7295               --  filtered out above when testing In_Default_Expr.
7296
7297               elsif Is_Record_Type (Current_Scope) then
7298                  Cannot_Inline
7299                    ("cannot inline & (inside record type)?", N, Nam_UA);
7300
7301               --  With the one-pass inlining technique, a call cannot be
7302               --  inlined if the corresponding body has not been seen yet.
7303
7304               elsif No (Body_Id) then
7305                  Cannot_Inline
7306                    ("cannot inline & (body not seen yet)?", N, Nam_UA);
7307
7308               --  Nothing to do if there is no body to inline, indicating that
7309               --  the subprogram is not suitable for inlining in GNATprove
7310               --  mode.
7311
7312               elsif No (Body_To_Inline (Nam_Decl)) then
7313                  null;
7314
7315               --  Calls cannot be inlined inside potentially unevaluated
7316               --  expressions, as this would create complex actions inside
7317               --  expressions, that are not handled by GNATprove.
7318
7319               elsif Is_Potentially_Unevaluated (N) then
7320                  Cannot_Inline
7321                    ("cannot inline & (in potentially unevaluated context)?",
7322                     N, Nam_UA);
7323
7324               --  Calls cannot be inlined inside the conditions of while
7325               --  loops, as this would create complex actions inside
7326               --  the condition, that are not handled by GNATprove.
7327
7328               elsif In_While_Loop_Condition (N) then
7329                  Cannot_Inline
7330                    ("cannot inline & (in while loop condition)?", N, Nam_UA);
7331
7332               --  Do not inline calls which would possibly lead to missing a
7333               --  type conversion check on an input parameter.
7334
7335               elsif not Call_Can_Be_Inlined_In_GNATprove_Mode (N, Nam) then
7336                  Cannot_Inline
7337                    ("cannot inline & (possible check on input parameters)?",
7338                     N, Nam_UA);
7339
7340               --  Otherwise, inline the call, issuing an info message when
7341               --  -gnatd_f is set.
7342
7343               else
7344                  if Debug_Flag_Underscore_F then
7345                     Error_Msg_NE
7346                       ("info: analyzing call to & in context?", N, Nam_UA);
7347                  end if;
7348
7349                  Expand_Inlined_Call (N, Nam_UA, Nam);
7350               end if;
7351            end if;
7352         end if;
7353      end if;
7354   end Resolve_Call;
7355
7356   -----------------------------
7357   -- Resolve_Case_Expression --
7358   -----------------------------
7359
7360   procedure Resolve_Case_Expression (N : Node_Id; Typ : Entity_Id) is
7361      Alt      : Node_Id;
7362      Alt_Expr : Node_Id;
7363      Alt_Typ  : Entity_Id;
7364      Is_Dyn   : Boolean;
7365
7366   begin
7367      Alt := First (Alternatives (N));
7368      while Present (Alt) loop
7369         Alt_Expr := Expression (Alt);
7370
7371         if Error_Posted (Alt_Expr) then
7372            return;
7373         end if;
7374
7375         Resolve (Alt_Expr, Typ);
7376         Alt_Typ := Etype (Alt_Expr);
7377
7378         --  When the expression is of a scalar subtype different from the
7379         --  result subtype, then insert a conversion to ensure the generation
7380         --  of a constraint check.
7381
7382         if Is_Scalar_Type (Alt_Typ) and then Alt_Typ /= Typ then
7383            Rewrite (Alt_Expr, Convert_To (Typ, Alt_Expr));
7384            Analyze_And_Resolve (Alt_Expr, Typ);
7385         end if;
7386
7387         Next (Alt);
7388      end loop;
7389
7390      --  Apply RM 4.5.7 (17/3): whether the expression is statically or
7391      --  dynamically tagged must be known statically.
7392
7393      if Is_Tagged_Type (Typ) and then not Is_Class_Wide_Type (Typ) then
7394         Alt    := First (Alternatives (N));
7395         Is_Dyn := Is_Dynamically_Tagged (Expression (Alt));
7396
7397         while Present (Alt) loop
7398            if Is_Dynamically_Tagged (Expression (Alt)) /= Is_Dyn then
7399               Error_Msg_N
7400                 ("all or none of the dependent expressions can be "
7401                  & "dynamically tagged", N);
7402            end if;
7403
7404            Next (Alt);
7405         end loop;
7406      end if;
7407
7408      Set_Etype (N, Typ);
7409      Eval_Case_Expression (N);
7410      Analyze_Dimension (N);
7411   end Resolve_Case_Expression;
7412
7413   -------------------------------
7414   -- Resolve_Character_Literal --
7415   -------------------------------
7416
7417   procedure Resolve_Character_Literal (N : Node_Id; Typ : Entity_Id) is
7418      B_Typ : constant Entity_Id := Base_Type (Typ);
7419      C     : Entity_Id;
7420
7421   begin
7422      --  Verify that the character does belong to the type of the context
7423
7424      Set_Etype (N, B_Typ);
7425      Eval_Character_Literal (N);
7426
7427      --  Wide_Wide_Character literals must always be defined, since the set
7428      --  of wide wide character literals is complete, i.e. if a character
7429      --  literal is accepted by the parser, then it is OK for wide wide
7430      --  character (out of range character literals are rejected).
7431
7432      if Root_Type (B_Typ) = Standard_Wide_Wide_Character then
7433         return;
7434
7435      --  Always accept character literal for type Any_Character, which
7436      --  occurs in error situations and in comparisons of literals, both
7437      --  of which should accept all literals.
7438
7439      elsif B_Typ = Any_Character then
7440         return;
7441
7442      --  For Standard.Character or a type derived from it, check that the
7443      --  literal is in range.
7444
7445      elsif Root_Type (B_Typ) = Standard_Character then
7446         if In_Character_Range (UI_To_CC (Char_Literal_Value (N))) then
7447            return;
7448         end if;
7449
7450      --  For Standard.Wide_Character or a type derived from it, check that the
7451      --  literal is in range.
7452
7453      elsif Root_Type (B_Typ) = Standard_Wide_Character then
7454         if In_Wide_Character_Range (UI_To_CC (Char_Literal_Value (N))) then
7455            return;
7456         end if;
7457
7458      --  If the entity is already set, this has already been resolved in a
7459      --  generic context, or comes from expansion. Nothing else to do.
7460
7461      elsif Present (Entity (N)) then
7462         return;
7463
7464      --  Otherwise we have a user defined character type, and we can use the
7465      --  standard visibility mechanisms to locate the referenced entity.
7466
7467      else
7468         C := Current_Entity (N);
7469         while Present (C) loop
7470            if Etype (C) = B_Typ then
7471               Set_Entity_With_Checks (N, C);
7472               Generate_Reference (C, N);
7473               return;
7474            end if;
7475
7476            C := Homonym (C);
7477         end loop;
7478      end if;
7479
7480      --  If we fall through, then the literal does not match any of the
7481      --  entries of the enumeration type. This isn't just a constraint error
7482      --  situation, it is an illegality (see RM 4.2).
7483
7484      Error_Msg_NE
7485        ("character not defined for }", N, First_Subtype (B_Typ));
7486   end Resolve_Character_Literal;
7487
7488   ---------------------------
7489   -- Resolve_Comparison_Op --
7490   ---------------------------
7491
7492   --  Context requires a boolean type, and plays no role in resolution.
7493   --  Processing identical to that for equality operators. The result type is
7494   --  the base type, which matters when pathological subtypes of booleans with
7495   --  limited ranges are used.
7496
7497   procedure Resolve_Comparison_Op (N : Node_Id; Typ : Entity_Id) is
7498      L : constant Node_Id := Left_Opnd (N);
7499      R : constant Node_Id := Right_Opnd (N);
7500      T : Entity_Id;
7501
7502   begin
7503      --  If this is an intrinsic operation which is not predefined, use the
7504      --  types of its declared arguments to resolve the possibly overloaded
7505      --  operands. Otherwise the operands are unambiguous and specify the
7506      --  expected type.
7507
7508      if Scope (Entity (N)) /= Standard_Standard then
7509         T := Etype (First_Entity (Entity (N)));
7510
7511      else
7512         T := Find_Unique_Type (L, R);
7513
7514         if T = Any_Fixed then
7515            T := Unique_Fixed_Point_Type (L);
7516         end if;
7517      end if;
7518
7519      Set_Etype (N, Base_Type (Typ));
7520      Generate_Reference (T, N, ' ');
7521
7522      --  Skip remaining processing if already set to Any_Type
7523
7524      if T = Any_Type then
7525         return;
7526      end if;
7527
7528      --  Deal with other error cases
7529
7530      if T = Any_String    or else
7531         T = Any_Composite or else
7532         T = Any_Character
7533      then
7534         if T = Any_Character then
7535            Ambiguous_Character (L);
7536         else
7537            Error_Msg_N ("ambiguous operands for comparison", N);
7538         end if;
7539
7540         Set_Etype (N, Any_Type);
7541         return;
7542      end if;
7543
7544      --  Resolve the operands if types OK
7545
7546      Resolve (L, T);
7547      Resolve (R, T);
7548      Check_Unset_Reference (L);
7549      Check_Unset_Reference (R);
7550      Generate_Operator_Reference (N, T);
7551      Check_Low_Bound_Tested (N);
7552
7553      --  Check comparison on unordered enumeration
7554
7555      if Bad_Unordered_Enumeration_Reference (N, Etype (L)) then
7556         Error_Msg_Sloc := Sloc (Etype (L));
7557         Error_Msg_NE
7558           ("comparison on unordered enumeration type& declared#?.u?",
7559            N, Etype (L));
7560      end if;
7561
7562      Analyze_Dimension (N);
7563
7564      Eval_Relational_Op (N);
7565   end Resolve_Comparison_Op;
7566
7567   --------------------------------
7568   -- Resolve_Declare_Expression --
7569   --------------------------------
7570
7571   procedure Resolve_Declare_Expression
7572     (N   : Node_Id;
7573      Typ : Entity_Id)
7574   is
7575      Expr : constant Node_Id := Expression (N);
7576
7577      Decl  : Node_Id;
7578      Local : Entity_Id := Empty;
7579
7580      function Replace_Local (N  : Node_Id) return Traverse_Result;
7581      --  Use a tree traversal to replace each ocurrence of the name of
7582      --  a local object declared in the construct, with the corresponding
7583      --  entity. This replaces the usual way to perform name capture by
7584      --  visibility, because it is not possible to place on the scope
7585      --  stack the fake scope created for the analysis of the local
7586      --  declarations; such a scope conflicts with the transient scopes
7587      --  that may be generated if the expression includes function calls
7588      --  requiring finalization.
7589
7590      -------------------
7591      -- Replace_Local --
7592      -------------------
7593
7594      function Replace_Local (N  : Node_Id) return Traverse_Result is
7595      begin
7596         --  The identifier may be the prefix of a selected component,
7597         --  but not a selector name, because the local entities do not
7598         --  have a scope that can be named: a selected component whose
7599         --  selector is a homonym of a local entity must denote some
7600         --  global entity.
7601
7602         if Nkind (N) = N_Identifier
7603           and then Chars (N) = Chars (Local)
7604           and then No (Entity (N))
7605           and then
7606             (Nkind (Parent (N)) /= N_Selected_Component
7607               or else N = Prefix (Parent (N)))
7608         then
7609            Set_Entity (N, Local);
7610            Set_Etype (N, Etype (Local));
7611         end if;
7612
7613         return OK;
7614      end Replace_Local;
7615
7616      procedure Replace_Local_Ref is new Traverse_Proc (Replace_Local);
7617
7618      --  Start of processing for  Resolve_Declare_Expression
7619
7620   begin
7621
7622      Decl := First (Actions (N));
7623
7624      while Present (Decl) loop
7625         if Nkind (Decl) in
7626            N_Object_Declaration | N_Object_Renaming_Declaration
7627              and then Comes_From_Source (Defining_Identifier (Decl))
7628         then
7629            Local := Defining_Identifier (Decl);
7630            Replace_Local_Ref (Expr);
7631         end if;
7632
7633         Next (Decl);
7634      end loop;
7635
7636      --  The end of the declarative list is a freeze point for the
7637      --  local declarations.
7638
7639      if Present (Local) then
7640         Decl := Parent (Local);
7641         Freeze_All (First_Entity (Scope (Local)), Decl);
7642      end if;
7643
7644      Resolve (Expr, Typ);
7645   end Resolve_Declare_Expression;
7646
7647   -----------------------------------------
7648   -- Resolve_Discrete_Subtype_Indication --
7649   -----------------------------------------
7650
7651   procedure Resolve_Discrete_Subtype_Indication
7652     (N   : Node_Id;
7653      Typ : Entity_Id)
7654   is
7655      R : Node_Id;
7656      S : Entity_Id;
7657
7658   begin
7659      Analyze (Subtype_Mark (N));
7660      S := Entity (Subtype_Mark (N));
7661
7662      if Nkind (Constraint (N)) /= N_Range_Constraint then
7663         Error_Msg_N ("expect range constraint for discrete type", N);
7664         Set_Etype (N, Any_Type);
7665
7666      else
7667         R := Range_Expression (Constraint (N));
7668
7669         if R = Error then
7670            return;
7671         end if;
7672
7673         Analyze (R);
7674
7675         if Base_Type (S) /= Base_Type (Typ) then
7676            Error_Msg_NE
7677              ("expect subtype of }", N, First_Subtype (Typ));
7678
7679            --  Rewrite the constraint as a range of Typ
7680            --  to allow compilation to proceed further.
7681
7682            Set_Etype (N, Typ);
7683            Rewrite (Low_Bound (R),
7684              Make_Attribute_Reference (Sloc (Low_Bound (R)),
7685                Prefix         => New_Occurrence_Of (Typ, Sloc (R)),
7686                Attribute_Name => Name_First));
7687            Rewrite (High_Bound (R),
7688              Make_Attribute_Reference (Sloc (High_Bound (R)),
7689                Prefix         => New_Occurrence_Of (Typ, Sloc (R)),
7690                Attribute_Name => Name_First));
7691
7692         else
7693            Resolve (R, Typ);
7694            Set_Etype (N, Etype (R));
7695
7696            --  Additionally, we must check that the bounds are compatible
7697            --  with the given subtype, which might be different from the
7698            --  type of the context.
7699
7700            Apply_Range_Check (R, S);
7701
7702            --  ??? If the above check statically detects a Constraint_Error
7703            --  it replaces the offending bound(s) of the range R with a
7704            --  Constraint_Error node. When the itype which uses these bounds
7705            --  is frozen the resulting call to Duplicate_Subexpr generates
7706            --  a new temporary for the bounds.
7707
7708            --  Unfortunately there are other itypes that are also made depend
7709            --  on these bounds, so when Duplicate_Subexpr is called they get
7710            --  a forward reference to the newly created temporaries and Gigi
7711            --  aborts on such forward references. This is probably sign of a
7712            --  more fundamental problem somewhere else in either the order of
7713            --  itype freezing or the way certain itypes are constructed.
7714
7715            --  To get around this problem we call Remove_Side_Effects right
7716            --  away if either bounds of R are a Constraint_Error.
7717
7718            declare
7719               L : constant Node_Id := Low_Bound (R);
7720               H : constant Node_Id := High_Bound (R);
7721
7722            begin
7723               if Nkind (L) = N_Raise_Constraint_Error then
7724                  Remove_Side_Effects (L);
7725               end if;
7726
7727               if Nkind (H) = N_Raise_Constraint_Error then
7728                  Remove_Side_Effects (H);
7729               end if;
7730            end;
7731
7732            Check_Unset_Reference (Low_Bound  (R));
7733            Check_Unset_Reference (High_Bound (R));
7734         end if;
7735      end if;
7736   end Resolve_Discrete_Subtype_Indication;
7737
7738   -------------------------
7739   -- Resolve_Entity_Name --
7740   -------------------------
7741
7742   --  Used to resolve identifiers and expanded names
7743
7744   procedure Resolve_Entity_Name (N : Node_Id; Typ : Entity_Id) is
7745      function Is_Assignment_Or_Object_Expression
7746        (Context : Node_Id;
7747         Expr    : Node_Id) return Boolean;
7748      --  Determine whether node Context denotes an assignment statement or an
7749      --  object declaration whose expression is node Expr.
7750
7751      function Is_Attribute_Expression (Expr : Node_Id) return Boolean;
7752      --  Determine whether Expr is part of an N_Attribute_Reference
7753      --  expression.
7754
7755      ----------------------------------------
7756      -- Is_Assignment_Or_Object_Expression --
7757      ----------------------------------------
7758
7759      function Is_Assignment_Or_Object_Expression
7760        (Context : Node_Id;
7761         Expr    : Node_Id) return Boolean
7762      is
7763      begin
7764         if Nkind (Context) in N_Assignment_Statement | N_Object_Declaration
7765           and then Expression (Context) = Expr
7766         then
7767            return True;
7768
7769         --  Check whether a construct that yields a name is the expression of
7770         --  an assignment statement or an object declaration.
7771
7772         elsif (Nkind (Context) in N_Attribute_Reference
7773                                 | N_Explicit_Dereference
7774                                 | N_Indexed_Component
7775                                 | N_Selected_Component
7776                                 | N_Slice
7777                  and then Prefix (Context) = Expr)
7778           or else
7779               (Nkind (Context) in N_Type_Conversion
7780                                 | N_Unchecked_Type_Conversion
7781                  and then Expression (Context) = Expr)
7782         then
7783            return
7784              Is_Assignment_Or_Object_Expression
7785                (Context => Parent (Context),
7786                 Expr    => Context);
7787
7788         --  Otherwise the context is not an assignment statement or an object
7789         --  declaration.
7790
7791         else
7792            return False;
7793         end if;
7794      end Is_Assignment_Or_Object_Expression;
7795
7796      -----------------------------
7797      -- Is_Attribute_Expression --
7798      -----------------------------
7799
7800      function Is_Attribute_Expression (Expr : Node_Id) return Boolean is
7801         N : Node_Id := Expr;
7802      begin
7803         while Present (N) loop
7804            if Nkind (N) = N_Attribute_Reference then
7805               return True;
7806
7807            --  Prevent the search from going too far
7808
7809            elsif Is_Body_Or_Package_Declaration (N) then
7810               return False;
7811            end if;
7812
7813            N := Parent (N);
7814         end loop;
7815
7816         return False;
7817      end Is_Attribute_Expression;
7818
7819      --  Local variables
7820
7821      E   : constant Entity_Id := Entity (N);
7822      Par : Node_Id;
7823
7824   --  Start of processing for Resolve_Entity_Name
7825
7826   begin
7827      --  If garbage from errors, set to Any_Type and return
7828
7829      if No (E) and then Total_Errors_Detected /= 0 then
7830         Set_Etype (N, Any_Type);
7831         return;
7832      end if;
7833
7834      --  Replace named numbers by corresponding literals. Note that this is
7835      --  the one case where Resolve_Entity_Name must reset the Etype, since
7836      --  it is currently marked as universal.
7837
7838      if Ekind (E) = E_Named_Integer then
7839         Set_Etype (N, Typ);
7840         Eval_Named_Integer (N);
7841
7842      elsif Ekind (E) = E_Named_Real then
7843         Set_Etype (N, Typ);
7844         Eval_Named_Real (N);
7845
7846      --  For enumeration literals, we need to make sure that a proper style
7847      --  check is done, since such literals are overloaded, and thus we did
7848      --  not do a style check during the first phase of analysis.
7849
7850      elsif Ekind (E) = E_Enumeration_Literal then
7851         Set_Entity_With_Checks (N, E);
7852         Eval_Entity_Name (N);
7853
7854      --  Case of (sub)type name appearing in a context where an expression
7855      --  is expected. This is legal if occurrence is a current instance.
7856      --  See RM 8.6 (17/3). It is also legal if the expression is
7857      --  part of a choice pattern for a case stmt/expr having a
7858      --  non-discrete selecting expression.
7859
7860      elsif Is_Type (E) then
7861         if Is_Current_Instance (N) or else Is_Case_Choice_Pattern (N) then
7862            null;
7863
7864         --  Any other use is an error
7865
7866         else
7867            Error_Msg_N
7868              ("invalid use of subtype mark in expression or call", N);
7869         end if;
7870
7871      --  Check discriminant use if entity is discriminant in current scope,
7872      --  i.e. discriminant of record or concurrent type currently being
7873      --  analyzed. Uses in corresponding body are unrestricted.
7874
7875      elsif Ekind (E) = E_Discriminant
7876        and then Scope (E) = Current_Scope
7877        and then not Has_Completion (Current_Scope)
7878      then
7879         Check_Discriminant_Use (N);
7880
7881      --  A parameterless generic function cannot appear in a context that
7882      --  requires resolution.
7883
7884      elsif Ekind (E) = E_Generic_Function then
7885         Error_Msg_N ("illegal use of generic function", N);
7886
7887      --  In Ada 83 an OUT parameter cannot be read, but attributes of
7888      --  array types (i.e. bounds and length) are legal.
7889
7890      elsif Ekind (E) = E_Out_Parameter
7891        and then (Is_Scalar_Type (Etype (E))
7892                   or else not Is_Attribute_Expression (Parent (N)))
7893
7894        and then (Nkind (Parent (N)) in N_Op
7895                   or else Nkind (Parent (N)) = N_Explicit_Dereference
7896                   or else Is_Assignment_Or_Object_Expression
7897                             (Context => Parent (N),
7898                              Expr    => N))
7899      then
7900         if Ada_Version = Ada_83 then
7901            Error_Msg_N ("(Ada 83) illegal reading of out parameter", N);
7902         end if;
7903
7904      --  In all other cases, just do the possible static evaluation
7905
7906      else
7907         --  A deferred constant that appears in an expression must have a
7908         --  completion, unless it has been removed by in-place expansion of
7909         --  an aggregate. A constant that is a renaming does not need
7910         --  initialization.
7911
7912         if Ekind (E) = E_Constant
7913           and then Comes_From_Source (E)
7914           and then No (Constant_Value (E))
7915           and then Is_Frozen (Etype (E))
7916           and then not In_Spec_Expression
7917           and then not Is_Imported (E)
7918           and then Nkind (Parent (E)) /= N_Object_Renaming_Declaration
7919         then
7920            if No_Initialization (Parent (E))
7921              or else (Present (Full_View (E))
7922                        and then No_Initialization (Parent (Full_View (E))))
7923            then
7924               null;
7925            else
7926               Error_Msg_N
7927                 ("deferred constant is frozen before completion", N);
7928            end if;
7929         end if;
7930
7931         Eval_Entity_Name (N);
7932      end if;
7933
7934      Par := Parent (N);
7935
7936      --  When the entity appears in a parameter association, retrieve the
7937      --  related subprogram call.
7938
7939      if Nkind (Par) = N_Parameter_Association then
7940         Par := Parent (Par);
7941      end if;
7942
7943      if Comes_From_Source (N) then
7944
7945         --  The following checks are only relevant when SPARK_Mode is on as
7946         --  they are not standard Ada legality rules.
7947
7948         if SPARK_Mode = On then
7949
7950            --  An effectively volatile object for reading must appear in
7951            --  non-interfering context (SPARK RM 7.1.3(10)).
7952
7953            if Is_Object (E)
7954              and then Is_Effectively_Volatile_For_Reading (E)
7955              and then
7956                not Is_OK_Volatile_Context (Par, N, Check_Actuals => False)
7957            then
7958               SPARK_Msg_N
7959                 ("volatile object cannot appear in this context "
7960                  & "(SPARK RM 7.1.3(10))", N);
7961            end if;
7962
7963            --  Check for possible elaboration issues with respect to reads of
7964            --  variables. The act of renaming the variable is not considered a
7965            --  read as it simply establishes an alias.
7966
7967            if Legacy_Elaboration_Checks
7968              and then Ekind (E) = E_Variable
7969              and then Dynamic_Elaboration_Checks
7970              and then Nkind (Par) /= N_Object_Renaming_Declaration
7971            then
7972               Check_Elab_Call (N);
7973            end if;
7974         end if;
7975
7976         --  The variable may eventually become a constituent of a single
7977         --  protected/task type. Record the reference now and verify its
7978         --  legality when analyzing the contract of the variable
7979         --  (SPARK RM 9.3).
7980
7981         if Ekind (E) = E_Variable then
7982            Record_Possible_Part_Of_Reference (E, N);
7983         end if;
7984
7985         --  A Ghost entity must appear in a specific context
7986
7987         if Is_Ghost_Entity (E) then
7988            Check_Ghost_Context (E, N);
7989         end if;
7990      end if;
7991
7992      --  We may be resolving an entity within expanded code, so a reference to
7993      --  an entity should be ignored when calculating effective use clauses to
7994      --  avoid inappropriate marking.
7995
7996      if Comes_From_Source (N) then
7997         Mark_Use_Clauses (E);
7998      end if;
7999   end Resolve_Entity_Name;
8000
8001   -------------------
8002   -- Resolve_Entry --
8003   -------------------
8004
8005   procedure Resolve_Entry (Entry_Name : Node_Id) is
8006      Loc    : constant Source_Ptr := Sloc (Entry_Name);
8007      Nam    : Entity_Id;
8008      New_N  : Node_Id;
8009      S      : Entity_Id;
8010      Tsk    : Entity_Id;
8011      E_Name : Node_Id;
8012      Index  : Node_Id;
8013
8014      function Actual_Index_Type (E : Entity_Id) return Entity_Id;
8015      --  If the bounds of the entry family being called depend on task
8016      --  discriminants, build a new index subtype where a discriminant is
8017      --  replaced with the value of the discriminant of the target task.
8018      --  The target task is the prefix of the entry name in the call.
8019
8020      -----------------------
8021      -- Actual_Index_Type --
8022      -----------------------
8023
8024      function Actual_Index_Type (E : Entity_Id) return Entity_Id is
8025         Typ   : constant Entity_Id := Entry_Index_Type (E);
8026         Tsk   : constant Entity_Id := Scope (E);
8027         Lo    : constant Node_Id   := Type_Low_Bound  (Typ);
8028         Hi    : constant Node_Id   := Type_High_Bound (Typ);
8029         New_T : Entity_Id;
8030
8031         function Actual_Discriminant_Ref (Bound : Node_Id) return Node_Id;
8032         --  If the bound is given by a discriminant, replace with a reference
8033         --  to the discriminant of the same name in the target task. If the
8034         --  entry name is the target of a requeue statement and the entry is
8035         --  in the current protected object, the bound to be used is the
8036         --  discriminal of the object (see Apply_Range_Check for details of
8037         --  the transformation).
8038
8039         -----------------------------
8040         -- Actual_Discriminant_Ref --
8041         -----------------------------
8042
8043         function Actual_Discriminant_Ref (Bound : Node_Id) return Node_Id is
8044            Typ : constant Entity_Id := Etype (Bound);
8045            Ref : Node_Id;
8046
8047         begin
8048            Remove_Side_Effects (Bound);
8049
8050            if not Is_Entity_Name (Bound)
8051              or else Ekind (Entity (Bound)) /= E_Discriminant
8052            then
8053               return Bound;
8054
8055            elsif Is_Protected_Type (Tsk)
8056              and then In_Open_Scopes (Tsk)
8057              and then Nkind (Parent (Entry_Name)) = N_Requeue_Statement
8058            then
8059               --  Note: here Bound denotes a discriminant of the corresponding
8060               --  record type tskV, whose discriminal is a formal of the
8061               --  init-proc tskVIP. What we want is the body discriminal,
8062               --  which is associated to the discriminant of the original
8063               --  concurrent type tsk.
8064
8065               return New_Occurrence_Of
8066                        (Find_Body_Discriminal (Entity (Bound)), Loc);
8067
8068            else
8069               Ref :=
8070                 Make_Selected_Component (Loc,
8071                   Prefix => New_Copy_Tree (Prefix (Prefix (Entry_Name))),
8072                   Selector_Name => New_Occurrence_Of (Entity (Bound), Loc));
8073               Analyze (Ref);
8074               Resolve (Ref, Typ);
8075               return Ref;
8076            end if;
8077         end Actual_Discriminant_Ref;
8078
8079      --  Start of processing for Actual_Index_Type
8080
8081      begin
8082         if not Has_Discriminants (Tsk)
8083           or else (not Is_Entity_Name (Lo) and then not Is_Entity_Name (Hi))
8084         then
8085            return Entry_Index_Type (E);
8086
8087         else
8088            New_T := Create_Itype (Ekind (Typ), Parent (Entry_Name));
8089            Set_Etype        (New_T, Base_Type (Typ));
8090            Set_Size_Info    (New_T, Typ);
8091            Set_RM_Size      (New_T, RM_Size (Typ));
8092            Set_Scalar_Range (New_T,
8093              Make_Range (Sloc (Entry_Name),
8094                Low_Bound  => Actual_Discriminant_Ref (Lo),
8095                High_Bound => Actual_Discriminant_Ref (Hi)));
8096
8097            return New_T;
8098         end if;
8099      end Actual_Index_Type;
8100
8101   --  Start of processing for Resolve_Entry
8102
8103   begin
8104      --  Find name of entry being called, and resolve prefix of name with its
8105      --  own type. The prefix can be overloaded, and the name and signature of
8106      --  the entry must be taken into account.
8107
8108      if Nkind (Entry_Name) = N_Indexed_Component then
8109
8110         --  Case of dealing with entry family within the current tasks
8111
8112         E_Name := Prefix (Entry_Name);
8113
8114      else
8115         E_Name := Entry_Name;
8116      end if;
8117
8118      if Is_Entity_Name (E_Name) then
8119
8120         --  Entry call to an entry (or entry family) in the current task. This
8121         --  is legal even though the task will deadlock. Rewrite as call to
8122         --  current task.
8123
8124         --  This can also be a call to an entry in an enclosing task. If this
8125         --  is a single task, we have to retrieve its name, because the scope
8126         --  of the entry is the task type, not the object. If the enclosing
8127         --  task is a task type, the identity of the task is given by its own
8128         --  self variable.
8129
8130         --  Finally this can be a requeue on an entry of the same task or
8131         --  protected object.
8132
8133         S := Scope (Entity (E_Name));
8134
8135         for J in reverse 0 .. Scope_Stack.Last loop
8136            if Is_Task_Type (Scope_Stack.Table (J).Entity)
8137              and then not Comes_From_Source (S)
8138            then
8139               --  S is an enclosing task or protected object. The concurrent
8140               --  declaration has been converted into a type declaration, and
8141               --  the object itself has an object declaration that follows
8142               --  the type in the same declarative part.
8143
8144               Tsk := Next_Entity (S);
8145               while Etype (Tsk) /= S loop
8146                  Next_Entity (Tsk);
8147               end loop;
8148
8149               S := Tsk;
8150               exit;
8151
8152            elsif S = Scope_Stack.Table (J).Entity then
8153
8154               --  Call to current task. Will be transformed into call to Self
8155
8156               exit;
8157
8158            end if;
8159         end loop;
8160
8161         New_N :=
8162           Make_Selected_Component (Loc,
8163             Prefix => New_Occurrence_Of (S, Loc),
8164             Selector_Name =>
8165               New_Occurrence_Of (Entity (E_Name), Loc));
8166         Rewrite (E_Name, New_N);
8167         Analyze (E_Name);
8168
8169      elsif Nkind (Entry_Name) = N_Selected_Component
8170        and then Is_Overloaded (Prefix (Entry_Name))
8171      then
8172         --  Use the entry name (which must be unique at this point) to find
8173         --  the prefix that returns the corresponding task/protected type.
8174
8175         declare
8176            Pref : constant Node_Id := Prefix (Entry_Name);
8177            Ent  : constant Entity_Id := Entity (Selector_Name (Entry_Name));
8178            I    : Interp_Index;
8179            It   : Interp;
8180
8181         begin
8182            Get_First_Interp (Pref, I, It);
8183            while Present (It.Typ) loop
8184               if Scope (Ent) = It.Typ then
8185                  Set_Etype (Pref, It.Typ);
8186                  exit;
8187               end if;
8188
8189               Get_Next_Interp (I, It);
8190            end loop;
8191         end;
8192      end if;
8193
8194      if Nkind (Entry_Name) = N_Selected_Component then
8195         Resolve (Prefix (Entry_Name));
8196         Resolve_Implicit_Dereference (Prefix (Entry_Name));
8197
8198      else pragma Assert (Nkind (Entry_Name) = N_Indexed_Component);
8199         Nam := Entity (Selector_Name (Prefix (Entry_Name)));
8200         Resolve (Prefix (Prefix (Entry_Name)));
8201         Resolve_Implicit_Dereference (Prefix (Prefix (Entry_Name)));
8202
8203         --  We do not resolve the prefix because an Entry_Family has no type,
8204         --  although it has the semantics of an array since it can be indexed.
8205         --  In order to perform the associated range check, we would need to
8206         --  build an array type on the fly and set it on the prefix, but this
8207         --  would be wasteful since only the index type matters. Therefore we
8208         --  attach this index type directly, so that Actual_Index_Expression
8209         --  can pick it up later in order to generate the range check.
8210
8211         Set_Etype (Prefix (Entry_Name), Actual_Index_Type (Nam));
8212
8213         Index := First (Expressions (Entry_Name));
8214         Resolve (Index, Entry_Index_Type (Nam));
8215
8216         --  Generate a reference for the index when it denotes an entity
8217
8218         if Is_Entity_Name (Index) then
8219            Generate_Reference (Entity (Index), Nam);
8220         end if;
8221
8222         --  Up to this point the expression could have been the actual in a
8223         --  simple entry call, and be given by a named association.
8224
8225         if Nkind (Index) = N_Parameter_Association then
8226            Error_Msg_N ("expect expression for entry index", Index);
8227         else
8228            Apply_Scalar_Range_Check (Index, Etype (Prefix (Entry_Name)));
8229         end if;
8230      end if;
8231   end Resolve_Entry;
8232
8233   ------------------------
8234   -- Resolve_Entry_Call --
8235   ------------------------
8236
8237   procedure Resolve_Entry_Call (N : Node_Id; Typ : Entity_Id) is
8238      Entry_Name : constant Node_Id    := Name (N);
8239      Loc        : constant Source_Ptr := Sloc (Entry_Name);
8240
8241      Nam      : Entity_Id;
8242      Norm_OK  : Boolean;
8243      Obj      : Node_Id;
8244      Was_Over : Boolean;
8245
8246   begin
8247      --  We kill all checks here, because it does not seem worth the effort to
8248      --  do anything better, an entry call is a big operation.
8249
8250      Kill_All_Checks;
8251
8252      --  Processing of the name is similar for entry calls and protected
8253      --  operation calls. Once the entity is determined, we can complete
8254      --  the resolution of the actuals.
8255
8256      --  The selector may be overloaded, in the case of a protected object
8257      --  with overloaded functions. The type of the context is used for
8258      --  resolution.
8259
8260      if Nkind (Entry_Name) = N_Selected_Component
8261        and then Is_Overloaded (Selector_Name (Entry_Name))
8262        and then Typ /= Standard_Void_Type
8263      then
8264         declare
8265            I  : Interp_Index;
8266            It : Interp;
8267
8268         begin
8269            Get_First_Interp (Selector_Name (Entry_Name), I, It);
8270            while Present (It.Typ) loop
8271               if Covers (Typ, It.Typ) then
8272                  Set_Entity (Selector_Name (Entry_Name), It.Nam);
8273                  Set_Etype  (Entry_Name, It.Typ);
8274
8275                  Generate_Reference (It.Typ, N, ' ');
8276               end if;
8277
8278               Get_Next_Interp (I, It);
8279            end loop;
8280         end;
8281      end if;
8282
8283      Resolve_Entry (Entry_Name);
8284
8285      if Nkind (Entry_Name) = N_Selected_Component then
8286
8287         --  Simple entry or protected operation call
8288
8289         Nam := Entity (Selector_Name (Entry_Name));
8290         Obj := Prefix (Entry_Name);
8291
8292         if Is_Subprogram (Nam) then
8293            Check_For_Eliminated_Subprogram (Entry_Name, Nam);
8294         end if;
8295
8296         Was_Over := Is_Overloaded (Selector_Name (Entry_Name));
8297
8298      else pragma Assert (Nkind (Entry_Name) = N_Indexed_Component);
8299
8300         --  Call to member of entry family
8301
8302         Nam := Entity (Selector_Name (Prefix (Entry_Name)));
8303         Obj := Prefix (Prefix (Entry_Name));
8304         Was_Over := Is_Overloaded (Selector_Name (Prefix (Entry_Name)));
8305      end if;
8306
8307      --  We cannot in general check the maximum depth of protected entry calls
8308      --  at compile time. But we can tell that any protected entry call at all
8309      --  violates a specified nesting depth of zero.
8310
8311      if Is_Protected_Type (Scope (Nam)) then
8312         Check_Restriction (Max_Entry_Queue_Length, N);
8313      end if;
8314
8315      --  Use context type to disambiguate a protected function that can be
8316      --  called without actuals and that returns an array type, and where the
8317      --  argument list may be an indexing of the returned value.
8318
8319      if Ekind (Nam) = E_Function
8320        and then Needs_No_Actuals (Nam)
8321        and then Present (Parameter_Associations (N))
8322        and then
8323          ((Is_Array_Type (Etype (Nam))
8324             and then Covers (Typ, Component_Type (Etype (Nam))))
8325
8326            or else (Is_Access_Type (Etype (Nam))
8327                      and then Is_Array_Type (Designated_Type (Etype (Nam)))
8328                      and then
8329                        Covers
8330                         (Typ,
8331                          Component_Type (Designated_Type (Etype (Nam))))))
8332      then
8333         declare
8334            Index_Node : Node_Id;
8335
8336         begin
8337            Index_Node :=
8338              Make_Indexed_Component (Loc,
8339                Prefix =>
8340                  Make_Function_Call (Loc, Name => Relocate_Node (Entry_Name)),
8341                Expressions => Parameter_Associations (N));
8342
8343            --  Since we are correcting a node classification error made by the
8344            --  parser, we call Replace rather than Rewrite.
8345
8346            Replace (N, Index_Node);
8347            Set_Etype (Prefix (N), Etype (Nam));
8348            Set_Etype (N, Typ);
8349            Resolve_Indexed_Component (N, Typ);
8350            return;
8351         end;
8352      end if;
8353
8354      if Is_Entry (Nam)
8355        and then Present (Contract_Wrapper (Nam))
8356        and then Current_Scope /= Contract_Wrapper (Nam)
8357      then
8358         --  Note the entity being called before rewriting the call, so that
8359         --  it appears used at this point.
8360
8361         Generate_Reference (Nam, Entry_Name, 'r');
8362
8363         --  Rewrite as call to the precondition wrapper, adding the task
8364         --  object to the list of actuals. If the call is to a member of an
8365         --  entry family, include the index as well.
8366
8367         declare
8368            New_Call    : Node_Id;
8369            New_Actuals : List_Id;
8370
8371         begin
8372            New_Actuals := New_List (Obj);
8373
8374            if Nkind (Entry_Name) = N_Indexed_Component then
8375               Append_To (New_Actuals,
8376                 New_Copy_Tree (First (Expressions (Entry_Name))));
8377            end if;
8378
8379            Append_List (Parameter_Associations (N), New_Actuals);
8380            New_Call :=
8381              Make_Procedure_Call_Statement (Loc,
8382                Name                   =>
8383                  New_Occurrence_Of (Contract_Wrapper (Nam), Loc),
8384                Parameter_Associations => New_Actuals);
8385            Rewrite (N, New_Call);
8386
8387            --  Preanalyze and resolve new call. Current procedure is called
8388            --  from Resolve_Call, after which expansion will take place.
8389
8390            Preanalyze_And_Resolve (N);
8391            return;
8392         end;
8393      end if;
8394
8395      --  The operation name may have been overloaded. Order the actuals
8396      --  according to the formals of the resolved entity, and set the return
8397      --  type to that of the operation.
8398
8399      if Was_Over then
8400         Normalize_Actuals (N, Nam, False, Norm_OK);
8401         pragma Assert (Norm_OK);
8402         Set_Etype (N, Etype (Nam));
8403
8404         --  Reset the Is_Overloaded flag, since resolution is now completed
8405
8406         --  Simple entry call
8407
8408         if Nkind (Entry_Name) = N_Selected_Component then
8409            Set_Is_Overloaded (Selector_Name (Entry_Name), False);
8410
8411         --  Call to a member of an entry family
8412
8413         else pragma Assert (Nkind (Entry_Name) = N_Indexed_Component);
8414            Set_Is_Overloaded (Selector_Name (Prefix (Entry_Name)), False);
8415         end if;
8416      end if;
8417
8418      Resolve_Actuals (N, Nam);
8419      Check_Internal_Protected_Use (N, Nam);
8420
8421      --  Create a call reference to the entry
8422
8423      Generate_Reference (Nam, Entry_Name, 's');
8424
8425      if Is_Entry (Nam) then
8426         Check_Potentially_Blocking_Operation (N);
8427      end if;
8428
8429      --  Verify that a procedure call cannot masquerade as an entry
8430      --  call where an entry call is expected.
8431
8432      if Ekind (Nam) = E_Procedure then
8433         if Nkind (Parent (N)) = N_Entry_Call_Alternative
8434           and then N = Entry_Call_Statement (Parent (N))
8435         then
8436            Error_Msg_N ("entry call required in select statement", N);
8437
8438         elsif Nkind (Parent (N)) = N_Triggering_Alternative
8439           and then N = Triggering_Statement (Parent (N))
8440         then
8441            Error_Msg_N ("triggering statement cannot be procedure call", N);
8442
8443         elsif Ekind (Scope (Nam)) = E_Task_Type
8444           and then not In_Open_Scopes (Scope (Nam))
8445         then
8446            Error_Msg_N ("task has no entry with this name", Entry_Name);
8447         end if;
8448      end if;
8449
8450      --  After resolution, entry calls and protected procedure calls are
8451      --  changed into entry calls, for expansion. The structure of the node
8452      --  does not change, so it can safely be done in place. Protected
8453      --  function calls must keep their structure because they are
8454      --  subexpressions.
8455
8456      if Ekind (Nam) /= E_Function then
8457
8458         --  A protected operation that is not a function may modify the
8459         --  corresponding object, and cannot apply to a constant. If this
8460         --  is an internal call, the prefix is the type itself.
8461
8462         if Is_Protected_Type (Scope (Nam))
8463           and then not Is_Variable (Obj)
8464           and then (not Is_Entity_Name (Obj)
8465                       or else not Is_Type (Entity (Obj)))
8466         then
8467            Error_Msg_N
8468              ("prefix of protected procedure or entry call must be variable",
8469               Entry_Name);
8470         end if;
8471
8472         declare
8473            Entry_Call : Node_Id;
8474
8475         begin
8476            Entry_Call :=
8477              Make_Entry_Call_Statement (Loc,
8478                Name                   => Entry_Name,
8479                Parameter_Associations => Parameter_Associations (N));
8480
8481            --  Inherit relevant attributes from the original call
8482
8483            Set_First_Named_Actual
8484              (Entry_Call, First_Named_Actual (N));
8485
8486            Set_Is_Elaboration_Checks_OK_Node
8487              (Entry_Call, Is_Elaboration_Checks_OK_Node (N));
8488
8489            Set_Is_Elaboration_Warnings_OK_Node
8490              (Entry_Call, Is_Elaboration_Warnings_OK_Node (N));
8491
8492            Set_Is_SPARK_Mode_On_Node
8493              (Entry_Call, Is_SPARK_Mode_On_Node (N));
8494
8495            Rewrite (N, Entry_Call);
8496            Set_Analyzed (N, True);
8497         end;
8498
8499      --  Protected functions can return on the secondary stack, in which case
8500      --  we must trigger the transient scope mechanism.
8501
8502      elsif Expander_Active
8503        and then Requires_Transient_Scope (Etype (Nam))
8504      then
8505         Establish_Transient_Scope (N, Manage_Sec_Stack => True);
8506      end if;
8507
8508      --  Now we know that this is not a call to a function that returns an
8509      --  array type; moreover, we know the name of the called entry. Detect
8510      --  overlapping actuals, just like for a subprogram call.
8511
8512      Warn_On_Overlapping_Actuals (Nam, N);
8513
8514   end Resolve_Entry_Call;
8515
8516   -------------------------
8517   -- Resolve_Equality_Op --
8518   -------------------------
8519
8520   --  Both arguments must have the same type, and the boolean context does
8521   --  not participate in the resolution. The first pass verifies that the
8522   --  interpretation is not ambiguous, and the type of the left argument is
8523   --  correctly set, or is Any_Type in case of ambiguity. If both arguments
8524   --  are strings or aggregates, allocators, or Null, they are ambiguous even
8525   --  though they carry a single (universal) type. Diagnose this case here.
8526
8527   procedure Resolve_Equality_Op (N : Node_Id; Typ : Entity_Id) is
8528      L : constant Node_Id   := Left_Opnd (N);
8529      R : constant Node_Id   := Right_Opnd (N);
8530      T : Entity_Id := Find_Unique_Type (L, R);
8531
8532      procedure Check_If_Expression (Cond : Node_Id);
8533      --  The resolution rule for if expressions requires that each such must
8534      --  have a unique type. This means that if several dependent expressions
8535      --  are of a non-null anonymous access type, and the context does not
8536      --  impose an expected type (as can be the case in an equality operation)
8537      --  the expression must be rejected.
8538
8539      procedure Explain_Redundancy (N : Node_Id);
8540      --  Attempt to explain the nature of a redundant comparison with True. If
8541      --  the expression N is too complex, this routine issues a general error
8542      --  message.
8543
8544      function Find_Unique_Access_Type return Entity_Id;
8545      --  In the case of allocators and access attributes, the context must
8546      --  provide an indication of the specific access type to be used. If
8547      --  one operand is of such a "generic" access type, check whether there
8548      --  is a specific visible access type that has the same designated type.
8549      --  This is semantically dubious, and of no interest to any real code,
8550      --  but c48008a makes it all worthwhile.
8551
8552      function Suspicious_Prio_For_Equality return Boolean;
8553      --  Returns True iff the parent node is a and/or/xor operation that
8554      --  could be the cause of confused priorities. Note that if the not is
8555      --  in parens, then False is returned.
8556
8557      -------------------------
8558      -- Check_If_Expression --
8559      -------------------------
8560
8561      procedure Check_If_Expression (Cond : Node_Id) is
8562         Then_Expr : Node_Id;
8563         Else_Expr : Node_Id;
8564
8565      begin
8566         if Nkind (Cond) = N_If_Expression then
8567            Then_Expr := Next (First (Expressions (Cond)));
8568            Else_Expr := Next (Then_Expr);
8569
8570            if Nkind (Then_Expr) /= N_Null
8571              and then Nkind (Else_Expr) /= N_Null
8572            then
8573               Error_Msg_N ("cannot determine type of if expression", Cond);
8574            end if;
8575         end if;
8576      end Check_If_Expression;
8577
8578      ------------------------
8579      -- Explain_Redundancy --
8580      ------------------------
8581
8582      procedure Explain_Redundancy (N : Node_Id) is
8583         Error  : Name_Id;
8584         Val    : Node_Id;
8585         Val_Id : Entity_Id;
8586
8587      begin
8588         Val := N;
8589
8590         --  Strip the operand down to an entity
8591
8592         loop
8593            if Nkind (Val) = N_Selected_Component then
8594               Val := Selector_Name (Val);
8595            else
8596               exit;
8597            end if;
8598         end loop;
8599
8600         --  The construct denotes an entity
8601
8602         if Is_Entity_Name (Val) and then Present (Entity (Val)) then
8603            Val_Id := Entity (Val);
8604
8605            --  Do not generate an error message when the comparison is done
8606            --  against the enumeration literal Standard.True.
8607
8608            if Ekind (Val_Id) /= E_Enumeration_Literal then
8609
8610               --  Build a customized error message
8611
8612               Name_Len := 0;
8613               Add_Str_To_Name_Buffer ("?r?");
8614
8615               if Ekind (Val_Id) = E_Component then
8616                  Add_Str_To_Name_Buffer ("component ");
8617
8618               elsif Ekind (Val_Id) = E_Constant then
8619                  Add_Str_To_Name_Buffer ("constant ");
8620
8621               elsif Ekind (Val_Id) = E_Discriminant then
8622                  Add_Str_To_Name_Buffer ("discriminant ");
8623
8624               elsif Is_Formal (Val_Id) then
8625                  Add_Str_To_Name_Buffer ("parameter ");
8626
8627               elsif Ekind (Val_Id) = E_Variable then
8628                  Add_Str_To_Name_Buffer ("variable ");
8629               end if;
8630
8631               Add_Str_To_Name_Buffer ("& is always True!");
8632               Error := Name_Find;
8633
8634               Error_Msg_NE (Get_Name_String (Error), Val, Val_Id);
8635            end if;
8636
8637         --  The construct is too complex to disect, issue a general message
8638
8639         else
8640            Error_Msg_N ("?r?expression is always True!", Val);
8641         end if;
8642      end Explain_Redundancy;
8643
8644      -----------------------------
8645      -- Find_Unique_Access_Type --
8646      -----------------------------
8647
8648      function Find_Unique_Access_Type return Entity_Id is
8649         Acc : Entity_Id;
8650         E   : Entity_Id;
8651         S   : Entity_Id;
8652
8653      begin
8654         if Ekind (Etype (R)) in E_Allocator_Type | E_Access_Attribute_Type
8655         then
8656            Acc := Designated_Type (Etype (R));
8657
8658         elsif Ekind (Etype (L)) in E_Allocator_Type | E_Access_Attribute_Type
8659         then
8660            Acc := Designated_Type (Etype (L));
8661         else
8662            return Empty;
8663         end if;
8664
8665         S := Current_Scope;
8666         while S /= Standard_Standard loop
8667            E := First_Entity (S);
8668            while Present (E) loop
8669               if Is_Type (E)
8670                 and then Is_Access_Type (E)
8671                 and then Ekind (E) /= E_Allocator_Type
8672                 and then Designated_Type (E) = Base_Type (Acc)
8673               then
8674                  return E;
8675               end if;
8676
8677               Next_Entity (E);
8678            end loop;
8679
8680            S := Scope (S);
8681         end loop;
8682
8683         return Empty;
8684      end Find_Unique_Access_Type;
8685
8686      ----------------------------------
8687      -- Suspicious_Prio_For_Equality --
8688      ----------------------------------
8689
8690      function Suspicious_Prio_For_Equality return Boolean is
8691         Par : constant Node_Id := Parent (N);
8692
8693      begin
8694         --  Check if parent node is one of and/or/xor, not parenthesized
8695         --  explicitly, and its own parent is not of this kind. Otherwise,
8696         --  it's a case of chained Boolean conditions which is likely well
8697         --  parenthesized.
8698
8699         if Nkind (Par) in N_Op_And | N_Op_Or | N_Op_Xor
8700           and then Paren_Count (N) = 0
8701           and then Nkind (Parent (Par)) not in N_Op_And | N_Op_Or | N_Op_Xor
8702         then
8703            declare
8704               Compar : Node_Id :=
8705                 (if Left_Opnd (Par) = N then
8706                     Right_Opnd (Par)
8707                  else
8708                     Left_Opnd (Par));
8709            begin
8710               --  Compar may have been rewritten, for example from (a /= b)
8711               --  into not (a = b). Use the Original_Node instead.
8712
8713               Compar := Original_Node (Compar);
8714
8715               --  If the other argument of the and/or/xor is also a
8716               --  comparison, or another and/or/xor then most likely
8717               --  the priorities are correctly set.
8718
8719               return Nkind (Compar) not in N_Op_Boolean;
8720            end;
8721
8722         else
8723            return False;
8724         end if;
8725      end Suspicious_Prio_For_Equality;
8726
8727   --  Start of processing for Resolve_Equality_Op
8728
8729   begin
8730      Set_Etype (N, Base_Type (Typ));
8731      Generate_Reference (T, N, ' ');
8732
8733      if T = Any_Fixed then
8734         T := Unique_Fixed_Point_Type (L);
8735      end if;
8736
8737      if T /= Any_Type then
8738         if T = Any_String    or else
8739            T = Any_Composite or else
8740            T = Any_Character
8741         then
8742            if T = Any_Character then
8743               Ambiguous_Character (L);
8744            else
8745               Error_Msg_N ("ambiguous operands for equality", N);
8746            end if;
8747
8748            Set_Etype (N, Any_Type);
8749            return;
8750
8751         elsif T = Any_Access
8752           or else Ekind (T) in E_Allocator_Type | E_Access_Attribute_Type
8753         then
8754            T := Find_Unique_Access_Type;
8755
8756            if No (T) then
8757               Error_Msg_N ("ambiguous operands for equality", N);
8758               Set_Etype (N, Any_Type);
8759               return;
8760            end if;
8761
8762         --  If expressions must have a single type, and if the context does
8763         --  not impose one the dependent expressions cannot be anonymous
8764         --  access types.
8765
8766         --  Why no similar processing for case expressions???
8767
8768         elsif Ada_Version >= Ada_2012
8769           and then Is_Anonymous_Access_Type (Etype (L))
8770           and then Is_Anonymous_Access_Type (Etype (R))
8771         then
8772            Check_If_Expression (L);
8773            Check_If_Expression (R);
8774         end if;
8775
8776         Resolve (L, T);
8777         Resolve (R, T);
8778
8779         --  If the unique type is a class-wide type then it will be expanded
8780         --  into a dispatching call to the predefined primitive. Therefore we
8781         --  check here for potential violation of such restriction.
8782
8783         if Is_Class_Wide_Type (T) then
8784            Check_Restriction (No_Dispatching_Calls, N);
8785         end if;
8786
8787         --  Only warn for redundant equality comparison to True for objects
8788         --  (e.g. "X = True") and operations (e.g. "(X < Y) = True"). For
8789         --  other expressions, it may be a matter of preference to write
8790         --  "Expr = True" or "Expr".
8791
8792         if Warn_On_Redundant_Constructs
8793           and then Comes_From_Source (N)
8794           and then Comes_From_Source (R)
8795           and then Is_Entity_Name (R)
8796           and then Entity (R) = Standard_True
8797           and then
8798             ((Is_Entity_Name (L) and then Is_Object (Entity (L)))
8799                 or else
8800               Nkind (L) in N_Op)
8801         then
8802            Error_Msg_N -- CODEFIX
8803              ("?r?comparison with True is redundant!", N);
8804            Explain_Redundancy (Original_Node (R));
8805         end if;
8806
8807         --  Warn on a (in)equality between boolean values which is not
8808         --  parenthesized when the parent expression is one of and/or/xor, as
8809         --  this is interpreted as (a = b) op c where most likely a = (b op c)
8810         --  was intended. Do not generate a warning in generic instances, as
8811         --  the problematic expression may be implicitly parenthesized in
8812         --  the generic itself if one of the operators is a generic formal.
8813         --  Also do not generate a warning for generated equality, for
8814         --  example from rewritting a membership test.
8815
8816         if Warn_On_Questionable_Missing_Parens
8817           and then not In_Instance
8818           and then Comes_From_Source (N)
8819           and then Is_Boolean_Type (T)
8820           and then Suspicious_Prio_For_Equality
8821         then
8822            Error_Msg_N ("?q?equality should be parenthesized here!", N);
8823         end if;
8824
8825         --  If the equality is overloaded and the operands have resolved
8826         --  properly, set the proper equality operator on the node. The
8827         --  current setting is the first one found during analysis, which
8828         --  is not necessarily the one to which the node has resolved.
8829
8830         if Is_Overloaded (N) then
8831            declare
8832               I  : Interp_Index;
8833               It : Interp;
8834
8835            begin
8836               Get_First_Interp (N, I, It);
8837
8838               --  If the equality is user-defined, the type of the operands
8839               --  matches that of the formals. For a predefined operator,
8840               --  it is the scope that matters, given that the predefined
8841               --  equality has Any_Type formals. In either case the result
8842               --  type (most often Boolean) must match the context. The scope
8843               --  is either that of the type, if there is a generated equality
8844               --  (when there is an equality for the component type), or else
8845               --  Standard otherwise.
8846
8847               while Present (It.Typ) loop
8848                  if Etype (It.Nam) = Typ
8849                    and then
8850                     (Etype (First_Entity (It.Nam)) = Etype (L)
8851                       or else Scope (It.Nam) = Standard_Standard
8852                       or else Scope (It.Nam) = Scope (T))
8853                  then
8854                     Set_Entity (N, It.Nam);
8855
8856                     Set_Is_Overloaded (N, False);
8857                     exit;
8858                  end if;
8859
8860                  Get_Next_Interp (I, It);
8861               end loop;
8862
8863               --  If expansion is active and this is an inherited operation,
8864               --  replace it with its ancestor. This must not be done during
8865               --  preanalysis because the type may not be frozen yet, as when
8866               --  the context is a precondition or postcondition.
8867
8868               if Present (Alias (Entity (N))) and then Expander_Active then
8869                  Set_Entity (N, Alias (Entity (N)));
8870               end if;
8871            end;
8872         end if;
8873
8874         Check_Unset_Reference (L);
8875         Check_Unset_Reference (R);
8876         Generate_Operator_Reference (N, T);
8877         Check_Low_Bound_Tested (N);
8878
8879         --  If this is an inequality, it may be the implicit inequality
8880         --  created for a user-defined operation, in which case the corres-
8881         --  ponding equality operation is not intrinsic, and the operation
8882         --  cannot be constant-folded. Else fold.
8883
8884         if Nkind (N) = N_Op_Eq
8885           or else Comes_From_Source (Entity (N))
8886           or else Ekind (Entity (N)) = E_Operator
8887           or else Is_Intrinsic_Subprogram
8888                     (Corresponding_Equality (Entity (N)))
8889         then
8890            Analyze_Dimension (N);
8891            Eval_Relational_Op (N);
8892
8893         elsif Nkind (N) = N_Op_Ne
8894           and then Is_Abstract_Subprogram (Entity (N))
8895         then
8896            Error_Msg_NE ("cannot call abstract subprogram &!", N, Entity (N));
8897         end if;
8898
8899         --  Ada 2005: If one operand is an anonymous access type, convert the
8900         --  other operand to it, to ensure that the underlying types match in
8901         --  the back-end. Same for access_to_subprogram, and the conversion
8902         --  verifies that the types are subtype conformant.
8903
8904         --  We apply the same conversion in the case one of the operands is a
8905         --  private subtype of the type of the other.
8906
8907         --  Why the Expander_Active test here ???
8908
8909         if Expander_Active
8910           and then
8911             (Ekind (T) in E_Anonymous_Access_Type
8912                         | E_Anonymous_Access_Subprogram_Type
8913               or else Is_Private_Type (T))
8914         then
8915            if Etype (L) /= T then
8916               Rewrite (L, Unchecked_Convert_To (T, L));
8917               Analyze_And_Resolve (L, T);
8918            end if;
8919
8920            if (Etype (R)) /= T then
8921               Rewrite (R, Unchecked_Convert_To (Etype (L), R));
8922               Analyze_And_Resolve (R, T);
8923            end if;
8924         end if;
8925      end if;
8926   end Resolve_Equality_Op;
8927
8928   ----------------------------------
8929   -- Resolve_Explicit_Dereference --
8930   ----------------------------------
8931
8932   procedure Resolve_Explicit_Dereference (N : Node_Id; Typ : Entity_Id) is
8933      Loc   : constant Source_Ptr := Sloc (N);
8934      New_N : Node_Id;
8935      P     : constant Node_Id := Prefix (N);
8936
8937      P_Typ : Entity_Id;
8938      --  The candidate prefix type, if overloaded
8939
8940      I     : Interp_Index;
8941      It    : Interp;
8942
8943   begin
8944      Check_Fully_Declared_Prefix (Typ, P);
8945      P_Typ := Empty;
8946
8947      --  A useful optimization:  check whether the dereference denotes an
8948      --  element of a container, and if so rewrite it as a call to the
8949      --  corresponding Element function.
8950
8951      --  Disabled for now, on advice of ARG. A more restricted form of the
8952      --  predicate might be acceptable ???
8953
8954      --  if Is_Container_Element (N) then
8955      --     return;
8956      --  end if;
8957
8958      if Is_Overloaded (P) then
8959
8960         --  Use the context type to select the prefix that has the correct
8961         --  designated type. Keep the first match, which will be the inner-
8962         --  most.
8963
8964         Get_First_Interp (P, I, It);
8965
8966         while Present (It.Typ) loop
8967            if Is_Access_Type (It.Typ)
8968              and then Covers (Typ, Designated_Type (It.Typ))
8969            then
8970               if No (P_Typ) then
8971                  P_Typ := It.Typ;
8972               end if;
8973
8974            --  Remove access types that do not match, but preserve access
8975            --  to subprogram interpretations, in case a further dereference
8976            --  is needed (see below).
8977
8978            elsif Ekind (It.Typ) /= E_Access_Subprogram_Type then
8979               Remove_Interp (I);
8980            end if;
8981
8982            Get_Next_Interp (I, It);
8983         end loop;
8984
8985         if Present (P_Typ) then
8986            Resolve (P, P_Typ);
8987            Set_Etype (N, Designated_Type (P_Typ));
8988
8989         else
8990            --  If no interpretation covers the designated type of the prefix,
8991            --  this is the pathological case where not all implementations of
8992            --  the prefix allow the interpretation of the node as a call. Now
8993            --  that the expected type is known, Remove other interpretations
8994            --  from prefix, rewrite it as a call, and resolve again, so that
8995            --  the proper call node is generated.
8996
8997            Get_First_Interp (P, I, It);
8998            while Present (It.Typ) loop
8999               if Ekind (It.Typ) /= E_Access_Subprogram_Type then
9000                  Remove_Interp (I);
9001               end if;
9002
9003               Get_Next_Interp (I, It);
9004            end loop;
9005
9006            New_N :=
9007              Make_Function_Call (Loc,
9008                Name =>
9009                  Make_Explicit_Dereference (Loc,
9010                    Prefix => P),
9011                Parameter_Associations => New_List);
9012
9013            Save_Interps (N, New_N);
9014            Rewrite (N, New_N);
9015            Analyze_And_Resolve (N, Typ);
9016            return;
9017         end if;
9018
9019      --  If not overloaded, resolve P with its own type
9020
9021      else
9022         Resolve (P);
9023      end if;
9024
9025      --  If the prefix might be null, add an access check
9026
9027      if Is_Access_Type (Etype (P))
9028        and then not Can_Never_Be_Null (Etype (P))
9029      then
9030         Apply_Access_Check (N);
9031      end if;
9032
9033      --  If the designated type is a packed unconstrained array type, and the
9034      --  explicit dereference is not in the context of an attribute reference,
9035      --  then we must compute and set the actual subtype, since it is needed
9036      --  by Gigi. The reason we exclude the attribute case is that this is
9037      --  handled fine by Gigi, and in fact we use such attributes to build the
9038      --  actual subtype. We also exclude generated code (which builds actual
9039      --  subtypes directly if they are needed).
9040
9041      if Is_Packed_Array (Etype (N))
9042        and then not Is_Constrained (Etype (N))
9043        and then Nkind (Parent (N)) /= N_Attribute_Reference
9044        and then Comes_From_Source (N)
9045      then
9046         Set_Etype (N, Get_Actual_Subtype (N));
9047      end if;
9048
9049      Analyze_Dimension (N);
9050
9051      --  Note: No Eval processing is required for an explicit dereference,
9052      --  because such a name can never be static.
9053
9054   end Resolve_Explicit_Dereference;
9055
9056   -------------------------------------
9057   -- Resolve_Expression_With_Actions --
9058   -------------------------------------
9059
9060   procedure Resolve_Expression_With_Actions (N : Node_Id; Typ : Entity_Id) is
9061
9062      function OK_For_Static (Act : Node_Id) return Boolean;
9063      --  True if Act is an action of a declare_expression that is allowed in a
9064      --  static declare_expression.
9065
9066      function All_OK_For_Static return Boolean;
9067      --  True if all actions of N are allowed in a static declare_expression.
9068
9069      function Get_Literal (Expr : Node_Id) return Node_Id;
9070      --  Expr is an expression with compile-time-known value. This returns the
9071      --  literal node that reprsents that value.
9072
9073      function OK_For_Static (Act : Node_Id) return Boolean is
9074      begin
9075         case Nkind (Act) is
9076            when N_Object_Declaration =>
9077               if Constant_Present (Act)
9078                 and then Is_Static_Expression (Expression (Act))
9079               then
9080                  return True;
9081               end if;
9082
9083            when N_Object_Renaming_Declaration =>
9084               if Statically_Names_Object (Name (Act)) then
9085                  return True;
9086               end if;
9087
9088            when others =>
9089               --  No other declarations, nor even pragmas, are allowed in a
9090               --  declare expression, so if we see something else, it must be
9091               --  an internally generated expression_with_actions.
9092               null;
9093         end case;
9094
9095         return False;
9096      end OK_For_Static;
9097
9098      function All_OK_For_Static return Boolean is
9099         Act : Node_Id := First (Actions (N));
9100      begin
9101         while Present (Act) loop
9102            if not OK_For_Static (Act) then
9103               return False;
9104            end if;
9105
9106            Next (Act);
9107         end loop;
9108
9109         return True;
9110      end All_OK_For_Static;
9111
9112      function Get_Literal (Expr : Node_Id) return Node_Id is
9113         pragma Assert (Compile_Time_Known_Value (Expr));
9114         Result : Node_Id;
9115      begin
9116         case Nkind (Expr) is
9117            when N_Has_Entity =>
9118               if Ekind (Entity (Expr)) = E_Enumeration_Literal then
9119                  Result := Expr;
9120               else
9121                  Result := Constant_Value (Entity (Expr));
9122               end if;
9123            when N_Numeric_Or_String_Literal =>
9124               Result := Expr;
9125            when others =>
9126               raise Program_Error;
9127         end case;
9128
9129         pragma Assert
9130           (Nkind (Result) in N_Numeric_Or_String_Literal
9131              or else Ekind (Entity (Result)) = E_Enumeration_Literal);
9132         return Result;
9133      end Get_Literal;
9134
9135      Loc : constant Source_Ptr := Sloc (N);
9136
9137   begin
9138      Set_Etype (N, Typ);
9139
9140      if Is_Empty_List (Actions (N)) then
9141         pragma Assert (All_OK_For_Static); null;
9142      end if;
9143
9144      --  If the value of the expression is known at compile time, and all
9145      --  of the actions (if any) are suitable, then replace the declare
9146      --  expression with its expression. This allows the declare expression
9147      --  as a whole to be static if appropriate. See AI12-0368.
9148
9149      if Compile_Time_Known_Value (Expression (N)) then
9150         if Is_Empty_List (Actions (N)) then
9151            Rewrite (N, Expression (N));
9152         elsif All_OK_For_Static then
9153            Rewrite
9154              (N, New_Copy_Tree
9155                    (Get_Literal (Expression (N)), New_Sloc => Loc));
9156         end if;
9157      end if;
9158   end Resolve_Expression_With_Actions;
9159
9160   ----------------------------------
9161   -- Resolve_Generalized_Indexing --
9162   ----------------------------------
9163
9164   procedure Resolve_Generalized_Indexing (N : Node_Id; Typ : Entity_Id) is
9165      Indexing : constant Node_Id := Generalized_Indexing (N);
9166   begin
9167      Rewrite (N, Indexing);
9168      Resolve (N, Typ);
9169   end Resolve_Generalized_Indexing;
9170
9171   ---------------------------
9172   -- Resolve_If_Expression --
9173   ---------------------------
9174
9175   procedure Resolve_If_Expression (N : Node_Id; Typ : Entity_Id) is
9176      procedure Apply_Check (Expr : Node_Id);
9177      --  When a dependent expression is of a subtype different from
9178      --  the context subtype, then insert a qualification to ensure
9179      --  the generation of a constraint check. This was previously
9180      --  for scalar types. For array types apply a length check, given
9181      --  that the context in general allows sliding, while a qualified
9182      --  expression forces equality of bounds.
9183
9184      Result_Type  : Entity_Id := Typ;
9185      --  So in most cases the type of the If_Expression and of its
9186      --  dependent expressions is that of the context. However, if
9187      --  the expression is the index of an Indexed_Component, we must
9188      --  ensure that a proper index check is applied, rather than a
9189      --  range check on the index type (which might be discriminant
9190      --  dependent). In this case we resolve with the base type of the
9191      --  index type, and the index check is generated in the resolution
9192      --  of the indexed_component above.
9193
9194      -----------------
9195      -- Apply_Check --
9196      -----------------
9197
9198      procedure Apply_Check (Expr : Node_Id) is
9199         Expr_Typ : constant Entity_Id  := Etype (Expr);
9200         Loc      : constant Source_Ptr := Sloc (Expr);
9201
9202      begin
9203         if Expr_Typ = Typ
9204           or else Is_Tagged_Type (Typ)
9205           or else Is_Access_Type (Typ)
9206           or else not Is_Constrained (Typ)
9207           or else Inside_A_Generic
9208         then
9209            null;
9210
9211         elsif Is_Array_Type (Typ) then
9212            Apply_Length_Check (Expr, Typ);
9213
9214         else
9215            Rewrite (Expr,
9216              Make_Qualified_Expression (Loc,
9217                Subtype_Mark => New_Occurrence_Of (Result_Type, Loc),
9218                Expression   => Relocate_Node (Expr)));
9219
9220            Analyze_And_Resolve (Expr, Result_Type);
9221         end if;
9222      end Apply_Check;
9223
9224      --  Local variables
9225
9226      Condition : constant Node_Id := First (Expressions (N));
9227      Else_Expr : Node_Id;
9228      Then_Expr : Node_Id;
9229
9230   --  Start of processing for Resolve_If_Expression
9231
9232   begin
9233      --  Defend against malformed expressions
9234
9235      if No (Condition) then
9236         return;
9237      end if;
9238
9239      if Present (Parent (N))
9240        and then (Nkind (Parent (N)) = N_Indexed_Component
9241                    or else Nkind (Parent (Parent (N))) = N_Indexed_Component)
9242      then
9243         Result_Type := Base_Type (Typ);
9244      end if;
9245
9246      Then_Expr := Next (Condition);
9247
9248      if No (Then_Expr) then
9249         return;
9250      end if;
9251
9252      Else_Expr := Next (Then_Expr);
9253
9254      Resolve (Condition, Any_Boolean);
9255      Resolve (Then_Expr, Result_Type);
9256      Apply_Check (Then_Expr);
9257
9258      --  If ELSE expression present, just resolve using the determined type
9259      --  If type is universal, resolve to any member of the class.
9260
9261      if Present (Else_Expr) then
9262         if Typ = Universal_Integer then
9263            Resolve (Else_Expr, Any_Integer);
9264
9265         elsif Typ = Universal_Real then
9266            Resolve (Else_Expr, Any_Real);
9267
9268         else
9269            Resolve (Else_Expr, Result_Type);
9270         end if;
9271
9272         Apply_Check (Else_Expr);
9273
9274         --  Apply RM 4.5.7 (17/3): whether the expression is statically or
9275         --  dynamically tagged must be known statically.
9276
9277         if Is_Tagged_Type (Typ) and then not Is_Class_Wide_Type (Typ) then
9278            if Is_Dynamically_Tagged (Then_Expr) /=
9279               Is_Dynamically_Tagged (Else_Expr)
9280            then
9281               Error_Msg_N ("all or none of the dependent expressions "
9282                            & "can be dynamically tagged", N);
9283            end if;
9284         end if;
9285
9286      --  If no ELSE expression is present, root type must be Standard.Boolean
9287      --  and we provide a Standard.True result converted to the appropriate
9288      --  Boolean type (in case it is a derived boolean type).
9289
9290      elsif Root_Type (Typ) = Standard_Boolean then
9291         Else_Expr :=
9292           Convert_To (Typ, New_Occurrence_Of (Standard_True, Sloc (N)));
9293         Analyze_And_Resolve (Else_Expr, Result_Type);
9294         Append_To (Expressions (N), Else_Expr);
9295
9296      else
9297         Error_Msg_N ("can only omit ELSE expression in Boolean case", N);
9298         Append_To (Expressions (N), Error);
9299      end if;
9300
9301      Set_Etype (N, Result_Type);
9302
9303      if not Error_Posted (N) then
9304         Eval_If_Expression (N);
9305      end if;
9306
9307      Analyze_Dimension (N);
9308   end Resolve_If_Expression;
9309
9310   ----------------------------------
9311   -- Resolve_Implicit_Dereference --
9312   ----------------------------------
9313
9314   procedure Resolve_Implicit_Dereference (P : Node_Id) is
9315      Desig_Typ : Entity_Id;
9316
9317   begin
9318      --  In an instance the proper view may not always be correct for
9319      --  private types, see e.g. Sem_Type.Covers for similar handling.
9320
9321      if Is_Private_Type (Etype (P))
9322        and then Present (Full_View (Etype (P)))
9323        and then Is_Access_Type (Full_View (Etype (P)))
9324        and then In_Instance
9325      then
9326         Set_Etype (P, Full_View (Etype (P)));
9327      end if;
9328
9329      if Is_Access_Type (Etype (P)) then
9330         Desig_Typ := Implicitly_Designated_Type (Etype (P));
9331         Insert_Explicit_Dereference (P);
9332         Analyze_And_Resolve (P, Desig_Typ);
9333      end if;
9334   end Resolve_Implicit_Dereference;
9335
9336   -------------------------------
9337   -- Resolve_Indexed_Component --
9338   -------------------------------
9339
9340   procedure Resolve_Indexed_Component (N : Node_Id; Typ : Entity_Id) is
9341      Pref       : constant Node_Id := Prefix (N);
9342      Expr       : Node_Id;
9343      Array_Type : Entity_Id := Empty; -- to prevent junk warning
9344      Index      : Node_Id;
9345
9346   begin
9347      if Present (Generalized_Indexing (N)) then
9348         Resolve_Generalized_Indexing (N, Typ);
9349         return;
9350      end if;
9351
9352      if Is_Overloaded (Pref) then
9353
9354         --  Use the context type to select the prefix that yields the correct
9355         --  component type.
9356
9357         declare
9358            I     : Interp_Index;
9359            It    : Interp;
9360            I1    : Interp_Index := 0;
9361            Found : Boolean := False;
9362
9363         begin
9364            Get_First_Interp (Pref, I, It);
9365            while Present (It.Typ) loop
9366               if (Is_Array_Type (It.Typ)
9367                     and then Covers (Typ, Component_Type (It.Typ)))
9368                 or else (Is_Access_Type (It.Typ)
9369                            and then Is_Array_Type (Designated_Type (It.Typ))
9370                            and then
9371                              Covers
9372                                (Typ,
9373                                 Component_Type (Designated_Type (It.Typ))))
9374               then
9375                  if Found then
9376                     It := Disambiguate (Pref, I1, I, Any_Type);
9377
9378                     if It = No_Interp then
9379                        Error_Msg_N ("ambiguous prefix for indexing",  N);
9380                        Set_Etype (N, Typ);
9381                        return;
9382
9383                     else
9384                        Found := True;
9385                        Array_Type := It.Typ;
9386                        I1 := I;
9387                     end if;
9388
9389                  else
9390                     Found := True;
9391                     Array_Type := It.Typ;
9392                     I1 := I;
9393                  end if;
9394               end if;
9395
9396               Get_Next_Interp (I, It);
9397            end loop;
9398         end;
9399
9400      else
9401         Array_Type := Etype (Pref);
9402      end if;
9403
9404      Resolve (Pref, Array_Type);
9405      Array_Type := Get_Actual_Subtype_If_Available (Pref);
9406
9407      --  If the prefix's type is an access type, get to the real array type.
9408      --  Note: we do not apply an access check because an explicit dereference
9409      --  will be introduced later, and the check will happen there.
9410
9411      if Is_Access_Type (Array_Type) then
9412         Array_Type := Implicitly_Designated_Type (Array_Type);
9413      end if;
9414
9415      --  If name was overloaded, set component type correctly now.
9416      --  If a misplaced call to an entry family (which has no index types)
9417      --  return. Error will be diagnosed from calling context.
9418
9419      if Is_Array_Type (Array_Type) then
9420         Set_Etype (N, Component_Type (Array_Type));
9421      else
9422         return;
9423      end if;
9424
9425      Index := First_Index (Array_Type);
9426      Expr  := First (Expressions (N));
9427
9428      --  The prefix may have resolved to a string literal, in which case its
9429      --  etype has a special representation. This is only possible currently
9430      --  if the prefix is a static concatenation, written in functional
9431      --  notation.
9432
9433      if Ekind (Array_Type) = E_String_Literal_Subtype then
9434         Resolve (Expr, Standard_Positive);
9435
9436      else
9437         while Present (Index) and then Present (Expr) loop
9438            Resolve (Expr, Etype (Index));
9439            Check_Unset_Reference (Expr);
9440
9441            Apply_Scalar_Range_Check (Expr, Etype (Index));
9442
9443            Next_Index (Index);
9444            Next (Expr);
9445         end loop;
9446      end if;
9447
9448      Resolve_Implicit_Dereference (Pref);
9449      Analyze_Dimension (N);
9450
9451      --  Do not generate the warning on suspicious index if we are analyzing
9452      --  package Ada.Tags; otherwise we will report the warning with the
9453      --  Prims_Ptr field of the dispatch table.
9454
9455      if Scope (Etype (Pref)) = Standard_Standard
9456        or else not
9457          Is_RTU (Cunit_Entity (Get_Source_Unit (Etype (Pref))), Ada_Tags)
9458      then
9459         Warn_On_Suspicious_Index (Pref, First (Expressions (N)));
9460         Eval_Indexed_Component (N);
9461      end if;
9462
9463      --  If the array type is atomic and the component is not, then this is
9464      --  worth a warning before Ada 2022, since we have a situation where the
9465      --  access to the component may cause extra read/writes of the atomic
9466      --  object, or partial word accesses, both of which may be unexpected.
9467
9468      if Nkind (N) = N_Indexed_Component
9469        and then Is_Atomic_Ref_With_Address (N)
9470        and then not (Has_Atomic_Components (Array_Type)
9471                       or else (Is_Entity_Name (Pref)
9472                                 and then Has_Atomic_Components
9473                                            (Entity (Pref))))
9474        and then not Is_Atomic (Component_Type (Array_Type))
9475        and then Ada_Version < Ada_2022
9476      then
9477         Error_Msg_N
9478           ("??access to non-atomic component of atomic array", Pref);
9479         Error_Msg_N
9480           ("??\may cause unexpected accesses to atomic object", Pref);
9481      end if;
9482   end Resolve_Indexed_Component;
9483
9484   -----------------------------
9485   -- Resolve_Integer_Literal --
9486   -----------------------------
9487
9488   procedure Resolve_Integer_Literal (N : Node_Id; Typ : Entity_Id) is
9489   begin
9490      Set_Etype (N, Typ);
9491      Eval_Integer_Literal (N);
9492   end Resolve_Integer_Literal;
9493
9494   --------------------------------
9495   -- Resolve_Intrinsic_Operator --
9496   --------------------------------
9497
9498   procedure Resolve_Intrinsic_Operator  (N : Node_Id; Typ : Entity_Id) is
9499      Btyp : constant Entity_Id := Base_Type (Underlying_Type (Typ));
9500      Op   : Entity_Id;
9501      Arg1 : Node_Id;
9502      Arg2 : Node_Id;
9503
9504      function Convert_Operand (Opnd : Node_Id) return Node_Id;
9505      --  If the operand is a literal, it cannot be the expression in a
9506      --  conversion. Use a qualified expression instead.
9507
9508      ---------------------
9509      -- Convert_Operand --
9510      ---------------------
9511
9512      function Convert_Operand (Opnd : Node_Id) return Node_Id is
9513         Loc : constant Source_Ptr := Sloc (Opnd);
9514         Res : Node_Id;
9515
9516      begin
9517         if Nkind (Opnd) in N_Integer_Literal | N_Real_Literal then
9518            Res :=
9519              Make_Qualified_Expression (Loc,
9520                Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
9521                Expression   => Relocate_Node (Opnd));
9522            Analyze (Res);
9523
9524         else
9525            Res := Unchecked_Convert_To (Btyp, Opnd);
9526         end if;
9527
9528         return Res;
9529      end Convert_Operand;
9530
9531   --  Start of processing for Resolve_Intrinsic_Operator
9532
9533   begin
9534      --  We must preserve the original entity in a generic setting, so that
9535      --  the legality of the operation can be verified in an instance.
9536
9537      if not Expander_Active then
9538         return;
9539      end if;
9540
9541      Op := Entity (N);
9542      while Scope (Op) /= Standard_Standard loop
9543         Op := Homonym (Op);
9544         pragma Assert (Present (Op));
9545      end loop;
9546
9547      Set_Entity (N, Op);
9548      Set_Is_Overloaded (N, False);
9549
9550      --  If the result or operand types are private, rewrite with unchecked
9551      --  conversions on the operands and the result, to expose the proper
9552      --  underlying numeric type.
9553
9554      if Is_Private_Type (Typ)
9555        or else Is_Private_Type (Etype (Left_Opnd (N)))
9556        or else Is_Private_Type (Etype (Right_Opnd (N)))
9557      then
9558         Arg1 := Convert_Operand (Left_Opnd (N));
9559
9560         if Nkind (N) = N_Op_Expon then
9561            Arg2 := Unchecked_Convert_To (Standard_Integer, Right_Opnd (N));
9562         else
9563            Arg2 := Convert_Operand (Right_Opnd (N));
9564         end if;
9565
9566         if Nkind (Arg1) = N_Type_Conversion then
9567            Save_Interps (Left_Opnd (N),  Expression (Arg1));
9568         end if;
9569
9570         if Nkind (Arg2) = N_Type_Conversion then
9571            Save_Interps (Right_Opnd (N), Expression (Arg2));
9572         end if;
9573
9574         Set_Left_Opnd  (N, Arg1);
9575         Set_Right_Opnd (N, Arg2);
9576
9577         Set_Etype (N, Btyp);
9578         Rewrite (N, Unchecked_Convert_To (Typ, N));
9579         Resolve (N, Typ);
9580
9581      elsif Typ /= Etype (Left_Opnd (N))
9582        or else Typ /= Etype (Right_Opnd (N))
9583      then
9584         --  Add explicit conversion where needed, and save interpretations in
9585         --  case operands are overloaded.
9586
9587         Arg1 := Convert_To (Typ, Left_Opnd  (N));
9588         Arg2 := Convert_To (Typ, Right_Opnd (N));
9589
9590         if Nkind (Arg1) = N_Type_Conversion then
9591            Save_Interps (Left_Opnd (N), Expression (Arg1));
9592         else
9593            Save_Interps (Left_Opnd (N), Arg1);
9594         end if;
9595
9596         if Nkind (Arg2) = N_Type_Conversion then
9597            Save_Interps (Right_Opnd (N), Expression (Arg2));
9598         else
9599            Save_Interps (Right_Opnd (N), Arg2);
9600         end if;
9601
9602         Rewrite (Left_Opnd  (N), Arg1);
9603         Rewrite (Right_Opnd (N), Arg2);
9604         Analyze (Arg1);
9605         Analyze (Arg2);
9606         Resolve_Arithmetic_Op (N, Typ);
9607
9608      else
9609         Resolve_Arithmetic_Op (N, Typ);
9610      end if;
9611   end Resolve_Intrinsic_Operator;
9612
9613   --------------------------------------
9614   -- Resolve_Intrinsic_Unary_Operator --
9615   --------------------------------------
9616
9617   procedure Resolve_Intrinsic_Unary_Operator
9618     (N   : Node_Id;
9619      Typ : Entity_Id)
9620   is
9621      Btyp : constant Entity_Id := Base_Type (Underlying_Type (Typ));
9622      Op   : Entity_Id;
9623      Arg2 : Node_Id;
9624
9625   begin
9626      Op := Entity (N);
9627      while Scope (Op) /= Standard_Standard loop
9628         Op := Homonym (Op);
9629         pragma Assert (Present (Op));
9630      end loop;
9631
9632      Set_Entity (N, Op);
9633
9634      if Is_Private_Type (Typ) then
9635         Arg2 := Unchecked_Convert_To (Btyp, Right_Opnd (N));
9636         Save_Interps (Right_Opnd (N), Expression (Arg2));
9637
9638         Set_Right_Opnd (N, Arg2);
9639
9640         Set_Etype (N, Btyp);
9641         Rewrite (N, Unchecked_Convert_To (Typ, N));
9642         Resolve (N, Typ);
9643
9644      else
9645         Resolve_Unary_Op (N, Typ);
9646      end if;
9647   end Resolve_Intrinsic_Unary_Operator;
9648
9649   ------------------------
9650   -- Resolve_Logical_Op --
9651   ------------------------
9652
9653   procedure Resolve_Logical_Op (N : Node_Id; Typ : Entity_Id) is
9654      B_Typ : Entity_Id;
9655
9656   begin
9657      Check_No_Direct_Boolean_Operators (N);
9658
9659      --  Predefined operations on scalar types yield the base type. On the
9660      --  other hand, logical operations on arrays yield the type of the
9661      --  arguments (and the context).
9662
9663      if Is_Array_Type (Typ) then
9664         B_Typ := Typ;
9665      else
9666         B_Typ := Base_Type (Typ);
9667      end if;
9668
9669      --  The following test is required because the operands of the operation
9670      --  may be literals, in which case the resulting type appears to be
9671      --  compatible with a signed integer type, when in fact it is compatible
9672      --  only with modular types. If the context itself is universal, the
9673      --  operation is illegal.
9674
9675      if not Valid_Boolean_Arg (Typ) then
9676         Error_Msg_N ("invalid context for logical operation", N);
9677         Set_Etype (N, Any_Type);
9678         return;
9679
9680      elsif Typ = Any_Modular then
9681         Error_Msg_N
9682           ("no modular type available in this context", N);
9683         Set_Etype (N, Any_Type);
9684         return;
9685
9686      elsif Is_Modular_Integer_Type (Typ)
9687        and then Etype (Left_Opnd (N)) = Universal_Integer
9688        and then Etype (Right_Opnd (N)) = Universal_Integer
9689      then
9690         Check_For_Visible_Operator (N, B_Typ);
9691      end if;
9692
9693      --  Replace AND by AND THEN, or OR by OR ELSE, if Short_Circuit_And_Or
9694      --  is active and the result type is standard Boolean (do not mess with
9695      --  ops that return a nonstandard Boolean type, because something strange
9696      --  is going on).
9697
9698      --  Note: you might expect this replacement to be done during expansion,
9699      --  but that doesn't work, because when the pragma Short_Circuit_And_Or
9700      --  is used, no part of the right operand of an "and" or "or" operator
9701      --  should be executed if the left operand would short-circuit the
9702      --  evaluation of the corresponding "and then" or "or else". If we left
9703      --  the replacement to expansion time, then run-time checks associated
9704      --  with such operands would be evaluated unconditionally, due to being
9705      --  before the condition prior to the rewriting as short-circuit forms
9706      --  during expansion.
9707
9708      if Short_Circuit_And_Or
9709        and then B_Typ = Standard_Boolean
9710        and then Nkind (N) in N_Op_And | N_Op_Or
9711      then
9712         --  Mark the corresponding putative SCO operator as truly a logical
9713         --  (and short-circuit) operator.
9714
9715         if Generate_SCO and then Comes_From_Source (N) then
9716            Set_SCO_Logical_Operator (N);
9717         end if;
9718
9719         if Nkind (N) = N_Op_And then
9720            Rewrite (N,
9721              Make_And_Then (Sloc (N),
9722                Left_Opnd  => Relocate_Node (Left_Opnd (N)),
9723                Right_Opnd => Relocate_Node (Right_Opnd (N))));
9724            Analyze_And_Resolve (N, B_Typ);
9725
9726         --  Case of OR changed to OR ELSE
9727
9728         else
9729            Rewrite (N,
9730              Make_Or_Else (Sloc (N),
9731                Left_Opnd  => Relocate_Node (Left_Opnd (N)),
9732                Right_Opnd => Relocate_Node (Right_Opnd (N))));
9733            Analyze_And_Resolve (N, B_Typ);
9734         end if;
9735
9736         --  Return now, since analysis of the rewritten ops will take care of
9737         --  other reference bookkeeping and expression folding.
9738
9739         return;
9740      end if;
9741
9742      Resolve (Left_Opnd (N), B_Typ);
9743      Resolve (Right_Opnd (N), B_Typ);
9744
9745      Check_Unset_Reference (Left_Opnd  (N));
9746      Check_Unset_Reference (Right_Opnd (N));
9747
9748      Set_Etype (N, B_Typ);
9749      Generate_Operator_Reference (N, B_Typ);
9750      Eval_Logical_Op (N);
9751   end Resolve_Logical_Op;
9752
9753   ---------------------------
9754   -- Resolve_Membership_Op --
9755   ---------------------------
9756
9757   --  The context can only be a boolean type, and does not determine the
9758   --  arguments. Arguments should be unambiguous, but the preference rule for
9759   --  universal types applies.
9760
9761   procedure Resolve_Membership_Op (N : Node_Id; Typ : Entity_Id) is
9762      pragma Assert (Is_Boolean_Type (Typ));
9763
9764      L : constant Node_Id := Left_Opnd  (N);
9765      R : constant Node_Id := Right_Opnd (N);
9766      T : Entity_Id;
9767
9768      procedure Resolve_Set_Membership;
9769      --  Analysis has determined a unique type for the left operand. Use it as
9770      --  the basis to resolve the disjuncts.
9771
9772      ----------------------------
9773      -- Resolve_Set_Membership --
9774      ----------------------------
9775
9776      procedure Resolve_Set_Membership is
9777         Alt  : Node_Id;
9778
9779      begin
9780         --  If the left operand is overloaded, find type compatible with not
9781         --  overloaded alternative of the right operand.
9782
9783         Alt := First (Alternatives (N));
9784         if Is_Overloaded (L) then
9785            T := Empty;
9786            while Present (Alt) loop
9787               if not Is_Overloaded (Alt) then
9788                  T := Intersect_Types (L, Alt);
9789                  exit;
9790               else
9791                  Next (Alt);
9792               end if;
9793            end loop;
9794
9795            --  Unclear how to resolve expression if all alternatives are also
9796            --  overloaded.
9797
9798            if No (T) then
9799               Error_Msg_N ("ambiguous expression", N);
9800            end if;
9801
9802         else
9803            T := Intersect_Types (L, Alt);
9804         end if;
9805
9806         Resolve (L, T);
9807
9808         Alt := First (Alternatives (N));
9809         while Present (Alt) loop
9810
9811            --  Alternative is an expression, a range
9812            --  or a subtype mark.
9813
9814            if not Is_Entity_Name (Alt)
9815              or else not Is_Type (Entity (Alt))
9816            then
9817               Resolve (Alt, T);
9818            end if;
9819
9820            Next (Alt);
9821         end loop;
9822
9823         --  Check for duplicates for discrete case
9824
9825         if Is_Discrete_Type (T) then
9826            declare
9827               type Ent is record
9828                  Alt : Node_Id;
9829                  Val : Uint;
9830               end record;
9831
9832               Alts  : array (0 .. List_Length (Alternatives (N))) of Ent;
9833               Nalts : Nat;
9834
9835            begin
9836               --  Loop checking duplicates. This is quadratic, but giant sets
9837               --  are unlikely in this context so it's a reasonable choice.
9838
9839               Nalts := 0;
9840               Alt := First (Alternatives (N));
9841               while Present (Alt) loop
9842                  if Is_OK_Static_Expression (Alt)
9843                    and then Nkind (Alt) in N_Integer_Literal
9844                                          | N_Character_Literal
9845                                          | N_Has_Entity
9846                  then
9847                     Nalts := Nalts + 1;
9848                     Alts (Nalts) := (Alt, Expr_Value (Alt));
9849
9850                     for J in 1 .. Nalts - 1 loop
9851                        if Alts (J).Val = Alts (Nalts).Val then
9852                           Error_Msg_Sloc := Sloc (Alts (J).Alt);
9853                           Error_Msg_N ("duplicate of value given#??", Alt);
9854                        end if;
9855                     end loop;
9856                  end if;
9857
9858                  Next (Alt);
9859               end loop;
9860            end;
9861         end if;
9862
9863         --  RM 4.5.2 (28.1/3) specifies that for types other than records or
9864         --  limited types, evaluation of a membership test uses the predefined
9865         --  equality for the type. This may be confusing to users, and the
9866         --  following warning appears useful for the most common case.
9867
9868         if Is_Scalar_Type (Etype (L))
9869           and then Present (Get_User_Defined_Eq (Etype (L)))
9870         then
9871            Error_Msg_NE
9872              ("membership test on& uses predefined equality?", N, Etype (L));
9873            Error_Msg_N
9874              ("\even if user-defined equality exists (RM 4.5.2 (28.1/3)?", N);
9875         end if;
9876      end Resolve_Set_Membership;
9877
9878   --  Start of processing for Resolve_Membership_Op
9879
9880   begin
9881      if L = Error or else R = Error then
9882         return;
9883      end if;
9884
9885      if Present (Alternatives (N)) then
9886         Resolve_Set_Membership;
9887         goto SM_Exit;
9888
9889      elsif not Is_Overloaded (R)
9890        and then Is_Universal_Numeric_Type (Etype (R))
9891        and then Is_Overloaded (L)
9892      then
9893         T := Etype (R);
9894
9895      --  Ada 2005 (AI-251): Support the following case:
9896
9897      --      type I is interface;
9898      --      type T is tagged ...
9899
9900      --      function Test (O : I'Class) is
9901      --      begin
9902      --         return O in T'Class.
9903      --      end Test;
9904
9905      --  In this case we have nothing else to do. The membership test will be
9906      --  done at run time.
9907
9908      elsif Ada_Version >= Ada_2005
9909        and then Is_Class_Wide_Type (Etype (L))
9910        and then Is_Interface (Etype (L))
9911        and then not Is_Interface (Etype (R))
9912      then
9913         return;
9914      else
9915         T := Intersect_Types (L, R);
9916      end if;
9917
9918      --  If mixed-mode operations are present and operands are all literal,
9919      --  the only interpretation involves Duration, which is probably not
9920      --  the intention of the programmer.
9921
9922      if T = Any_Fixed then
9923         T := Unique_Fixed_Point_Type (N);
9924
9925         if T = Any_Type then
9926            return;
9927         end if;
9928      end if;
9929
9930      Resolve (L, T);
9931      Check_Unset_Reference (L);
9932
9933      if Nkind (R) = N_Range
9934        and then not Is_Scalar_Type (T)
9935      then
9936         Error_Msg_N ("scalar type required for range", R);
9937      end if;
9938
9939      if Is_Entity_Name (R) then
9940         Freeze_Expression (R);
9941      else
9942         Resolve (R, T);
9943         Check_Unset_Reference (R);
9944      end if;
9945
9946      --  Here after resolving membership operation
9947
9948      <<SM_Exit>>
9949
9950      Eval_Membership_Op (N);
9951   end Resolve_Membership_Op;
9952
9953   ------------------
9954   -- Resolve_Null --
9955   ------------------
9956
9957   procedure Resolve_Null (N : Node_Id; Typ : Entity_Id) is
9958      Loc : constant Source_Ptr := Sloc (N);
9959
9960   begin
9961      --  Handle restriction against anonymous null access values This
9962      --  restriction can be turned off using -gnatdj.
9963
9964      --  Ada 2005 (AI-231): Remove restriction
9965
9966      if Ada_Version < Ada_2005
9967        and then not Debug_Flag_J
9968        and then Ekind (Typ) = E_Anonymous_Access_Type
9969        and then Comes_From_Source (N)
9970      then
9971         --  In the common case of a call which uses an explicitly null value
9972         --  for an access parameter, give specialized error message.
9973
9974         if Nkind (Parent (N)) in N_Subprogram_Call then
9975            Error_Msg_N
9976              ("NULL is not allowed as argument for an access parameter", N);
9977
9978         --  Standard message for all other cases (are there any?)
9979
9980         else
9981            Error_Msg_N
9982              ("NULL cannot be of an anonymous access type", N);
9983         end if;
9984      end if;
9985
9986      --  Ada 2005 (AI-231): Generate the null-excluding check in case of
9987      --  assignment to a null-excluding object.
9988
9989      if Ada_Version >= Ada_2005
9990        and then Can_Never_Be_Null (Typ)
9991        and then Nkind (Parent (N)) = N_Assignment_Statement
9992      then
9993         if Inside_Init_Proc then
9994
9995            --  Decide whether to generate an if_statement around our
9996            --  null-excluding check to avoid them on certain internal object
9997            --  declarations by looking at the type the current Init_Proc
9998            --  belongs to.
9999
10000            --  Generate:
10001            --    if T1b_skip_null_excluding_check then
10002            --       [constraint_error "access check failed"]
10003            --    end if;
10004
10005            if Needs_Conditional_Null_Excluding_Check
10006                (Etype (First_Formal (Enclosing_Init_Proc)))
10007            then
10008               Insert_Action (N,
10009                 Make_If_Statement (Loc,
10010                   Condition       =>
10011                     Make_Identifier (Loc,
10012                       New_External_Name
10013                         (Chars (Typ), "_skip_null_excluding_check")),
10014                   Then_Statements =>
10015                     New_List (
10016                       Make_Raise_Constraint_Error (Loc,
10017                         Reason => CE_Access_Check_Failed))));
10018
10019            --  Otherwise, simply create the check
10020
10021            else
10022               Insert_Action (N,
10023                 Make_Raise_Constraint_Error (Loc,
10024                   Reason => CE_Access_Check_Failed));
10025            end if;
10026         else
10027            Insert_Action
10028              (Compile_Time_Constraint_Error (N,
10029                 "(Ada 2005) NULL not allowed in null-excluding objects??"),
10030               Make_Raise_Constraint_Error (Loc,
10031                 Reason => CE_Access_Check_Failed));
10032         end if;
10033      end if;
10034
10035      --  In a distributed context, null for a remote access to subprogram may
10036      --  need to be replaced with a special record aggregate. In this case,
10037      --  return after having done the transformation.
10038
10039      if (Ekind (Typ) = E_Record_Type
10040           or else Is_Remote_Access_To_Subprogram_Type (Typ))
10041        and then Remote_AST_Null_Value (N, Typ)
10042      then
10043         return;
10044      end if;
10045
10046      --  The null literal takes its type from the context
10047
10048      Set_Etype (N, Typ);
10049   end Resolve_Null;
10050
10051   -----------------------
10052   -- Resolve_Op_Concat --
10053   -----------------------
10054
10055   procedure Resolve_Op_Concat (N : Node_Id; Typ : Entity_Id) is
10056
10057      --  We wish to avoid deep recursion, because concatenations are often
10058      --  deeply nested, as in A&B&...&Z. Therefore, we walk down the left
10059      --  operands nonrecursively until we find something that is not a simple
10060      --  concatenation (A in this case). We resolve that, and then walk back
10061      --  up the tree following Parent pointers, calling Resolve_Op_Concat_Rest
10062      --  to do the rest of the work at each level. The Parent pointers allow
10063      --  us to avoid recursion, and thus avoid running out of memory. See also
10064      --  Sem_Ch4.Analyze_Concatenation, where a similar approach is used.
10065
10066      NN  : Node_Id := N;
10067      Op1 : Node_Id;
10068
10069   begin
10070      --  The following code is equivalent to:
10071
10072      --    Resolve_Op_Concat_First (NN, Typ);
10073      --    Resolve_Op_Concat_Arg (N, ...);
10074      --    Resolve_Op_Concat_Rest (N, Typ);
10075
10076      --  where the Resolve_Op_Concat_Arg call recurses back here if the left
10077      --  operand is a concatenation.
10078
10079      --  Walk down left operands
10080
10081      loop
10082         Resolve_Op_Concat_First (NN, Typ);
10083         Op1 := Left_Opnd (NN);
10084         exit when not (Nkind (Op1) = N_Op_Concat
10085                         and then not Is_Array_Type (Component_Type (Typ))
10086                         and then Entity (Op1) = Entity (NN));
10087         NN := Op1;
10088      end loop;
10089
10090      --  Now (given the above example) NN is A&B and Op1 is A
10091
10092      --  First resolve Op1 ...
10093
10094      Resolve_Op_Concat_Arg (NN, Op1, Typ, Is_Component_Left_Opnd  (NN));
10095
10096      --  ... then walk NN back up until we reach N (where we started), calling
10097      --  Resolve_Op_Concat_Rest along the way.
10098
10099      loop
10100         Resolve_Op_Concat_Rest (NN, Typ);
10101         exit when NN = N;
10102         NN := Parent (NN);
10103      end loop;
10104   end Resolve_Op_Concat;
10105
10106   ---------------------------
10107   -- Resolve_Op_Concat_Arg --
10108   ---------------------------
10109
10110   procedure Resolve_Op_Concat_Arg
10111     (N       : Node_Id;
10112      Arg     : Node_Id;
10113      Typ     : Entity_Id;
10114      Is_Comp : Boolean)
10115   is
10116      Btyp : constant Entity_Id := Base_Type (Typ);
10117      Ctyp : constant Entity_Id := Component_Type (Typ);
10118
10119   begin
10120      if In_Instance then
10121         if Is_Comp
10122           or else (not Is_Overloaded (Arg)
10123                     and then Etype (Arg) /= Any_Composite
10124                     and then Covers (Ctyp, Etype (Arg)))
10125         then
10126            Resolve (Arg, Ctyp);
10127         else
10128            Resolve (Arg, Btyp);
10129         end if;
10130
10131      --  If both Array & Array and Array & Component are visible, there is a
10132      --  potential ambiguity that must be reported.
10133
10134      elsif Has_Compatible_Type (Arg, Ctyp) then
10135         if Nkind (Arg) = N_Aggregate
10136           and then Is_Composite_Type (Ctyp)
10137         then
10138            if Is_Private_Type (Ctyp) then
10139               Resolve (Arg, Btyp);
10140
10141            --  If the operation is user-defined and not overloaded use its
10142            --  profile. The operation may be a renaming, in which case it has
10143            --  been rewritten, and we want the original profile.
10144
10145            elsif not Is_Overloaded (N)
10146              and then Comes_From_Source (Entity (Original_Node (N)))
10147              and then Ekind (Entity (Original_Node (N))) = E_Function
10148            then
10149               Resolve (Arg,
10150                 Etype
10151                   (Next_Formal (First_Formal (Entity (Original_Node (N))))));
10152               return;
10153
10154            --  Otherwise an aggregate may match both the array type and the
10155            --  component type.
10156
10157            else
10158               Error_Msg_N ("ambiguous aggregate must be qualified", Arg);
10159               Set_Etype (Arg, Any_Type);
10160            end if;
10161
10162         else
10163            if Is_Overloaded (Arg)
10164              and then Has_Compatible_Type (Arg, Typ)
10165              and then Etype (Arg) /= Any_Type
10166            then
10167               declare
10168                  I    : Interp_Index;
10169                  It   : Interp;
10170                  Func : Entity_Id;
10171
10172               begin
10173                  Get_First_Interp (Arg, I, It);
10174                  Func := It.Nam;
10175                  Get_Next_Interp (I, It);
10176
10177                  --  Special-case the error message when the overloading is
10178                  --  caused by a function that yields an array and can be
10179                  --  called without parameters.
10180
10181                  if It.Nam = Func then
10182                     Error_Msg_Sloc := Sloc (Func);
10183                     Error_Msg_N ("ambiguous call to function#", Arg);
10184                     Error_Msg_NE
10185                       ("\\interpretation as call yields&", Arg, Typ);
10186                     Error_Msg_NE
10187                       ("\\interpretation as indexing of call yields&",
10188                         Arg, Component_Type (Typ));
10189
10190                  else
10191                     Error_Msg_N ("ambiguous operand for concatenation!", Arg);
10192
10193                     Get_First_Interp (Arg, I, It);
10194                     while Present (It.Nam) loop
10195                        Error_Msg_Sloc := Sloc (It.Nam);
10196
10197                        if Base_Type (It.Typ) = Btyp
10198                             or else
10199                           Base_Type (It.Typ) = Base_Type (Ctyp)
10200                        then
10201                           Error_Msg_N -- CODEFIX
10202                             ("\\possible interpretation#", Arg);
10203                        end if;
10204
10205                        Get_Next_Interp (I, It);
10206                     end loop;
10207                  end if;
10208               end;
10209            end if;
10210
10211            Resolve (Arg, Component_Type (Typ));
10212
10213            if Nkind (Arg) = N_String_Literal then
10214               Set_Etype (Arg, Component_Type (Typ));
10215            end if;
10216
10217            if Arg = Left_Opnd (N) then
10218               Set_Is_Component_Left_Opnd (N);
10219            else
10220               Set_Is_Component_Right_Opnd (N);
10221            end if;
10222         end if;
10223
10224      else
10225         Resolve (Arg, Btyp);
10226      end if;
10227
10228      Check_Unset_Reference (Arg);
10229   end Resolve_Op_Concat_Arg;
10230
10231   -----------------------------
10232   -- Resolve_Op_Concat_First --
10233   -----------------------------
10234
10235   procedure Resolve_Op_Concat_First (N : Node_Id; Typ : Entity_Id) is
10236      Btyp : constant Entity_Id := Base_Type (Typ);
10237      Op1  : constant Node_Id := Left_Opnd (N);
10238      Op2  : constant Node_Id := Right_Opnd (N);
10239
10240   begin
10241      --  The parser folds an enormous sequence of concatenations of string
10242      --  literals into "" & "...", where the Is_Folded_In_Parser flag is set
10243      --  in the right operand. If the expression resolves to a predefined "&"
10244      --  operator, all is well. Otherwise, the parser's folding is wrong, so
10245      --  we give an error. See P_Simple_Expression in Par.Ch4.
10246
10247      if Nkind (Op2) = N_String_Literal
10248        and then Is_Folded_In_Parser (Op2)
10249        and then Ekind (Entity (N)) = E_Function
10250      then
10251         pragma Assert (Nkind (Op1) = N_String_Literal  --  should be ""
10252               and then String_Length (Strval (Op1)) = 0);
10253         Error_Msg_N ("too many user-defined concatenations", N);
10254         return;
10255      end if;
10256
10257      Set_Etype (N, Btyp);
10258
10259      if Is_Limited_Composite (Btyp) then
10260         Error_Msg_N ("concatenation not available for limited array", N);
10261         Explain_Limited_Type (Btyp, N);
10262      end if;
10263   end Resolve_Op_Concat_First;
10264
10265   ----------------------------
10266   -- Resolve_Op_Concat_Rest --
10267   ----------------------------
10268
10269   procedure Resolve_Op_Concat_Rest (N : Node_Id; Typ : Entity_Id) is
10270      Op1  : constant Node_Id := Left_Opnd (N);
10271      Op2  : constant Node_Id := Right_Opnd (N);
10272
10273   begin
10274      Resolve_Op_Concat_Arg (N, Op2, Typ, Is_Component_Right_Opnd  (N));
10275
10276      Generate_Operator_Reference (N, Typ);
10277
10278      if Is_String_Type (Typ) then
10279         Eval_Concatenation (N);
10280      end if;
10281
10282      --  If this is not a static concatenation, but the result is a string
10283      --  type (and not an array of strings) ensure that static string operands
10284      --  have their subtypes properly constructed.
10285
10286      if Nkind (N) /= N_String_Literal
10287        and then Is_Character_Type (Component_Type (Typ))
10288      then
10289         Set_String_Literal_Subtype (Op1, Typ);
10290         Set_String_Literal_Subtype (Op2, Typ);
10291      end if;
10292   end Resolve_Op_Concat_Rest;
10293
10294   ----------------------
10295   -- Resolve_Op_Expon --
10296   ----------------------
10297
10298   procedure Resolve_Op_Expon (N : Node_Id; Typ : Entity_Id) is
10299      B_Typ : constant Entity_Id := Base_Type (Typ);
10300
10301   begin
10302      --  Catch attempts to do fixed-point exponentiation with universal
10303      --  operands, which is a case where the illegality is not caught during
10304      --  normal operator analysis. This is not done in preanalysis mode
10305      --  since the tree is not fully decorated during preanalysis.
10306
10307      if Full_Analysis then
10308         if Is_Fixed_Point_Type (Typ) and then Comes_From_Source (N) then
10309            Error_Msg_N ("exponentiation not available for fixed point", N);
10310            return;
10311
10312         elsif Nkind (Parent (N)) in N_Op
10313           and then Present (Etype (Parent (N)))
10314           and then Is_Fixed_Point_Type (Etype (Parent (N)))
10315           and then Etype (N) = Universal_Real
10316           and then Comes_From_Source (N)
10317         then
10318            Error_Msg_N ("exponentiation not available for fixed point", N);
10319            return;
10320         end if;
10321      end if;
10322
10323      if Comes_From_Source (N)
10324        and then Ekind (Entity (N)) = E_Function
10325        and then Is_Imported (Entity (N))
10326        and then Is_Intrinsic_Subprogram (Entity (N))
10327      then
10328         Resolve_Intrinsic_Operator (N, Typ);
10329         return;
10330      end if;
10331
10332      if Is_Universal_Numeric_Type (Etype (Left_Opnd (N))) then
10333         Check_For_Visible_Operator (N, B_Typ);
10334      end if;
10335
10336      --  We do the resolution using the base type, because intermediate values
10337      --  in expressions are always of the base type, not a subtype of it.
10338
10339      Resolve (Left_Opnd (N), B_Typ);
10340      Resolve (Right_Opnd (N), Standard_Integer);
10341
10342      --  For integer types, right argument must be in Natural range
10343
10344      if Is_Integer_Type (Typ) then
10345         Apply_Scalar_Range_Check (Right_Opnd (N), Standard_Natural);
10346      end if;
10347
10348      Check_Unset_Reference (Left_Opnd  (N));
10349      Check_Unset_Reference (Right_Opnd (N));
10350
10351      Set_Etype (N, B_Typ);
10352      Generate_Operator_Reference (N, B_Typ);
10353
10354      Analyze_Dimension (N);
10355
10356      if Ada_Version >= Ada_2012 and then Has_Dimension_System (B_Typ) then
10357         --  Evaluate the exponentiation operator for dimensioned type
10358
10359         Eval_Op_Expon_For_Dimensioned_Type (N, B_Typ);
10360      else
10361         Eval_Op_Expon (N);
10362      end if;
10363
10364      --  Set overflow checking bit. Much cleverer code needed here eventually
10365      --  and perhaps the Resolve routines should be separated for the various
10366      --  arithmetic operations, since they will need different processing. ???
10367
10368      if Nkind (N) in N_Op then
10369         if not Overflow_Checks_Suppressed (Etype (N)) then
10370            Enable_Overflow_Check (N);
10371         end if;
10372      end if;
10373   end Resolve_Op_Expon;
10374
10375   --------------------
10376   -- Resolve_Op_Not --
10377   --------------------
10378
10379   procedure Resolve_Op_Not (N : Node_Id; Typ : Entity_Id) is
10380      function Parent_Is_Boolean return Boolean;
10381      --  This function determines if the parent node is a boolean operator or
10382      --  operation (comparison op, membership test, or short circuit form) and
10383      --  the not in question is the left operand of this operation. Note that
10384      --  if the not is in parens, then false is returned.
10385
10386      -----------------------
10387      -- Parent_Is_Boolean --
10388      -----------------------
10389
10390      function Parent_Is_Boolean return Boolean is
10391      begin
10392         return Paren_Count (N) = 0
10393           and then Nkind (Parent (N)) in N_Membership_Test
10394                                        | N_Op_Boolean
10395                                        | N_Short_Circuit
10396            and then Left_Opnd (Parent (N)) = N;
10397      end Parent_Is_Boolean;
10398
10399      --  Local variables
10400
10401      B_Typ : Entity_Id;
10402
10403   --  Start of processing for Resolve_Op_Not
10404
10405   begin
10406      --  Predefined operations on scalar types yield the base type. On the
10407      --  other hand, logical operations on arrays yield the type of the
10408      --  arguments (and the context).
10409
10410      if Is_Array_Type (Typ) then
10411         B_Typ := Typ;
10412      else
10413         B_Typ := Base_Type (Typ);
10414      end if;
10415
10416      --  Straightforward case of incorrect arguments
10417
10418      if not Valid_Boolean_Arg (Typ) then
10419         Error_Msg_N ("invalid operand type for operator&", N);
10420         Set_Etype (N, Any_Type);
10421         return;
10422
10423      --  Special case of probable missing parens
10424
10425      elsif Typ = Universal_Integer or else Typ = Any_Modular then
10426         if Parent_Is_Boolean then
10427            Error_Msg_N
10428              ("operand of NOT must be enclosed in parentheses",
10429               Right_Opnd (N));
10430         else
10431            Error_Msg_N
10432              ("no modular type available in this context", N);
10433         end if;
10434
10435         Set_Etype (N, Any_Type);
10436         return;
10437
10438      --  OK resolution of NOT
10439
10440      else
10441         --  Warn if non-boolean types involved. This is a case like not a < b
10442         --  where a and b are modular, where we will get (not a) < b and most
10443         --  likely not (a < b) was intended.
10444
10445         if Warn_On_Questionable_Missing_Parens
10446           and then not Is_Boolean_Type (Typ)
10447           and then Parent_Is_Boolean
10448         then
10449            Error_Msg_N ("?q?not expression should be parenthesized here!", N);
10450         end if;
10451
10452         --  Warn on double negation if checking redundant constructs
10453
10454         if Warn_On_Redundant_Constructs
10455           and then Comes_From_Source (N)
10456           and then Comes_From_Source (Right_Opnd (N))
10457           and then Root_Type (Typ) = Standard_Boolean
10458           and then Nkind (Right_Opnd (N)) = N_Op_Not
10459         then
10460            Error_Msg_N ("redundant double negation?r?", N);
10461         end if;
10462
10463         --  Complete resolution and evaluation of NOT
10464         --  If argument is an equality and expected type is boolean, that
10465         --  expected type has no effect on resolution, and there are
10466         --  special rules for resolution of Eq, Neq in the presence of
10467         --  overloaded operands, so we directly call its resolution routines.
10468
10469         declare
10470            Opnd : constant Node_Id := Right_Opnd (N);
10471            Op_Id : Entity_Id;
10472
10473         begin
10474            if B_Typ = Standard_Boolean
10475              and then Nkind (Opnd) in N_Op_Eq | N_Op_Ne
10476              and then Is_Overloaded (Opnd)
10477            then
10478               Resolve_Equality_Op (Opnd, B_Typ);
10479               Op_Id := Entity (Opnd);
10480
10481               if Ekind (Op_Id) = E_Function
10482                 and then not Is_Intrinsic_Subprogram (Op_Id)
10483               then
10484                  Rewrite_Operator_As_Call (Opnd, Op_Id);
10485               end if;
10486
10487               if not Inside_A_Generic or else Is_Entity_Name (Opnd) then
10488                  Freeze_Expression (Opnd);
10489               end if;
10490
10491               Expand (Opnd);
10492
10493            else
10494               Resolve (Opnd, B_Typ);
10495            end if;
10496
10497            Check_Unset_Reference (Opnd);
10498         end;
10499
10500         Set_Etype (N, B_Typ);
10501         Generate_Operator_Reference (N, B_Typ);
10502         Eval_Op_Not (N);
10503      end if;
10504   end Resolve_Op_Not;
10505
10506   -----------------------------
10507   -- Resolve_Operator_Symbol --
10508   -----------------------------
10509
10510   --  Nothing to be done, all resolved already
10511
10512   procedure Resolve_Operator_Symbol (N : Node_Id; Typ : Entity_Id) is
10513      pragma Warnings (Off, N);
10514      pragma Warnings (Off, Typ);
10515
10516   begin
10517      null;
10518   end Resolve_Operator_Symbol;
10519
10520   ----------------------------------
10521   -- Resolve_Qualified_Expression --
10522   ----------------------------------
10523
10524   procedure Resolve_Qualified_Expression (N : Node_Id; Typ : Entity_Id) is
10525      pragma Warnings (Off, Typ);
10526
10527      Target_Typ : constant Entity_Id := Entity (Subtype_Mark (N));
10528      Expr       : constant Node_Id   := Expression (N);
10529
10530   begin
10531      Resolve (Expr, Target_Typ);
10532
10533      --  A qualified expression requires an exact match of the type, class-
10534      --  wide matching is not allowed. However, if the qualifying type is
10535      --  specific and the expression has a class-wide type, it may still be
10536      --  okay, since it can be the result of the expansion of a call to a
10537      --  dispatching function, so we also have to check class-wideness of the
10538      --  type of the expression's original node.
10539
10540      if (Is_Class_Wide_Type (Target_Typ)
10541           or else
10542             (Is_Class_Wide_Type (Etype (Expr))
10543               and then Is_Class_Wide_Type (Etype (Original_Node (Expr)))))
10544        and then Base_Type (Etype (Expr)) /= Base_Type (Target_Typ)
10545      then
10546         Wrong_Type (Expr, Target_Typ);
10547      end if;
10548
10549      --  If the target type is unconstrained, then we reset the type of the
10550      --  result from the type of the expression. For other cases, the actual
10551      --  subtype of the expression is the target type. But we avoid doing it
10552      --  for an allocator since this is not needed and might be problematic.
10553
10554      if Is_Composite_Type (Target_Typ)
10555        and then not Is_Constrained (Target_Typ)
10556        and then Nkind (Parent (N)) /= N_Allocator
10557      then
10558         Set_Etype (N, Etype (Expr));
10559      end if;
10560
10561      Analyze_Dimension (N);
10562      Eval_Qualified_Expression (N);
10563
10564      --  If we still have a qualified expression after the static evaluation,
10565      --  then apply a scalar range check if needed. The reason that we do this
10566      --  after the Eval call is that otherwise, the application of the range
10567      --  check may convert an illegal static expression and result in warning
10568      --  rather than giving an error (e.g Integer'(Integer'Last + 1)).
10569
10570      if Nkind (N) = N_Qualified_Expression
10571        and then Is_Scalar_Type (Target_Typ)
10572      then
10573         Apply_Scalar_Range_Check (Expr, Target_Typ);
10574      end if;
10575
10576      --  AI12-0100: Once the qualified expression is resolved, check whether
10577      --  operand statisfies a static predicate of the target subtype, if any.
10578      --  In the static expression case, a predicate check failure is an error.
10579
10580      if Has_Predicates (Target_Typ) then
10581         Check_Expression_Against_Static_Predicate
10582           (Expr, Target_Typ, Static_Failure_Is_Error => True);
10583      end if;
10584   end Resolve_Qualified_Expression;
10585
10586   ------------------------------
10587   -- Resolve_Raise_Expression --
10588   ------------------------------
10589
10590   procedure Resolve_Raise_Expression (N : Node_Id; Typ : Entity_Id) is
10591   begin
10592      if Typ = Raise_Type then
10593         Error_Msg_N ("cannot find unique type for raise expression", N);
10594         Set_Etype (N, Any_Type);
10595
10596      else
10597         Set_Etype (N, Typ);
10598
10599         --  Apply check for required parentheses in the enclosing
10600         --  context of raise_expressions (RM 11.3 (2)), including default
10601         --  expressions in contexts that can include aspect specifications,
10602         --  and ancestor parts of extension aggregates.
10603
10604         declare
10605            Par : Node_Id := Parent (N);
10606            Parentheses_Found : Boolean := Paren_Count (N) > 0;
10607
10608         begin
10609            while Present (Par)
10610              and then Nkind (Par) in N_Has_Etype
10611            loop
10612               if Paren_Count (Par) > 0 then
10613                  Parentheses_Found := True;
10614               end if;
10615
10616               if Nkind (Par) = N_Extension_Aggregate
10617                 and then N = Ancestor_Part (Par)
10618               then
10619                  exit;
10620               end if;
10621
10622               Par := Parent (Par);
10623            end loop;
10624
10625            if not Parentheses_Found
10626              and then Comes_From_Source (Par)
10627              and then
10628                ((Nkind (Par) in N_Modular_Type_Definition
10629                               | N_Floating_Point_Definition
10630                               | N_Ordinary_Fixed_Point_Definition
10631                               | N_Decimal_Fixed_Point_Definition
10632                               | N_Extension_Aggregate
10633                               | N_Discriminant_Specification
10634                               | N_Parameter_Specification
10635                               | N_Formal_Object_Declaration)
10636
10637                  or else (Nkind (Par) = N_Object_Declaration
10638                    and then
10639                      Nkind (Parent (Par)) /= N_Extended_Return_Statement))
10640            then
10641               Error_Msg_N
10642                 ("raise_expression must be parenthesized in this context",
10643                   N);
10644            end if;
10645         end;
10646      end if;
10647   end Resolve_Raise_Expression;
10648
10649   -------------------
10650   -- Resolve_Range --
10651   -------------------
10652
10653   procedure Resolve_Range (N : Node_Id; Typ : Entity_Id) is
10654      L : constant Node_Id := Low_Bound (N);
10655      H : constant Node_Id := High_Bound (N);
10656
10657      function First_Last_Ref return Boolean;
10658      --  Returns True if N is of the form X'First .. X'Last where X is the
10659      --  same entity for both attributes.
10660
10661      --------------------
10662      -- First_Last_Ref --
10663      --------------------
10664
10665      function First_Last_Ref return Boolean is
10666         Lorig : constant Node_Id := Original_Node (L);
10667         Horig : constant Node_Id := Original_Node (H);
10668
10669      begin
10670         if Nkind (Lorig) = N_Attribute_Reference
10671           and then Nkind (Horig) = N_Attribute_Reference
10672           and then Attribute_Name (Lorig) = Name_First
10673           and then Attribute_Name (Horig) = Name_Last
10674         then
10675            declare
10676               PL : constant Node_Id := Prefix (Lorig);
10677               PH : constant Node_Id := Prefix (Horig);
10678            begin
10679               return Is_Entity_Name (PL)
10680                 and then Is_Entity_Name (PH)
10681                 and then Entity (PL) = Entity (PH);
10682            end;
10683         end if;
10684
10685         return False;
10686      end First_Last_Ref;
10687
10688   --  Start of processing for Resolve_Range
10689
10690   begin
10691      Set_Etype (N, Typ);
10692
10693      Resolve (L, Typ);
10694      Resolve (H, Typ);
10695
10696      --  Reanalyze the lower bound after both bounds have been analyzed, so
10697      --  that the range is known to be static or not by now. This may trigger
10698      --  more compile-time evaluation, which is useful for static analysis
10699      --  with GNATprove. This is not needed for compilation or static analysis
10700      --  with CodePeer, as full expansion does that evaluation then.
10701
10702      if GNATprove_Mode then
10703         Set_Analyzed (L, False);
10704         Resolve (L, Typ);
10705      end if;
10706
10707      --  Check for inappropriate range on unordered enumeration type
10708
10709      if Bad_Unordered_Enumeration_Reference (N, Typ)
10710
10711        --  Exclude X'First .. X'Last if X is the same entity for both
10712
10713        and then not First_Last_Ref
10714      then
10715         Error_Msg_Sloc := Sloc (Typ);
10716         Error_Msg_NE
10717           ("subrange of unordered enumeration type& declared#?.u?", N, Typ);
10718      end if;
10719
10720      Check_Unset_Reference (L);
10721      Check_Unset_Reference (H);
10722
10723      --  We have to check the bounds for being within the base range as
10724      --  required for a non-static context. Normally this is automatic and
10725      --  done as part of evaluating expressions, but the N_Range node is an
10726      --  exception, since in GNAT we consider this node to be a subexpression,
10727      --  even though in Ada it is not. The circuit in Sem_Eval could check for
10728      --  this, but that would put the test on the main evaluation path for
10729      --  expressions.
10730
10731      Check_Non_Static_Context (L);
10732      Check_Non_Static_Context (H);
10733
10734      --  Check for an ambiguous range over character literals. This will
10735      --  happen with a membership test involving only literals.
10736
10737      if Typ = Any_Character then
10738         Ambiguous_Character (L);
10739         Set_Etype (N, Any_Type);
10740         return;
10741      end if;
10742
10743      --  If bounds are static, constant-fold them, so size computations are
10744      --  identical between front-end and back-end. Do not perform this
10745      --  transformation while analyzing generic units, as type information
10746      --  would be lost when reanalyzing the constant node in the instance.
10747
10748      if Is_Discrete_Type (Typ) and then Expander_Active then
10749         if Is_OK_Static_Expression (L) then
10750            Fold_Uint (L, Expr_Value (L), Static => True);
10751         end if;
10752
10753         if Is_OK_Static_Expression (H) then
10754            Fold_Uint (H, Expr_Value (H), Static => True);
10755         end if;
10756      end if;
10757   end Resolve_Range;
10758
10759   --------------------------
10760   -- Resolve_Real_Literal --
10761   --------------------------
10762
10763   procedure Resolve_Real_Literal (N : Node_Id; Typ : Entity_Id) is
10764      Actual_Typ : constant Entity_Id := Etype (N);
10765
10766   begin
10767      --  Special processing for fixed-point literals to make sure that the
10768      --  value is an exact multiple of the small where this is required. We
10769      --  skip this for the universal real case, and also for generic types.
10770
10771      if Is_Fixed_Point_Type (Typ)
10772        and then Typ /= Universal_Fixed
10773        and then Typ /= Any_Fixed
10774        and then not Is_Generic_Type (Typ)
10775      then
10776         --  We must freeze the base type to get the proper value of the small
10777
10778         if not Is_Frozen (Base_Type (Typ)) then
10779            Freeze_Fixed_Point_Type (Base_Type (Typ));
10780         end if;
10781
10782         declare
10783            Val   : constant Ureal := Realval (N);
10784            Cintr : constant Ureal := Val / Small_Value (Base_Type (Typ));
10785            Cint  : constant Uint  := UR_Trunc (Cintr);
10786            Den   : constant Uint  := Norm_Den (Cintr);
10787            Stat  : Boolean;
10788
10789         begin
10790            --  Case of literal is not an exact multiple of the Small
10791
10792            if Den /= 1 then
10793
10794               --  For a source program literal for a decimal fixed-point type,
10795               --  this is statically illegal (RM 4.9(36)).
10796
10797               if Is_Decimal_Fixed_Point_Type (Typ)
10798                 and then Actual_Typ = Universal_Real
10799                 and then Comes_From_Source (N)
10800               then
10801                  Error_Msg_N ("value has extraneous low order digits", N);
10802               end if;
10803
10804               --  Generate a warning if literal from source
10805
10806               if Is_OK_Static_Expression (N)
10807                 and then Warn_On_Bad_Fixed_Value
10808               then
10809                  Error_Msg_N
10810                    ("?b?static fixed-point value is not a multiple of Small!",
10811                     N);
10812               end if;
10813
10814               --  Replace literal by a value that is the exact representation
10815               --  of a value of the type, i.e. a multiple of the small value,
10816               --  by truncation, since Machine_Rounds is false for all GNAT
10817               --  fixed-point types (RM 4.9(38)).
10818
10819               Stat := Is_OK_Static_Expression (N);
10820               Rewrite (N,
10821                 Make_Real_Literal (Sloc (N),
10822                   Realval => Small_Value (Typ) * Cint));
10823
10824               Set_Is_Static_Expression (N, Stat);
10825            end if;
10826
10827            --  In all cases, set the corresponding integer field
10828
10829            Set_Corresponding_Integer_Value (N, Cint);
10830         end;
10831      end if;
10832
10833      --  Now replace the actual type by the expected type as usual
10834
10835      Set_Etype (N, Typ);
10836      Eval_Real_Literal (N);
10837   end Resolve_Real_Literal;
10838
10839   -----------------------
10840   -- Resolve_Reference --
10841   -----------------------
10842
10843   procedure Resolve_Reference (N : Node_Id; Typ : Entity_Id) is
10844      P : constant Node_Id := Prefix (N);
10845
10846   begin
10847      --  Replace general access with specific type
10848
10849      if Ekind (Etype (N)) = E_Allocator_Type then
10850         Set_Etype (N, Base_Type (Typ));
10851      end if;
10852
10853      Resolve (P, Designated_Type (Etype (N)));
10854
10855      --  If we are taking the reference of a volatile entity, then treat it as
10856      --  a potential modification of this entity. This is too conservative,
10857      --  but necessary because remove side effects can cause transformations
10858      --  of normal assignments into reference sequences that otherwise fail to
10859      --  notice the modification.
10860
10861      if Is_Entity_Name (P) and then Treat_As_Volatile (Entity (P)) then
10862         Note_Possible_Modification (P, Sure => False);
10863      end if;
10864   end Resolve_Reference;
10865
10866   --------------------------------
10867   -- Resolve_Selected_Component --
10868   --------------------------------
10869
10870   procedure Resolve_Selected_Component (N : Node_Id; Typ : Entity_Id) is
10871      Comp  : Entity_Id;
10872      Comp1 : Entity_Id        := Empty; -- prevent junk warning
10873      P     : constant Node_Id := Prefix (N);
10874      S     : constant Node_Id := Selector_Name (N);
10875      T     : Entity_Id        := Etype (P);
10876      I     : Interp_Index;
10877      I1    : Interp_Index := 0; -- prevent junk warning
10878      It    : Interp;
10879      It1   : Interp;
10880      Found : Boolean;
10881
10882      function Init_Component return Boolean;
10883      --  Check whether this is the initialization of a component within an
10884      --  init proc (by assignment or call to another init proc). If true,
10885      --  there is no need for a discriminant check.
10886
10887      --------------------
10888      -- Init_Component --
10889      --------------------
10890
10891      function Init_Component return Boolean is
10892      begin
10893         return Inside_Init_Proc
10894           and then Nkind (Prefix (N)) = N_Identifier
10895           and then Chars (Prefix (N)) = Name_uInit
10896           and then Nkind (Parent (Parent (N))) = N_Case_Statement_Alternative;
10897      end Init_Component;
10898
10899   --  Start of processing for Resolve_Selected_Component
10900
10901   begin
10902      if Is_Overloaded (P) then
10903
10904         --  Use the context type to select the prefix that has a selector
10905         --  of the correct name and type.
10906
10907         Found := False;
10908         Get_First_Interp (P, I, It);
10909
10910         Search : while Present (It.Typ) loop
10911            if Is_Access_Type (It.Typ) then
10912               T := Designated_Type (It.Typ);
10913            else
10914               T := It.Typ;
10915            end if;
10916
10917            --  Locate selected component. For a private prefix the selector
10918            --  can denote a discriminant.
10919
10920            if Is_Record_Type (T) or else Is_Private_Type (T) then
10921
10922               --  The visible components of a class-wide type are those of
10923               --  the root type.
10924
10925               if Is_Class_Wide_Type (T) then
10926                  T := Etype (T);
10927               end if;
10928
10929               Comp := First_Entity (T);
10930               while Present (Comp) loop
10931                  if Chars (Comp) = Chars (S)
10932                    and then Covers (Typ, Etype (Comp))
10933                  then
10934                     if not Found then
10935                        Found := True;
10936                        I1  := I;
10937                        It1 := It;
10938                        Comp1 := Comp;
10939
10940                     else
10941                        It := Disambiguate (P, I1, I, Any_Type);
10942
10943                        if It = No_Interp then
10944                           Error_Msg_N
10945                             ("ambiguous prefix for selected component",  N);
10946                           Set_Etype (N, Typ);
10947                           return;
10948
10949                        else
10950                           It1 := It;
10951
10952                           --  There may be an implicit dereference. Retrieve
10953                           --  designated record type.
10954
10955                           if Is_Access_Type (It1.Typ) then
10956                              T := Designated_Type (It1.Typ);
10957                           else
10958                              T := It1.Typ;
10959                           end if;
10960
10961                           if Scope (Comp1) /= T then
10962
10963                              --  Resolution chooses the new interpretation.
10964                              --  Find the component with the right name.
10965
10966                              Comp1 := First_Entity (T);
10967                              while Present (Comp1)
10968                                and then Chars (Comp1) /= Chars (S)
10969                              loop
10970                                 Next_Entity (Comp1);
10971                              end loop;
10972                           end if;
10973
10974                           exit Search;
10975                        end if;
10976                     end if;
10977                  end if;
10978
10979                  Next_Entity (Comp);
10980               end loop;
10981            end if;
10982
10983            Get_Next_Interp (I, It);
10984         end loop Search;
10985
10986         --  There must be a legal interpretation at this point
10987
10988         pragma Assert (Found);
10989         Resolve (P, It1.Typ);
10990
10991         --  In general the expected type is the type of the context, not the
10992         --  type of the candidate selected component.
10993
10994         Set_Etype (N, Typ);
10995         Set_Entity_With_Checks (S, Comp1);
10996
10997         --  The type of the context and that of the component are
10998         --  compatible and in general identical, but if they are anonymous
10999         --  access-to-subprogram types, the relevant type is that of the
11000         --  component. This matters in Unnest_Subprograms mode, where the
11001         --  relevant context is the one in which the type is declared, not
11002         --  the point of use. This determines what activation record to use.
11003
11004         if Ekind (Typ) = E_Anonymous_Access_Subprogram_Type then
11005            Set_Etype (N, Etype (Comp1));
11006
11007         --  When the type of the component is an access to a class-wide type
11008         --  the relevant type is that of the component (since in such case we
11009         --  may need to generate implicit type conversions or dispatching
11010         --  calls).
11011
11012         elsif Is_Access_Type (Typ)
11013           and then not Is_Class_Wide_Type (Designated_Type (Typ))
11014           and then Is_Class_Wide_Type (Designated_Type (Etype (Comp1)))
11015         then
11016            Set_Etype (N, Etype (Comp1));
11017         end if;
11018
11019      else
11020         --  Resolve prefix with its type
11021
11022         Resolve (P, T);
11023      end if;
11024
11025      --  Generate cross-reference. We needed to wait until full overloading
11026      --  resolution was complete to do this, since otherwise we can't tell if
11027      --  we are an lvalue or not.
11028
11029      if May_Be_Lvalue (N) then
11030         Generate_Reference (Entity (S), S, 'm');
11031      else
11032         Generate_Reference (Entity (S), S, 'r');
11033      end if;
11034
11035      --  If the prefix's type is an access type, get to the real record type.
11036      --  Note: we do not apply an access check because an explicit dereference
11037      --  will be introduced later, and the check will happen there.
11038
11039      if Is_Access_Type (Etype (P)) then
11040         T := Implicitly_Designated_Type (Etype (P));
11041         Check_Fully_Declared_Prefix (T, P);
11042
11043      else
11044         T := Etype (P);
11045
11046         --  If the prefix is an entity it may have a deferred reference set
11047         --  during analysis of the selected component. After resolution we
11048         --  can transform it into a proper reference. This prevents spurious
11049         --  warnings on useless assignments when the same selected component
11050         --  is the actual for an out parameter in a subsequent call.
11051
11052         if Is_Entity_Name (P)
11053           and then Has_Deferred_Reference (Entity (P))
11054         then
11055            if May_Be_Lvalue (N) then
11056               Generate_Reference (Entity (P), P, 'm');
11057            else
11058               Generate_Reference (Entity (P), P, 'r');
11059            end if;
11060         end if;
11061      end if;
11062
11063      --  Set flag for expander if discriminant check required on a component
11064      --  appearing within a variant.
11065
11066      if Has_Discriminants (T)
11067        and then Ekind (Entity (S)) = E_Component
11068        and then Present (Original_Record_Component (Entity (S)))
11069        and then Ekind (Original_Record_Component (Entity (S))) = E_Component
11070        and then
11071          Is_Declared_Within_Variant (Original_Record_Component (Entity (S)))
11072        and then not Discriminant_Checks_Suppressed (T)
11073        and then not Init_Component
11074      then
11075         Set_Do_Discriminant_Check (N);
11076      end if;
11077
11078      if Ekind (Entity (S)) = E_Void then
11079         Error_Msg_N ("premature use of component", S);
11080      end if;
11081
11082      --  If the prefix is a record conversion, this may be a renamed
11083      --  discriminant whose bounds differ from those of the original
11084      --  one, so we must ensure that a range check is performed.
11085
11086      if Nkind (P) = N_Type_Conversion
11087        and then Ekind (Entity (S)) = E_Discriminant
11088        and then Is_Discrete_Type (Typ)
11089      then
11090         Set_Etype (N, Base_Type (Typ));
11091      end if;
11092
11093      --  Eval_Selected_Component may e.g. fold statically known discriminants.
11094
11095      Eval_Selected_Component (N);
11096
11097      if Nkind (N) = N_Selected_Component then
11098
11099         --  If the record type is atomic and the component is not, then this
11100         --  is worth a warning before Ada 2022, since we have a situation
11101         --  where the access to the component may cause extra read/writes of
11102         --  the atomic object, or partial word accesses, both of which may be
11103         --  unexpected.
11104
11105         if Is_Atomic_Ref_With_Address (N)
11106           and then not Is_Atomic (Entity (S))
11107           and then not Is_Atomic (Etype (Entity (S)))
11108           and then Ada_Version < Ada_2022
11109         then
11110            Error_Msg_N
11111              ("??access to non-atomic component of atomic record",
11112               Prefix (N));
11113            Error_Msg_N
11114              ("\??may cause unexpected accesses to atomic object",
11115               Prefix (N));
11116         end if;
11117
11118         Resolve_Implicit_Dereference (Prefix (N));
11119         Analyze_Dimension (N);
11120      end if;
11121   end Resolve_Selected_Component;
11122
11123   -------------------
11124   -- Resolve_Shift --
11125   -------------------
11126
11127   procedure Resolve_Shift (N : Node_Id; Typ : Entity_Id) is
11128      B_Typ : constant Entity_Id := Base_Type (Typ);
11129      L     : constant Node_Id   := Left_Opnd  (N);
11130      R     : constant Node_Id   := Right_Opnd (N);
11131
11132   begin
11133      --  We do the resolution using the base type, because intermediate values
11134      --  in expressions always are of the base type, not a subtype of it.
11135
11136      Resolve (L, B_Typ);
11137      Resolve (R, Standard_Natural);
11138
11139      Check_Unset_Reference (L);
11140      Check_Unset_Reference (R);
11141
11142      Set_Etype (N, B_Typ);
11143      Generate_Operator_Reference (N, B_Typ);
11144      Eval_Shift (N);
11145   end Resolve_Shift;
11146
11147   ---------------------------
11148   -- Resolve_Short_Circuit --
11149   ---------------------------
11150
11151   procedure Resolve_Short_Circuit (N : Node_Id; Typ : Entity_Id) is
11152      B_Typ : constant Entity_Id := Base_Type (Typ);
11153      L     : constant Node_Id   := Left_Opnd  (N);
11154      R     : constant Node_Id   := Right_Opnd (N);
11155
11156   begin
11157      --  Ensure all actions associated with the left operand (e.g.
11158      --  finalization of transient objects) are fully evaluated locally within
11159      --  an expression with actions. This is particularly helpful for coverage
11160      --  analysis. However this should not happen in generics or if option
11161      --  Minimize_Expression_With_Actions is set.
11162
11163      if Expander_Active and not Minimize_Expression_With_Actions then
11164         declare
11165            Reloc_L : constant Node_Id := Relocate_Node (L);
11166         begin
11167            Save_Interps (Old_N => L, New_N => Reloc_L);
11168
11169            Rewrite (L,
11170              Make_Expression_With_Actions (Sloc (L),
11171                Actions    => New_List,
11172                Expression => Reloc_L));
11173
11174            --  Set Comes_From_Source on L to preserve warnings for unset
11175            --  reference.
11176
11177            Preserve_Comes_From_Source (L, Reloc_L);
11178         end;
11179      end if;
11180
11181      Resolve (L, B_Typ);
11182      Resolve (R, B_Typ);
11183
11184      --  Check for issuing warning for always False assert/check, this happens
11185      --  when assertions are turned off, in which case the pragma Assert/Check
11186      --  was transformed into:
11187
11188      --     if False and then <condition> then ...
11189
11190      --  and we detect this pattern
11191
11192      if Warn_On_Assertion_Failure
11193        and then Is_Entity_Name (R)
11194        and then Entity (R) = Standard_False
11195        and then Nkind (Parent (N)) = N_If_Statement
11196        and then Nkind (N) = N_And_Then
11197        and then Is_Entity_Name (L)
11198        and then Entity (L) = Standard_False
11199      then
11200         declare
11201            Orig : constant Node_Id := Original_Node (Parent (N));
11202
11203         begin
11204            --  Special handling of Asssert pragma
11205
11206            if Nkind (Orig) = N_Pragma
11207              and then Pragma_Name (Orig) = Name_Assert
11208            then
11209               declare
11210                  Expr : constant Node_Id :=
11211                           Original_Node
11212                             (Expression
11213                               (First (Pragma_Argument_Associations (Orig))));
11214
11215               begin
11216                  --  Don't warn if original condition is explicit False,
11217                  --  since obviously the failure is expected in this case.
11218
11219                  if Is_Entity_Name (Expr)
11220                    and then Entity (Expr) = Standard_False
11221                  then
11222                     null;
11223
11224                  --  Issue warning. We do not want the deletion of the
11225                  --  IF/AND-THEN to take this message with it. We achieve this
11226                  --  by making sure that the expanded code points to the Sloc
11227                  --  of the expression, not the original pragma.
11228
11229                  else
11230                     --  Note: Use Error_Msg_F here rather than Error_Msg_N.
11231                     --  The source location of the expression is not usually
11232                     --  the best choice here. For example, it gets located on
11233                     --  the last AND keyword in a chain of boolean expressiond
11234                     --  AND'ed together. It is best to put the message on the
11235                     --  first character of the assertion, which is the effect
11236                     --  of the First_Node call here.
11237
11238                     Error_Msg_F
11239                       ("?.a?assertion would fail at run time!",
11240                        Expression
11241                          (First (Pragma_Argument_Associations (Orig))));
11242                  end if;
11243               end;
11244
11245            --  Similar processing for Check pragma
11246
11247            elsif Nkind (Orig) = N_Pragma
11248              and then Pragma_Name (Orig) = Name_Check
11249            then
11250               --  Don't want to warn if original condition is explicit False
11251
11252               declare
11253                  Expr : constant Node_Id :=
11254                    Original_Node
11255                      (Expression
11256                        (Next (First (Pragma_Argument_Associations (Orig)))));
11257               begin
11258                  if Is_Entity_Name (Expr)
11259                    and then Entity (Expr) = Standard_False
11260                  then
11261                     null;
11262
11263                  --  Post warning
11264
11265                  else
11266                     --  Again use Error_Msg_F rather than Error_Msg_N, see
11267                     --  comment above for an explanation of why we do this.
11268
11269                     Error_Msg_F
11270                       ("?.a?check would fail at run time!",
11271                        Expression
11272                          (Last (Pragma_Argument_Associations (Orig))));
11273                  end if;
11274               end;
11275            end if;
11276         end;
11277      end if;
11278
11279      --  Continue with processing of short circuit
11280
11281      Check_Unset_Reference (L);
11282      Check_Unset_Reference (R);
11283
11284      Set_Etype (N, B_Typ);
11285      Eval_Short_Circuit (N);
11286   end Resolve_Short_Circuit;
11287
11288   -------------------
11289   -- Resolve_Slice --
11290   -------------------
11291
11292   procedure Resolve_Slice (N : Node_Id; Typ : Entity_Id) is
11293      Drange     : constant Node_Id := Discrete_Range (N);
11294      Pref       : constant Node_Id := Prefix (N);
11295      Array_Type : Entity_Id        := Empty;
11296      Dexpr      : Node_Id          := Empty;
11297      Index_Type : Entity_Id;
11298
11299   begin
11300      if Is_Overloaded (Pref) then
11301
11302         --  Use the context type to select the prefix that yields the correct
11303         --  array type.
11304
11305         declare
11306            I      : Interp_Index;
11307            I1     : Interp_Index := 0;
11308            It     : Interp;
11309            Found  : Boolean := False;
11310
11311         begin
11312            Get_First_Interp (Pref, I,  It);
11313            while Present (It.Typ) loop
11314               if (Is_Array_Type (It.Typ)
11315                    and then Covers (Typ,  It.Typ))
11316                 or else (Is_Access_Type (It.Typ)
11317                           and then Is_Array_Type (Designated_Type (It.Typ))
11318                           and then Covers (Typ, Designated_Type (It.Typ)))
11319               then
11320                  if Found then
11321                     It := Disambiguate (Pref, I1, I, Any_Type);
11322
11323                     if It = No_Interp then
11324                        Error_Msg_N ("ambiguous prefix for slicing",  N);
11325                        Set_Etype (N, Typ);
11326                        return;
11327                     else
11328                        Found := True;
11329                        Array_Type := It.Typ;
11330                        I1 := I;
11331                     end if;
11332                  else
11333                     Found := True;
11334                     Array_Type := It.Typ;
11335                     I1 := I;
11336                  end if;
11337               end if;
11338
11339               Get_Next_Interp (I, It);
11340            end loop;
11341         end;
11342
11343      else
11344         Array_Type := Etype (Pref);
11345      end if;
11346
11347      Resolve (Pref, Array_Type);
11348
11349      --  If the prefix's type is an access type, get to the real array type.
11350      --  Note: we do not apply an access check because an explicit dereference
11351      --  will be introduced later, and the check will happen there.
11352
11353      if Is_Access_Type (Array_Type) then
11354         Array_Type := Implicitly_Designated_Type (Array_Type);
11355
11356         --  If the prefix is an access to an unconstrained array, we must use
11357         --  the actual subtype of the object to perform the index checks. The
11358         --  object denoted by the prefix is implicit in the node, so we build
11359         --  an explicit representation for it in order to compute the actual
11360         --  subtype.
11361
11362         if not Is_Constrained (Array_Type) then
11363            Remove_Side_Effects (Pref);
11364
11365            declare
11366               Obj : constant Node_Id :=
11367                       Make_Explicit_Dereference (Sloc (N),
11368                         Prefix => New_Copy_Tree (Pref));
11369            begin
11370               Set_Etype (Obj, Array_Type);
11371               Set_Parent (Obj, Parent (N));
11372               Array_Type := Get_Actual_Subtype (Obj);
11373            end;
11374         end if;
11375
11376      --  In CodePeer mode the attribute Image is not expanded, so when it
11377      --  acts as a prefix of a slice, we handle it like a call to function
11378      --  returning an unconstrained string. Same for the Wide variants of
11379      --  attribute Image.
11380
11381      elsif Is_Entity_Name (Pref)
11382        or else Nkind (Pref) = N_Explicit_Dereference
11383        or else (Nkind (Pref) = N_Function_Call
11384                  and then not Is_Constrained (Etype (Pref)))
11385        or else (CodePeer_Mode
11386                  and then Nkind (Pref) = N_Attribute_Reference
11387                  and then Attribute_Name (Pref) in Name_Image
11388                                                  | Name_Wide_Image
11389                                                  | Name_Wide_Wide_Image)
11390      then
11391         Array_Type := Get_Actual_Subtype (Pref);
11392
11393      --  If the name is a selected component that depends on discriminants,
11394      --  build an actual subtype for it. This can happen only when the name
11395      --  itself is overloaded; otherwise the actual subtype is created when
11396      --  the selected component is analyzed.
11397
11398      elsif Nkind (Pref) = N_Selected_Component
11399        and then Full_Analysis
11400        and then Depends_On_Discriminant (First_Index (Array_Type))
11401      then
11402         declare
11403            Act_Decl : constant Node_Id :=
11404                         Build_Actual_Subtype_Of_Component (Array_Type, Pref);
11405         begin
11406            Insert_Action (N, Act_Decl);
11407            Array_Type := Defining_Identifier (Act_Decl);
11408         end;
11409
11410      --  Maybe this should just be "else", instead of checking for the
11411      --  specific case of slice??? This is needed for the case where the
11412      --  prefix is an Image attribute, which gets expanded to a slice, and so
11413      --  has a constrained subtype which we want to use for the slice range
11414      --  check applied below (the range check won't get done if the
11415      --  unconstrained subtype of the 'Image is used).
11416
11417      elsif Nkind (Pref) = N_Slice then
11418         Array_Type := Etype (Pref);
11419      end if;
11420
11421      --  Obtain the type of the array index
11422
11423      if Ekind (Array_Type) = E_String_Literal_Subtype then
11424         Index_Type := Etype (String_Literal_Low_Bound (Array_Type));
11425      else
11426         Index_Type := Etype (First_Index (Array_Type));
11427      end if;
11428
11429      --  If name was overloaded, set slice type correctly now
11430
11431      Set_Etype (N, Array_Type);
11432
11433      --  Handle the generation of a range check that compares the array index
11434      --  against the discrete_range. The check is not applied to internally
11435      --  built nodes associated with the expansion of dispatch tables. Check
11436      --  that Ada.Tags has already been loaded to avoid extra dependencies on
11437      --  the unit.
11438
11439      if Tagged_Type_Expansion
11440        and then RTU_Loaded (Ada_Tags)
11441        and then Nkind (Pref) = N_Selected_Component
11442        and then Present (Entity (Selector_Name (Pref)))
11443        and then Entity (Selector_Name (Pref)) =
11444                   RTE_Record_Component (RE_Prims_Ptr)
11445      then
11446         null;
11447
11448      --  The discrete_range is specified by a subtype name. Create an
11449      --  equivalent range attribute, apply checks to this attribute, but
11450      --  insert them into the range expression of the slice itself.
11451
11452      elsif Is_Entity_Name (Drange) then
11453         Dexpr :=
11454           Make_Attribute_Reference
11455             (Sloc (Drange),
11456              Prefix         =>
11457                New_Occurrence_Of (Entity (Drange), Sloc (Drange)),
11458              Attribute_Name => Name_Range);
11459
11460         Analyze_And_Resolve (Dexpr, Etype  (Drange));
11461
11462      elsif Nkind (Drange) = N_Subtype_Indication then
11463         Dexpr := Range_Expression (Constraint (Drange));
11464
11465      --  The discrete_range is a regular range (or a range attribute, which
11466      --  will be resolved into a regular range). Resolve the bounds and remove
11467      --  their side effects.
11468
11469      else
11470         Resolve (Drange, Base_Type (Index_Type));
11471
11472         if Nkind (Drange) = N_Range then
11473            Force_Evaluation (Low_Bound  (Drange));
11474            Force_Evaluation (High_Bound (Drange));
11475
11476            Dexpr := Drange;
11477         end if;
11478      end if;
11479
11480      if Present (Dexpr) then
11481         Apply_Range_Check (Dexpr, Index_Type, Insert_Node => Drange);
11482      end if;
11483
11484      Set_Slice_Subtype (N);
11485
11486      --  Check bad use of type with predicates
11487
11488      declare
11489         Subt : Entity_Id;
11490
11491      begin
11492         if Nkind (Drange) = N_Subtype_Indication
11493           and then Has_Predicates (Entity (Subtype_Mark (Drange)))
11494         then
11495            Subt := Entity (Subtype_Mark (Drange));
11496         else
11497            Subt := Etype (Drange);
11498         end if;
11499
11500         if Has_Predicates (Subt) then
11501            Bad_Predicated_Subtype_Use
11502              ("subtype& has predicate, not allowed in slice", Drange, Subt);
11503         end if;
11504      end;
11505
11506      --  Otherwise here is where we check suspicious indexes
11507
11508      if Nkind (Drange) = N_Range then
11509         Warn_On_Suspicious_Index (Pref, Low_Bound  (Drange));
11510         Warn_On_Suspicious_Index (Pref, High_Bound (Drange));
11511      end if;
11512
11513      Resolve_Implicit_Dereference (Pref);
11514      Analyze_Dimension (N);
11515      Eval_Slice (N);
11516   end Resolve_Slice;
11517
11518   ----------------------------
11519   -- Resolve_String_Literal --
11520   ----------------------------
11521
11522   procedure Resolve_String_Literal (N : Node_Id; Typ : Entity_Id) is
11523      C_Typ      : constant Entity_Id  := Component_Type (Typ);
11524      R_Typ      : constant Entity_Id  := Root_Type (C_Typ);
11525      Loc        : constant Source_Ptr := Sloc (N);
11526      Str        : constant String_Id  := Strval (N);
11527      Strlen     : constant Nat        := String_Length (Str);
11528      Subtype_Id : Entity_Id;
11529      Need_Check : Boolean;
11530
11531   begin
11532      --  For a string appearing in a concatenation, defer creation of the
11533      --  string_literal_subtype until the end of the resolution of the
11534      --  concatenation, because the literal may be constant-folded away. This
11535      --  is a useful optimization for long concatenation expressions.
11536
11537      --  If the string is an aggregate built for a single character (which
11538      --  happens in a non-static context) or a is null string to which special
11539      --  checks may apply, we build the subtype. Wide strings must also get a
11540      --  string subtype if they come from a one character aggregate. Strings
11541      --  generated by attributes might be static, but it is often hard to
11542      --  determine whether the enclosing context is static, so we generate
11543      --  subtypes for them as well, thus losing some rarer optimizations ???
11544      --  Same for strings that come from a static conversion.
11545
11546      Need_Check :=
11547        (Strlen = 0 and then Typ /= Standard_String)
11548          or else Nkind (Parent (N)) /= N_Op_Concat
11549          or else (N /= Left_Opnd (Parent (N))
11550                    and then N /= Right_Opnd (Parent (N)))
11551          or else ((Typ = Standard_Wide_String
11552                      or else Typ = Standard_Wide_Wide_String)
11553                    and then Nkind (Original_Node (N)) /= N_String_Literal);
11554
11555      --  If the resolving type is itself a string literal subtype, we can just
11556      --  reuse it, since there is no point in creating another.
11557
11558      if Ekind (Typ) = E_String_Literal_Subtype then
11559         Subtype_Id := Typ;
11560
11561      elsif Nkind (Parent (N)) = N_Op_Concat
11562        and then not Need_Check
11563        and then Nkind (Original_Node (N)) not in N_Character_Literal
11564                                                | N_Attribute_Reference
11565                                                | N_Qualified_Expression
11566                                                | N_Type_Conversion
11567      then
11568         Subtype_Id := Typ;
11569
11570      --  Do not generate a string literal subtype for the default expression
11571      --  of a formal parameter in GNATprove mode. This is because the string
11572      --  subtype is associated with the freezing actions of the subprogram,
11573      --  however freezing is disabled in GNATprove mode and as a result the
11574      --  subtype is unavailable.
11575
11576      elsif GNATprove_Mode
11577        and then Nkind (Parent (N)) = N_Parameter_Specification
11578      then
11579         Subtype_Id := Typ;
11580
11581      --  Otherwise we must create a string literal subtype. Note that the
11582      --  whole idea of string literal subtypes is simply to avoid the need
11583      --  for building a full fledged array subtype for each literal.
11584
11585      else
11586         Set_String_Literal_Subtype (N, Typ);
11587         Subtype_Id := Etype (N);
11588      end if;
11589
11590      if Nkind (Parent (N)) /= N_Op_Concat
11591        or else Need_Check
11592      then
11593         Set_Etype (N, Subtype_Id);
11594         Eval_String_Literal (N);
11595      end if;
11596
11597      if Is_Limited_Composite (Typ)
11598        or else Is_Private_Composite (Typ)
11599      then
11600         Error_Msg_N ("string literal not available for private array", N);
11601         Set_Etype (N, Any_Type);
11602         return;
11603      end if;
11604
11605      --  The validity of a null string has been checked in the call to
11606      --  Eval_String_Literal.
11607
11608      if Strlen = 0 then
11609         return;
11610
11611      --  Always accept string literal with component type Any_Character, which
11612      --  occurs in error situations and in comparisons of literals, both of
11613      --  which should accept all literals.
11614
11615      elsif R_Typ = Any_Character then
11616         return;
11617
11618      --  If the type is bit-packed, then we always transform the string
11619      --  literal into a full fledged aggregate.
11620
11621      elsif Is_Bit_Packed_Array (Typ) then
11622         null;
11623
11624      --  Deal with cases of Wide_Wide_String, Wide_String, and String
11625
11626      else
11627         --  For Standard.Wide_Wide_String, or any other type whose component
11628         --  type is Standard.Wide_Wide_Character, we know that all the
11629         --  characters in the string must be acceptable, since the parser
11630         --  accepted the characters as valid character literals.
11631
11632         if R_Typ = Standard_Wide_Wide_Character then
11633            null;
11634
11635         --  For the case of Standard.String, or any other type whose component
11636         --  type is Standard.Character, we must make sure that there are no
11637         --  wide characters in the string, i.e. that it is entirely composed
11638         --  of characters in range of type Character.
11639
11640         --  If the string literal is the result of a static concatenation, the
11641         --  test has already been performed on the components, and need not be
11642         --  repeated.
11643
11644         elsif R_Typ = Standard_Character
11645           and then Nkind (Original_Node (N)) /= N_Op_Concat
11646         then
11647            for J in 1 .. Strlen loop
11648               if not In_Character_Range (Get_String_Char (Str, J)) then
11649
11650                  --  If we are out of range, post error. This is one of the
11651                  --  very few places that we place the flag in the middle of
11652                  --  a token, right under the offending wide character. Not
11653                  --  quite clear if this is right wrt wide character encoding
11654                  --  sequences, but it's only an error message.
11655
11656                  Error_Msg
11657                    ("literal out of range of type Standard.Character",
11658                     Source_Ptr (Int (Loc) + J));
11659                  return;
11660               end if;
11661            end loop;
11662
11663         --  For the case of Standard.Wide_String, or any other type whose
11664         --  component type is Standard.Wide_Character, we must make sure that
11665         --  there are no wide characters in the string, i.e. that it is
11666         --  entirely composed of characters in range of type Wide_Character.
11667
11668         --  If the string literal is the result of a static concatenation,
11669         --  the test has already been performed on the components, and need
11670         --  not be repeated.
11671
11672         elsif R_Typ = Standard_Wide_Character
11673           and then Nkind (Original_Node (N)) /= N_Op_Concat
11674         then
11675            for J in 1 .. Strlen loop
11676               if not In_Wide_Character_Range (Get_String_Char (Str, J)) then
11677
11678                  --  If we are out of range, post error. This is one of the
11679                  --  very few places that we place the flag in the middle of
11680                  --  a token, right under the offending wide character.
11681
11682                  --  This is not quite right, because characters in general
11683                  --  will take more than one character position ???
11684
11685                  Error_Msg
11686                    ("literal out of range of type Standard.Wide_Character",
11687                     Source_Ptr (Int (Loc) + J));
11688                  return;
11689               end if;
11690            end loop;
11691
11692         --  If the root type is not a standard character, then we will convert
11693         --  the string into an aggregate and will let the aggregate code do
11694         --  the checking. Standard Wide_Wide_Character is also OK here.
11695
11696         else
11697            null;
11698         end if;
11699
11700         --  See if the component type of the array corresponding to the string
11701         --  has compile time known bounds. If yes we can directly check
11702         --  whether the evaluation of the string will raise constraint error.
11703         --  Otherwise we need to transform the string literal into the
11704         --  corresponding character aggregate and let the aggregate code do
11705         --  the checking. We use the same transformation if the component
11706         --  type has a static predicate, which will be applied to each
11707         --  character when the aggregate is resolved.
11708
11709         if Is_Standard_Character_Type (R_Typ) then
11710
11711            --  Check for the case of full range, where we are definitely OK
11712
11713            if Component_Type (Typ) = Base_Type (Component_Type (Typ)) then
11714               return;
11715            end if;
11716
11717            --  Here the range is not the complete base type range, so check
11718
11719            declare
11720               Comp_Typ_Lo : constant Node_Id :=
11721                               Type_Low_Bound (Component_Type (Typ));
11722               Comp_Typ_Hi : constant Node_Id :=
11723                               Type_High_Bound (Component_Type (Typ));
11724
11725               Char_Val : Int;
11726
11727            begin
11728               if Compile_Time_Known_Value (Comp_Typ_Lo)
11729                 and then Compile_Time_Known_Value (Comp_Typ_Hi)
11730               then
11731                  for J in 1 .. Strlen loop
11732                     Char_Val := Int (Get_String_Char (Str, J));
11733
11734                     if Char_Val < Expr_Value (Comp_Typ_Lo)
11735                       or else Char_Val > Expr_Value (Comp_Typ_Hi)
11736                     then
11737                        Apply_Compile_Time_Constraint_Error
11738                          (N, "character out of range??",
11739                           CE_Range_Check_Failed,
11740                           Loc => Source_Ptr (Int (Loc) + J));
11741                     end if;
11742                  end loop;
11743
11744                  if not Has_Static_Predicate (C_Typ) then
11745                     return;
11746                  end if;
11747               end if;
11748            end;
11749         end if;
11750      end if;
11751
11752      --  If we got here we meed to transform the string literal into the
11753      --  equivalent qualified positional array aggregate. This is rather
11754      --  heavy artillery for this situation, but it is hard work to avoid.
11755
11756      declare
11757         Lits : constant List_Id := New_List;
11758         P    : Source_Ptr := Loc + 1;
11759         C    : Char_Code;
11760
11761      begin
11762         --  Build the character literals, we give them source locations that
11763         --  correspond to the string positions, which is a bit tricky given
11764         --  the possible presence of wide character escape sequences.
11765
11766         for J in 1 .. Strlen loop
11767            C := Get_String_Char (Str, J);
11768            Set_Character_Literal_Name (C);
11769
11770            Append_To (Lits,
11771              Make_Character_Literal (P,
11772                Chars              => Name_Find,
11773                Char_Literal_Value => UI_From_CC (C)));
11774
11775            if In_Character_Range (C) then
11776               P := P + 1;
11777
11778            --  Should we have a call to Skip_Wide here ???
11779
11780            --  ???     else
11781            --             Skip_Wide (P);
11782
11783            end if;
11784         end loop;
11785
11786         Rewrite (N,
11787           Make_Qualified_Expression (Loc,
11788             Subtype_Mark => New_Occurrence_Of (Typ, Loc),
11789             Expression   =>
11790               Make_Aggregate (Loc, Expressions => Lits)));
11791
11792         Analyze_And_Resolve (N, Typ);
11793      end;
11794   end Resolve_String_Literal;
11795
11796   -------------------------
11797   -- Resolve_Target_Name --
11798   -------------------------
11799
11800   procedure Resolve_Target_Name (N : Node_Id; Typ : Entity_Id) is
11801   begin
11802      Set_Etype (N, Typ);
11803   end Resolve_Target_Name;
11804
11805   -----------------------------
11806   -- Resolve_Type_Conversion --
11807   -----------------------------
11808
11809   procedure Resolve_Type_Conversion (N : Node_Id; Typ : Entity_Id) is
11810      Conv_OK     : constant Boolean   := Conversion_OK (N);
11811      Operand     : constant Node_Id   := Expression (N);
11812      Operand_Typ : constant Entity_Id := Etype (Operand);
11813      Target_Typ  : constant Entity_Id := Etype (N);
11814      Rop         : Node_Id;
11815      Orig_N      : Node_Id;
11816      Orig_T      : Node_Id;
11817
11818      Test_Redundant : Boolean := Warn_On_Redundant_Constructs;
11819      --  Set to False to suppress cases where we want to suppress the test
11820      --  for redundancy to avoid possible false positives on this warning.
11821
11822   begin
11823      if not Conv_OK
11824        and then not Valid_Conversion (N, Target_Typ, Operand)
11825      then
11826         return;
11827      end if;
11828
11829      --  If the Operand Etype is Universal_Fixed, then the conversion is
11830      --  never redundant. We need this check because by the time we have
11831      --  finished the rather complex transformation, the conversion looks
11832      --  redundant when it is not.
11833
11834      if Operand_Typ = Universal_Fixed then
11835         Test_Redundant := False;
11836
11837      --  If the operand is marked as Any_Fixed, then special processing is
11838      --  required. This is also a case where we suppress the test for a
11839      --  redundant conversion, since most certainly it is not redundant.
11840
11841      elsif Operand_Typ = Any_Fixed then
11842         Test_Redundant := False;
11843
11844         --  Mixed-mode operation involving a literal. Context must be a fixed
11845         --  type which is applied to the literal subsequently.
11846
11847         --  Multiplication and division involving two fixed type operands must
11848         --  yield a universal real because the result is computed in arbitrary
11849         --  precision.
11850
11851         if Is_Fixed_Point_Type (Typ)
11852           and then Nkind (Operand) in N_Op_Divide | N_Op_Multiply
11853           and then Etype (Left_Opnd  (Operand)) = Any_Fixed
11854           and then Etype (Right_Opnd (Operand)) = Any_Fixed
11855         then
11856            Set_Etype (Operand, Universal_Real);
11857
11858         elsif Is_Numeric_Type (Typ)
11859           and then Nkind (Operand) in N_Op_Multiply | N_Op_Divide
11860           and then (Etype (Right_Opnd (Operand)) = Universal_Real
11861                       or else
11862                     Etype (Left_Opnd  (Operand)) = Universal_Real)
11863         then
11864            --  Return if expression is ambiguous
11865
11866            if Unique_Fixed_Point_Type (N) = Any_Type then
11867               return;
11868
11869            --  If nothing else, the available fixed type is Duration
11870
11871            else
11872               Set_Etype (Operand, Standard_Duration);
11873            end if;
11874
11875            --  Resolve the real operand with largest available precision
11876
11877            if Etype (Right_Opnd (Operand)) = Universal_Real then
11878               Rop := New_Copy_Tree (Right_Opnd (Operand));
11879            else
11880               Rop := New_Copy_Tree (Left_Opnd (Operand));
11881            end if;
11882
11883            Resolve (Rop, Universal_Real);
11884
11885            --  If the operand is a literal (it could be a non-static and
11886            --  illegal exponentiation) check whether the use of Duration
11887            --  is potentially inaccurate.
11888
11889            if Nkind (Rop) = N_Real_Literal
11890              and then Realval (Rop) /= Ureal_0
11891              and then abs (Realval (Rop)) < Delta_Value (Standard_Duration)
11892            then
11893               Error_Msg_N
11894                 ("??universal real operand can only "
11895                  & "be interpreted as Duration!", Rop);
11896               Error_Msg_N
11897                 ("\??precision will be lost in the conversion!", Rop);
11898            end if;
11899
11900         elsif Is_Numeric_Type (Typ)
11901           and then Nkind (Operand) in N_Op
11902           and then Unique_Fixed_Point_Type (N) /= Any_Type
11903         then
11904            Set_Etype (Operand, Standard_Duration);
11905
11906         else
11907            Error_Msg_N ("invalid context for mixed mode operation", N);
11908            Set_Etype (Operand, Any_Type);
11909            return;
11910         end if;
11911      end if;
11912
11913      Resolve (Operand);
11914
11915      Analyze_Dimension (N);
11916
11917      --  Note: we do the Eval_Type_Conversion call before applying the
11918      --  required checks for a subtype conversion. This is important, since
11919      --  both are prepared under certain circumstances to change the type
11920      --  conversion to a constraint error node, but in the case of
11921      --  Eval_Type_Conversion this may reflect an illegality in the static
11922      --  case, and we would miss the illegality (getting only a warning
11923      --  message), if we applied the type conversion checks first.
11924
11925      Eval_Type_Conversion (N);
11926
11927      --  Even when evaluation is not possible, we may be able to simplify the
11928      --  conversion or its expression. This needs to be done before applying
11929      --  checks, since otherwise the checks may use the original expression
11930      --  and defeat the simplifications. This is specifically the case for
11931      --  elimination of the floating-point Truncation attribute in
11932      --  float-to-int conversions.
11933
11934      Simplify_Type_Conversion (N);
11935
11936      --  If after evaluation we still have a type conversion, then we may need
11937      --  to apply checks required for a subtype conversion. But skip them if
11938      --  universal fixed operands are involved, since range checks are handled
11939      --  separately for these cases, after the expansion done by Exp_Fixd.
11940
11941      if Nkind (N) = N_Type_Conversion
11942        and then not Is_Generic_Type (Root_Type (Target_Typ))
11943        and then Target_Typ /= Universal_Fixed
11944        and then Etype (Operand) /= Universal_Fixed
11945      then
11946         Apply_Type_Conversion_Checks (N);
11947      end if;
11948
11949      --  Issue warning for conversion of simple object to its own type. We
11950      --  have to test the original nodes, since they may have been rewritten
11951      --  by various optimizations.
11952
11953      Orig_N := Original_Node (N);
11954
11955      --  Here we test for a redundant conversion if the warning mode is
11956      --  active (and was not locally reset), and we have a type conversion
11957      --  from source not appearing in a generic instance.
11958
11959      if Test_Redundant
11960        and then Nkind (Orig_N) = N_Type_Conversion
11961        and then Comes_From_Source (Orig_N)
11962        and then not In_Instance
11963      then
11964         Orig_N := Original_Node (Expression (Orig_N));
11965         Orig_T := Target_Typ;
11966
11967         --  If the node is part of a larger expression, the Target_Type
11968         --  may not be the original type of the node if the context is a
11969         --  condition. Recover original type to see if conversion is needed.
11970
11971         if Is_Boolean_Type (Orig_T)
11972          and then Nkind (Parent (N)) in N_Op
11973         then
11974            Orig_T := Etype (Parent (N));
11975         end if;
11976
11977         --  If we have an entity name, then give the warning if the entity
11978         --  is the right type, or if it is a loop parameter covered by the
11979         --  original type (that's needed because loop parameters have an
11980         --  odd subtype coming from the bounds).
11981
11982         if (Is_Entity_Name (Orig_N)
11983              and then Present (Entity (Orig_N))
11984              and then
11985                (Etype (Entity (Orig_N)) = Orig_T
11986                  or else
11987                    (Ekind (Entity (Orig_N)) = E_Loop_Parameter
11988                      and then Covers (Orig_T, Etype (Entity (Orig_N))))))
11989
11990           --  If not an entity, then type of expression must match
11991
11992           or else Etype (Orig_N) = Orig_T
11993         then
11994            --  One more check, do not give warning if the analyzed conversion
11995            --  has an expression with non-static bounds, and the bounds of the
11996            --  target are static. This avoids junk warnings in cases where the
11997            --  conversion is necessary to establish staticness, for example in
11998            --  a case statement.
11999
12000            if not Is_OK_Static_Subtype (Operand_Typ)
12001              and then Is_OK_Static_Subtype (Target_Typ)
12002            then
12003               null;
12004
12005            --  Finally, if this type conversion occurs in a context requiring
12006            --  a prefix, and the expression is a qualified expression then the
12007            --  type conversion is not redundant, since a qualified expression
12008            --  is not a prefix, whereas a type conversion is. For example, "X
12009            --  := T'(Funx(...)).Y;" is illegal because a selected component
12010            --  requires a prefix, but a type conversion makes it legal: "X :=
12011            --  T(T'(Funx(...))).Y;"
12012
12013            --  In Ada 2012, a qualified expression is a name, so this idiom is
12014            --  no longer needed, but we still suppress the warning because it
12015            --  seems unfriendly for warnings to pop up when you switch to the
12016            --  newer language version.
12017
12018            elsif Nkind (Orig_N) = N_Qualified_Expression
12019              and then Nkind (Parent (N)) in N_Attribute_Reference
12020                                           | N_Indexed_Component
12021                                           | N_Selected_Component
12022                                           | N_Slice
12023                                           | N_Explicit_Dereference
12024            then
12025               null;
12026
12027            --  Never warn on conversion to Long_Long_Integer'Base since
12028            --  that is most likely an artifact of the extended overflow
12029            --  checking and comes from complex expanded code.
12030
12031            elsif Orig_T = Base_Type (Standard_Long_Long_Integer) then
12032               null;
12033
12034            --  Here we give the redundant conversion warning. If it is an
12035            --  entity, give the name of the entity in the message. If not,
12036            --  just mention the expression.
12037
12038            else
12039               if Is_Entity_Name (Orig_N) then
12040                  Error_Msg_Node_2 := Orig_T;
12041                  Error_Msg_NE -- CODEFIX
12042                    ("?r?redundant conversion, & is of type &!",
12043                     N, Entity (Orig_N));
12044               else
12045                  Error_Msg_NE
12046                    ("?r?redundant conversion, expression is of type&!",
12047                     N, Orig_T);
12048               end if;
12049            end if;
12050         end if;
12051      end if;
12052
12053      --  Ada 2005 (AI-251): Handle class-wide interface type conversions.
12054      --  No need to perform any interface conversion if the type of the
12055      --  expression coincides with the target type.
12056
12057      if Ada_Version >= Ada_2005
12058        and then Expander_Active
12059        and then Operand_Typ /= Target_Typ
12060      then
12061         declare
12062            Opnd   : Entity_Id := Operand_Typ;
12063            Target : Entity_Id := Target_Typ;
12064
12065         begin
12066            --  If the type of the operand is a limited view, use nonlimited
12067            --  view when available. If it is a class-wide type, recover the
12068            --  class-wide type of the nonlimited view.
12069
12070            if From_Limited_With (Opnd)
12071              and then Has_Non_Limited_View (Opnd)
12072            then
12073               Opnd := Non_Limited_View (Opnd);
12074               Set_Etype (Expression (N), Opnd);
12075            end if;
12076
12077            --  It seems that Non_Limited_View should also be applied for
12078            --  Target when it has a limited view, but that leads to missing
12079            --  error checks on interface conversions further below. ???
12080
12081            if Is_Access_Type (Opnd) then
12082               Opnd := Designated_Type (Opnd);
12083
12084               --  If the type of the operand is a limited view, use nonlimited
12085               --  view when available. If it is a class-wide type, recover the
12086               --  class-wide type of the nonlimited view.
12087
12088               if From_Limited_With (Opnd)
12089                 and then Has_Non_Limited_View (Opnd)
12090               then
12091                  Opnd := Non_Limited_View (Opnd);
12092               end if;
12093            end if;
12094
12095            if Is_Access_Type (Target_Typ) then
12096               Target := Designated_Type (Target);
12097
12098               --  If the target type is a limited view, use nonlimited view
12099               --  when available.
12100
12101               if From_Limited_With (Target)
12102                 and then Has_Non_Limited_View (Target)
12103               then
12104                  Target := Non_Limited_View (Target);
12105               end if;
12106            end if;
12107
12108            if Opnd = Target then
12109               null;
12110
12111            --  Conversion from interface type
12112
12113            --  It seems that it would be better for the error checks below
12114            --  to be performed as part of Validate_Conversion (and maybe some
12115            --  of the error checks above could be moved as well?). ???
12116
12117            elsif Is_Interface (Opnd) then
12118
12119               --  Ada 2005 (AI-217): Handle entities from limited views
12120
12121               if From_Limited_With (Opnd) then
12122                  Error_Msg_Qual_Level := 99;
12123                  Error_Msg_NE -- CODEFIX
12124                    ("missing WITH clause on package &", N,
12125                    Cunit_Entity (Get_Source_Unit (Base_Type (Opnd))));
12126                  Error_Msg_N
12127                    ("type conversions require visibility of the full view",
12128                     N);
12129
12130               elsif From_Limited_With (Target)
12131                 and then not
12132                   (Is_Access_Type (Target_Typ)
12133                      and then Present (Non_Limited_View (Etype (Target))))
12134               then
12135                  Error_Msg_Qual_Level := 99;
12136                  Error_Msg_NE -- CODEFIX
12137                    ("missing WITH clause on package &", N,
12138                    Cunit_Entity (Get_Source_Unit (Base_Type (Target))));
12139                  Error_Msg_N
12140                    ("type conversions require visibility of the full view",
12141                     N);
12142
12143               else
12144                  Expand_Interface_Conversion (N);
12145               end if;
12146
12147            --  Conversion to interface type
12148
12149            elsif Is_Interface (Target) then
12150
12151               --  Handle subtypes
12152
12153               if Ekind (Opnd) in E_Protected_Subtype | E_Task_Subtype then
12154                  Opnd := Etype (Opnd);
12155               end if;
12156
12157               if Is_Class_Wide_Type (Opnd)
12158                 or else Interface_Present_In_Ancestor
12159                           (Typ   => Opnd,
12160                            Iface => Target)
12161               then
12162                  Expand_Interface_Conversion (N);
12163               else
12164                  Error_Msg_Name_1 := Chars (Etype (Target));
12165                  Error_Msg_Name_2 := Chars (Opnd);
12166                  Error_Msg_N
12167                    ("wrong interface conversion (% is not a progenitor "
12168                     & "of %)", N);
12169               end if;
12170            end if;
12171         end;
12172      end if;
12173
12174      --  Ada 2012: Once the type conversion is resolved, check whether the
12175      --  operand statisfies a static predicate of the target subtype, if any.
12176      --  In the static expression case, a predicate check failure is an error.
12177
12178      if Has_Predicates (Target_Typ) then
12179         Check_Expression_Against_Static_Predicate
12180           (N, Target_Typ, Static_Failure_Is_Error => True);
12181      end if;
12182
12183      --  If at this stage we have a fixed to integer conversion, make sure the
12184      --  Do_Range_Check flag is set, because such conversions in general need
12185      --  a range check. We only need this if expansion is off, see above why.
12186
12187      if Nkind (N) = N_Type_Conversion
12188        and then not Expander_Active
12189        and then Is_Integer_Type (Target_Typ)
12190        and then Is_Fixed_Point_Type (Operand_Typ)
12191        and then not Range_Checks_Suppressed (Target_Typ)
12192        and then not Range_Checks_Suppressed (Operand_Typ)
12193      then
12194         Set_Do_Range_Check (Operand);
12195      end if;
12196
12197      --  Generating C code a type conversion of an access to constrained
12198      --  array type to access to unconstrained array type involves building
12199      --  a fat pointer which in general cannot be generated on the fly. We
12200      --  remove side effects in order to store the result of the conversion
12201      --  into a temporary.
12202
12203      if Modify_Tree_For_C
12204        and then Nkind (N) = N_Type_Conversion
12205        and then Nkind (Parent (N)) /= N_Object_Declaration
12206        and then Is_Access_Type (Etype (N))
12207        and then Is_Array_Type (Designated_Type (Etype (N)))
12208        and then not Is_Constrained (Designated_Type (Etype (N)))
12209        and then Is_Constrained (Designated_Type (Etype (Expression (N))))
12210      then
12211         Remove_Side_Effects (N);
12212      end if;
12213   end Resolve_Type_Conversion;
12214
12215   ----------------------
12216   -- Resolve_Unary_Op --
12217   ----------------------
12218
12219   procedure Resolve_Unary_Op (N : Node_Id; Typ : Entity_Id) is
12220      B_Typ : constant Entity_Id := Base_Type (Typ);
12221      R     : constant Node_Id   := Right_Opnd (N);
12222      OK    : Boolean;
12223      Lo    : Uint;
12224      Hi    : Uint;
12225
12226   begin
12227      --  Deal with intrinsic unary operators
12228
12229      if Comes_From_Source (N)
12230        and then Ekind (Entity (N)) = E_Function
12231        and then Is_Imported (Entity (N))
12232        and then Is_Intrinsic_Subprogram (Entity (N))
12233      then
12234         Resolve_Intrinsic_Unary_Operator (N, Typ);
12235         return;
12236      end if;
12237
12238      --  Deal with universal cases
12239
12240      if Is_Universal_Numeric_Type (Etype (R)) then
12241         Check_For_Visible_Operator (N, B_Typ);
12242      end if;
12243
12244      Set_Etype (N, B_Typ);
12245      Resolve (R, B_Typ);
12246
12247      --  Generate warning for negative literal of a modular type, unless it is
12248      --  enclosed directly in a type qualification or a type conversion, as it
12249      --  is likely not what the user intended. We don't issue the warning for
12250      --  the common use of -1 to denote OxFFFF_FFFF...
12251
12252      if Warn_On_Suspicious_Modulus_Value
12253        and then Nkind (N) = N_Op_Minus
12254        and then Nkind (R) = N_Integer_Literal
12255        and then Is_Modular_Integer_Type (B_Typ)
12256        and then Nkind (Parent (N)) not in N_Qualified_Expression
12257                                         | N_Type_Conversion
12258        and then Expr_Value (R) > Uint_1
12259      then
12260         Error_Msg_N
12261           ("?.m?negative literal of modular type is in fact positive", N);
12262         Error_Msg_Uint_1 := (-Expr_Value (R)) mod Modulus (B_Typ);
12263         Error_Msg_Uint_2 := Expr_Value (R);
12264         Error_Msg_N ("\do you really mean^ when writing -^ '?", N);
12265         Error_Msg_N
12266           ("\if you do, use qualification to avoid this warning", N);
12267      end if;
12268
12269      --  Generate warning for expressions like abs (x mod 2)
12270
12271      if Warn_On_Redundant_Constructs
12272        and then Nkind (N) = N_Op_Abs
12273      then
12274         Determine_Range (Right_Opnd (N), OK, Lo, Hi);
12275
12276         if OK and then Hi >= Lo and then Lo >= 0 then
12277            Error_Msg_N -- CODEFIX
12278             ("?r?abs applied to known non-negative value has no effect", N);
12279         end if;
12280      end if;
12281
12282      --  Deal with reference generation
12283
12284      Check_Unset_Reference (R);
12285      Generate_Operator_Reference (N, B_Typ);
12286      Analyze_Dimension (N);
12287      Eval_Unary_Op (N);
12288
12289      --  Set overflow checking bit. Much cleverer code needed here eventually
12290      --  and perhaps the Resolve routines should be separated for the various
12291      --  arithmetic operations, since they will need different processing ???
12292
12293      if Nkind (N) in N_Op then
12294         if not Overflow_Checks_Suppressed (Etype (N)) then
12295            Enable_Overflow_Check (N);
12296         end if;
12297      end if;
12298
12299      --  Generate warning for expressions like -5 mod 3 for integers. No need
12300      --  to worry in the floating-point case, since parens do not affect the
12301      --  result so there is no point in giving in a warning.
12302
12303      declare
12304         Norig : constant Node_Id := Original_Node (N);
12305         Rorig : Node_Id;
12306         Val   : Uint;
12307         HB    : Uint;
12308         LB    : Uint;
12309         Lval  : Uint;
12310         Opnd  : Node_Id;
12311
12312      begin
12313         if Warn_On_Questionable_Missing_Parens
12314           and then Comes_From_Source (Norig)
12315           and then Is_Integer_Type (Typ)
12316           and then Nkind (Norig) = N_Op_Minus
12317         then
12318            Rorig := Original_Node (Right_Opnd (Norig));
12319
12320            --  We are looking for cases where the right operand is not
12321            --  parenthesized, and is a binary operator, multiply, divide, or
12322            --  mod. These are the cases where the grouping can affect results.
12323
12324            if Paren_Count (Rorig) = 0
12325              and then Nkind (Rorig) in N_Op_Mod | N_Op_Multiply | N_Op_Divide
12326            then
12327               --  For mod, we always give the warning, since the value is
12328               --  affected by the parenthesization (e.g. (-5) mod 315 /=
12329               --  -(5 mod 315)). But for the other cases, the only concern is
12330               --  overflow, e.g. for the case of 8 big signed (-(2 * 64)
12331               --  overflows, but (-2) * 64 does not). So we try to give the
12332               --  message only when overflow is possible.
12333
12334               if Nkind (Rorig) /= N_Op_Mod
12335                 and then Compile_Time_Known_Value (R)
12336               then
12337                  Val := Expr_Value (R);
12338
12339                  if Compile_Time_Known_Value (Type_High_Bound (Typ)) then
12340                     HB := Expr_Value (Type_High_Bound (Typ));
12341                  else
12342                     HB := Expr_Value (Type_High_Bound (Base_Type (Typ)));
12343                  end if;
12344
12345                  if Compile_Time_Known_Value (Type_Low_Bound (Typ)) then
12346                     LB := Expr_Value (Type_Low_Bound (Typ));
12347                  else
12348                     LB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
12349                  end if;
12350
12351                  --  Note that the test below is deliberately excluding the
12352                  --  largest negative number, since that is a potentially
12353                  --  troublesome case (e.g. -2 * x, where the result is the
12354                  --  largest negative integer has an overflow with 2 * x).
12355
12356                  if Val > LB and then Val <= HB then
12357                     return;
12358                  end if;
12359               end if;
12360
12361               --  For the multiplication case, the only case we have to worry
12362               --  about is when (-a)*b is exactly the largest negative number
12363               --  so that -(a*b) can cause overflow. This can only happen if
12364               --  a is a power of 2, and more generally if any operand is a
12365               --  constant that is not a power of 2, then the parentheses
12366               --  cannot affect whether overflow occurs. We only bother to
12367               --  test the left most operand
12368
12369               --  Loop looking at left operands for one that has known value
12370
12371               Opnd := Rorig;
12372               Opnd_Loop : while Nkind (Opnd) = N_Op_Multiply loop
12373                  if Compile_Time_Known_Value (Left_Opnd (Opnd)) then
12374                     Lval := UI_Abs (Expr_Value (Left_Opnd (Opnd)));
12375
12376                     --  Operand value of 0 or 1 skips warning
12377
12378                     if Lval <= 1 then
12379                        return;
12380
12381                     --  Otherwise check power of 2, if power of 2, warn, if
12382                     --  anything else, skip warning.
12383
12384                     else
12385                        while Lval /= 2 loop
12386                           if Lval mod 2 = 1 then
12387                              return;
12388                           else
12389                              Lval := Lval / 2;
12390                           end if;
12391                        end loop;
12392
12393                        exit Opnd_Loop;
12394                     end if;
12395                  end if;
12396
12397                  --  Keep looking at left operands
12398
12399                  Opnd := Left_Opnd (Opnd);
12400               end loop Opnd_Loop;
12401
12402               --  For rem or "/" we can only have a problematic situation
12403               --  if the divisor has a value of minus one or one. Otherwise
12404               --  overflow is impossible (divisor > 1) or we have a case of
12405               --  division by zero in any case.
12406
12407               if Nkind (Rorig) in N_Op_Divide | N_Op_Rem
12408                 and then Compile_Time_Known_Value (Right_Opnd (Rorig))
12409                 and then UI_Abs (Expr_Value (Right_Opnd (Rorig))) /= 1
12410               then
12411                  return;
12412               end if;
12413
12414               --  If we fall through warning should be issued
12415
12416               --  Shouldn't we test Warn_On_Questionable_Missing_Parens ???
12417
12418               Error_Msg_N
12419                 ("??unary minus expression should be parenthesized here!", N);
12420            end if;
12421         end if;
12422      end;
12423   end Resolve_Unary_Op;
12424
12425   ----------------------------------
12426   -- Resolve_Unchecked_Expression --
12427   ----------------------------------
12428
12429   procedure Resolve_Unchecked_Expression
12430     (N   : Node_Id;
12431      Typ : Entity_Id)
12432   is
12433   begin
12434      Resolve (Expression (N), Typ, Suppress => All_Checks);
12435      Set_Etype (N, Typ);
12436   end Resolve_Unchecked_Expression;
12437
12438   ---------------------------------------
12439   -- Resolve_Unchecked_Type_Conversion --
12440   ---------------------------------------
12441
12442   procedure Resolve_Unchecked_Type_Conversion
12443     (N   : Node_Id;
12444      Typ : Entity_Id)
12445   is
12446      pragma Warnings (Off, Typ);
12447
12448      Operand   : constant Node_Id   := Expression (N);
12449      Opnd_Type : constant Entity_Id := Etype (Operand);
12450
12451   begin
12452      --  Resolve operand using its own type
12453
12454      Resolve (Operand, Opnd_Type);
12455
12456      --  If the expression is a conversion to universal integer of an
12457      --  an expression with an integer type, then we can eliminate the
12458      --  intermediate conversion to universal integer.
12459
12460      if Nkind (Operand) = N_Type_Conversion
12461        and then Entity (Subtype_Mark (Operand)) = Universal_Integer
12462        and then Is_Integer_Type (Etype (Expression (Operand)))
12463      then
12464         Rewrite (Operand, Relocate_Node (Expression (Operand)));
12465         Analyze_And_Resolve (Operand);
12466      end if;
12467
12468      --  In an inlined context, the unchecked conversion may be applied
12469      --  to a literal, in which case its type is the type of the context.
12470      --  (In other contexts conversions cannot apply to literals).
12471
12472      if In_Inlined_Body
12473        and then (Opnd_Type = Any_Character or else
12474                  Opnd_Type = Any_Integer   or else
12475                  Opnd_Type = Any_Real)
12476      then
12477         Set_Etype (Operand, Typ);
12478      end if;
12479
12480      Analyze_Dimension (N);
12481      Eval_Unchecked_Conversion (N);
12482   end Resolve_Unchecked_Type_Conversion;
12483
12484   ------------------------------
12485   -- Rewrite_Operator_As_Call --
12486   ------------------------------
12487
12488   procedure Rewrite_Operator_As_Call (N : Node_Id; Nam : Entity_Id) is
12489      Loc     : constant Source_Ptr := Sloc (N);
12490      Actuals : constant List_Id    := New_List;
12491      New_N   : Node_Id;
12492
12493   begin
12494      if Nkind (N) in N_Binary_Op then
12495         Append (Left_Opnd (N), Actuals);
12496      end if;
12497
12498      Append (Right_Opnd (N), Actuals);
12499
12500      New_N :=
12501        Make_Function_Call (Sloc => Loc,
12502          Name => New_Occurrence_Of (Nam, Loc),
12503          Parameter_Associations => Actuals);
12504
12505      Preserve_Comes_From_Source (New_N, N);
12506      Preserve_Comes_From_Source (Name (New_N), N);
12507      Rewrite (N, New_N);
12508      Set_Etype (N, Etype (Nam));
12509   end Rewrite_Operator_As_Call;
12510
12511   ------------------------------
12512   -- Rewrite_Renamed_Operator --
12513   ------------------------------
12514
12515   procedure Rewrite_Renamed_Operator
12516     (N   : Node_Id;
12517      Op  : Entity_Id;
12518      Typ : Entity_Id)
12519   is
12520      Nam       : constant Name_Id := Chars (Op);
12521      Is_Binary : constant Boolean := Nkind (N) in N_Binary_Op;
12522      Op_Node   : Node_Id;
12523
12524   begin
12525      --  Do not perform this transformation within a pre/postcondition,
12526      --  because the expression will be reanalyzed, and the transformation
12527      --  might affect the visibility of the operator, e.g. in an instance.
12528      --  Note that fully analyzed and expanded pre/postconditions appear as
12529      --  pragma Check equivalents.
12530
12531      if In_Pre_Post_Condition (N) then
12532         return;
12533      end if;
12534
12535      --  Likewise when an expression function is being preanalyzed, since the
12536      --  expression will be reanalyzed as part of the generated body.
12537
12538      if In_Spec_Expression then
12539         declare
12540            S : constant Entity_Id := Current_Scope_No_Loops;
12541         begin
12542            if Ekind (S) = E_Function
12543              and then Nkind (Original_Node (Unit_Declaration_Node (S))) =
12544                         N_Expression_Function
12545            then
12546               return;
12547            end if;
12548         end;
12549      end if;
12550
12551      --  Rewrite the operator node using the real operator, not its renaming.
12552      --  Exclude user-defined intrinsic operations of the same name, which are
12553      --  treated separately and rewritten as calls.
12554
12555      if Ekind (Op) /= E_Function or else Chars (N) /= Nam then
12556         Op_Node := New_Node (Operator_Kind (Nam, Is_Binary), Sloc (N));
12557         Set_Chars      (Op_Node, Nam);
12558         Set_Etype      (Op_Node, Etype (N));
12559         Set_Entity     (Op_Node, Op);
12560         Set_Right_Opnd (Op_Node, Right_Opnd (N));
12561
12562         --  Indicate that both the original entity and its renaming are
12563         --  referenced at this point.
12564
12565         Generate_Reference (Entity (N), N);
12566         Generate_Reference (Op, N);
12567
12568         if Is_Binary then
12569            Set_Left_Opnd (Op_Node, Left_Opnd (N));
12570         end if;
12571
12572         Rewrite (N, Op_Node);
12573
12574         --  If the context type is private, add the appropriate conversions so
12575         --  that the operator is applied to the full view. This is done in the
12576         --  routines that resolve intrinsic operators.
12577
12578         if Is_Intrinsic_Subprogram (Op) and then Is_Private_Type (Typ) then
12579            case Nkind (N) is
12580               when N_Op_Add
12581                  | N_Op_Divide
12582                  | N_Op_Expon
12583                  | N_Op_Mod
12584                  | N_Op_Multiply
12585                  | N_Op_Rem
12586                  | N_Op_Subtract
12587               =>
12588                  Resolve_Intrinsic_Operator (N, Typ);
12589
12590               when N_Op_Abs
12591                  | N_Op_Minus
12592                  | N_Op_Plus
12593               =>
12594                  Resolve_Intrinsic_Unary_Operator (N, Typ);
12595
12596               when others =>
12597                  Resolve (N, Typ);
12598            end case;
12599         end if;
12600
12601      elsif Ekind (Op) = E_Function and then Is_Intrinsic_Subprogram (Op) then
12602
12603         --  Operator renames a user-defined operator of the same name. Use the
12604         --  original operator in the node, which is the one Gigi knows about.
12605
12606         Set_Entity (N, Op);
12607         Set_Is_Overloaded (N, False);
12608      end if;
12609   end Rewrite_Renamed_Operator;
12610
12611   -----------------------
12612   -- Set_Slice_Subtype --
12613   -----------------------
12614
12615   --  Build an implicit subtype declaration to represent the type delivered by
12616   --  the slice. This is an abbreviated version of an array subtype. We define
12617   --  an index subtype for the slice, using either the subtype name or the
12618   --  discrete range of the slice. To be consistent with index usage elsewhere
12619   --  we create a list header to hold the single index. This list is not
12620   --  otherwise attached to the syntax tree.
12621
12622   procedure Set_Slice_Subtype (N : Node_Id) is
12623      Loc           : constant Source_Ptr := Sloc (N);
12624      Index_List    : constant List_Id    := New_List;
12625      Index         : Node_Id;
12626      Index_Subtype : Entity_Id;
12627      Index_Type    : Entity_Id;
12628      Slice_Subtype : Entity_Id;
12629      Drange        : constant Node_Id := Discrete_Range (N);
12630
12631   begin
12632      Index_Type := Base_Type (Etype (Drange));
12633
12634      if Is_Entity_Name (Drange) then
12635         Index_Subtype := Entity (Drange);
12636
12637      else
12638         --  We force the evaluation of a range. This is definitely needed in
12639         --  the renamed case, and seems safer to do unconditionally. Note in
12640         --  any case that since we will create and insert an Itype referring
12641         --  to this range, we must make sure any side effect removal actions
12642         --  are inserted before the Itype definition.
12643
12644         if Nkind (Drange) = N_Range then
12645            Force_Evaluation (Low_Bound (Drange));
12646            Force_Evaluation (High_Bound (Drange));
12647
12648         --  If the discrete range is given by a subtype indication, the
12649         --  type of the slice is the base of the subtype mark.
12650
12651         elsif Nkind (Drange) = N_Subtype_Indication then
12652            declare
12653               R : constant Node_Id := Range_Expression (Constraint (Drange));
12654            begin
12655               Index_Type := Base_Type (Entity (Subtype_Mark (Drange)));
12656               Force_Evaluation (Low_Bound  (R));
12657               Force_Evaluation (High_Bound (R));
12658            end;
12659         end if;
12660
12661         Index_Subtype := Create_Itype (Subtype_Kind (Ekind (Index_Type)), N);
12662
12663         --  Take a new copy of Drange (where bounds have been rewritten to
12664         --  reference side-effect-free names). Using a separate tree ensures
12665         --  that further expansion (e.g. while rewriting a slice assignment
12666         --  into a FOR loop) does not attempt to remove side effects on the
12667         --  bounds again (which would cause the bounds in the index subtype
12668         --  definition to refer to temporaries before they are defined) (the
12669         --  reason is that some names are considered side effect free here
12670         --  for the subtype, but not in the context of a loop iteration
12671         --  scheme).
12672
12673         Set_Scalar_Range   (Index_Subtype, New_Copy_Tree (Drange));
12674         Set_Parent         (Scalar_Range (Index_Subtype), Index_Subtype);
12675         Set_Etype          (Index_Subtype, Index_Type);
12676         Set_Size_Info      (Index_Subtype, Index_Type);
12677         Set_RM_Size        (Index_Subtype, RM_Size (Index_Type));
12678         Set_Is_Constrained (Index_Subtype);
12679      end if;
12680
12681      Slice_Subtype := Create_Itype (E_Array_Subtype, N);
12682
12683      Index := New_Occurrence_Of (Index_Subtype, Loc);
12684      Set_Etype (Index, Index_Subtype);
12685      Append (Index, Index_List);
12686
12687      Set_First_Index    (Slice_Subtype, Index);
12688      Set_Etype          (Slice_Subtype, Base_Type (Etype (N)));
12689      Set_Is_Constrained (Slice_Subtype, True);
12690
12691      Check_Compile_Time_Size (Slice_Subtype);
12692
12693      --  The Etype of the existing Slice node is reset to this slice subtype.
12694      --  Its bounds are obtained from its first index.
12695
12696      Set_Etype (N, Slice_Subtype);
12697
12698      --  For bit-packed slice subtypes, freeze immediately (except in the case
12699      --  of being in a "spec expression" where we never freeze when we first
12700      --  see the expression).
12701
12702      if Is_Bit_Packed_Array (Slice_Subtype) and not In_Spec_Expression then
12703         Freeze_Itype (Slice_Subtype, N);
12704
12705      --  For all other cases insert an itype reference in the slice's actions
12706      --  so that the itype is frozen at the proper place in the tree (i.e. at
12707      --  the point where actions for the slice are analyzed). Note that this
12708      --  is different from freezing the itype immediately, which might be
12709      --  premature (e.g. if the slice is within a transient scope). This needs
12710      --  to be done only if expansion is enabled.
12711
12712      elsif Expander_Active then
12713         Ensure_Defined (Typ => Slice_Subtype, N => N);
12714      end if;
12715   end Set_Slice_Subtype;
12716
12717   --------------------------------
12718   -- Set_String_Literal_Subtype --
12719   --------------------------------
12720
12721   procedure Set_String_Literal_Subtype (N : Node_Id; Typ : Entity_Id) is
12722      Loc        : constant Source_Ptr := Sloc (N);
12723      Low_Bound  : constant Node_Id :=
12724                     Type_Low_Bound (Etype (First_Index (Typ)));
12725      Subtype_Id : Entity_Id;
12726
12727   begin
12728      if Nkind (N) /= N_String_Literal then
12729         return;
12730      end if;
12731
12732      Subtype_Id := Create_Itype (E_String_Literal_Subtype, N);
12733      Set_String_Literal_Length (Subtype_Id, UI_From_Int
12734                                               (String_Length (Strval (N))));
12735      Set_Etype          (Subtype_Id, Base_Type (Typ));
12736      Set_Is_Constrained (Subtype_Id);
12737      Set_Etype          (N, Subtype_Id);
12738
12739      --  The low bound is set from the low bound of the corresponding index
12740      --  type. Note that we do not store the high bound in the string literal
12741      --  subtype, but it can be deduced if necessary from the length and the
12742      --  low bound.
12743
12744      if Is_OK_Static_Expression (Low_Bound) then
12745         Set_String_Literal_Low_Bound (Subtype_Id, Low_Bound);
12746
12747      --  If the lower bound is not static we create a range for the string
12748      --  literal, using the index type and the known length of the literal.
12749      --  If the length is 1, then the upper bound is set to a mere copy of
12750      --  the lower bound; or else, if the index type is a signed integer,
12751      --  then the upper bound is computed as Low_Bound + L - 1; otherwise,
12752      --  the upper bound is computed as T'Val (T'Pos (Low_Bound) + L - 1).
12753
12754      else
12755         declare
12756            Length        : constant Nat := String_Length (Strval (N));
12757            Index_List    : constant List_Id   := New_List;
12758            Index_Type    : constant Entity_Id := Etype (First_Index (Typ));
12759            Array_Subtype : Entity_Id;
12760            Drange        : Node_Id;
12761            High_Bound    : Node_Id;
12762            Index         : Node_Id;
12763            Index_Subtype : Entity_Id;
12764
12765         begin
12766            if Length = 1 then
12767               High_Bound := New_Copy_Tree (Low_Bound);
12768
12769            elsif Is_Signed_Integer_Type (Index_Type) then
12770               High_Bound :=
12771                 Make_Op_Add (Loc,
12772                   Left_Opnd  => New_Copy_Tree (Low_Bound),
12773                   Right_Opnd => Make_Integer_Literal (Loc, Length - 1));
12774
12775            else
12776               High_Bound :=
12777                 Make_Attribute_Reference (Loc,
12778                   Attribute_Name => Name_Val,
12779                   Prefix         =>
12780                     New_Occurrence_Of (Index_Type, Loc),
12781                   Expressions    => New_List (
12782                     Make_Op_Add (Loc,
12783                       Left_Opnd  =>
12784                         Make_Attribute_Reference (Loc,
12785                           Attribute_Name => Name_Pos,
12786                           Prefix         =>
12787                             New_Occurrence_Of (Index_Type, Loc),
12788                           Expressions    =>
12789                             New_List (New_Copy_Tree (Low_Bound))),
12790                       Right_Opnd =>
12791                         Make_Integer_Literal (Loc, Length - 1))));
12792            end if;
12793
12794            if Is_Integer_Type (Index_Type) then
12795               Set_String_Literal_Low_Bound
12796                 (Subtype_Id, Make_Integer_Literal (Loc, 1));
12797
12798            else
12799               --  If the index type is an enumeration type, build bounds
12800               --  expression with attributes.
12801
12802               Set_String_Literal_Low_Bound
12803                 (Subtype_Id,
12804                  Make_Attribute_Reference (Loc,
12805                    Attribute_Name => Name_First,
12806                    Prefix         =>
12807                      New_Occurrence_Of (Base_Type (Index_Type), Loc)));
12808            end if;
12809
12810            Analyze_And_Resolve
12811              (String_Literal_Low_Bound (Subtype_Id), Base_Type (Index_Type));
12812
12813            --  Build bona fide subtype for the string, and wrap it in an
12814            --  unchecked conversion, because the back end expects the
12815            --  String_Literal_Subtype to have a static lower bound.
12816
12817            Index_Subtype :=
12818              Create_Itype (Subtype_Kind (Ekind (Index_Type)), N);
12819            Drange := Make_Range (Loc, New_Copy_Tree (Low_Bound), High_Bound);
12820            Set_Scalar_Range (Index_Subtype, Drange);
12821            Set_Parent (Drange, N);
12822            Analyze_And_Resolve (Drange, Index_Type);
12823
12824            --  In this context, the Index_Type may already have a constraint,
12825            --  so use common base type on string subtype. The base type may
12826            --  be used when generating attributes of the string, for example
12827            --  in the context of a slice assignment.
12828
12829            Set_Etype     (Index_Subtype, Base_Type (Index_Type));
12830            Set_Size_Info (Index_Subtype, Index_Type);
12831            Set_RM_Size   (Index_Subtype, RM_Size (Index_Type));
12832
12833            Array_Subtype := Create_Itype (E_Array_Subtype, N);
12834
12835            Index := New_Occurrence_Of (Index_Subtype, Loc);
12836            Set_Etype (Index, Index_Subtype);
12837            Append (Index, Index_List);
12838
12839            Set_First_Index    (Array_Subtype, Index);
12840            Set_Etype          (Array_Subtype, Base_Type (Typ));
12841            Set_Is_Constrained (Array_Subtype, True);
12842
12843            Rewrite (N, Unchecked_Convert_To (Array_Subtype, N));
12844            Set_Etype (N, Array_Subtype);
12845         end;
12846      end if;
12847   end Set_String_Literal_Subtype;
12848
12849   ------------------------------
12850   -- Simplify_Type_Conversion --
12851   ------------------------------
12852
12853   procedure Simplify_Type_Conversion (N : Node_Id) is
12854   begin
12855      if Nkind (N) = N_Type_Conversion then
12856         declare
12857            Operand    : constant Node_Id   := Expression (N);
12858            Target_Typ : constant Entity_Id := Etype (N);
12859            Opnd_Typ   : constant Entity_Id := Etype (Operand);
12860
12861         begin
12862            --  Special processing if the conversion is the expression of a
12863            --  Rounding or Truncation attribute reference. In this case we
12864            --  replace:
12865
12866            --     ityp (ftyp'Rounding (x)) or ityp (ftyp'Truncation (x))
12867
12868            --  by
12869
12870            --     ityp (x)
12871
12872            --  with the Float_Truncate flag set to False or True respectively,
12873            --  which is more efficient. We reuse Rounding for Machine_Rounding
12874            --  as System.Fat_Gen, which is a permissible behavior.
12875
12876            if Is_Floating_Point_Type (Opnd_Typ)
12877              and then
12878                (Is_Integer_Type (Target_Typ)
12879                  or else (Is_Fixed_Point_Type (Target_Typ)
12880                            and then Conversion_OK (N)))
12881              and then Nkind (Operand) = N_Attribute_Reference
12882              and then Attribute_Name (Operand) in Name_Rounding
12883                                                 | Name_Machine_Rounding
12884                                                 | Name_Truncation
12885            then
12886               declare
12887                  Truncate : constant Boolean :=
12888                               Attribute_Name (Operand) = Name_Truncation;
12889               begin
12890                  Rewrite (Operand,
12891                    Relocate_Node (First (Expressions (Operand))));
12892                  Set_Float_Truncate (N, Truncate);
12893               end;
12894
12895            --  Special processing for the conversion of an integer literal to
12896            --  a dynamic type: we first convert the literal to the root type
12897            --  and then convert the result to the target type, the goal being
12898            --  to avoid doing range checks in universal integer.
12899
12900            elsif Is_Integer_Type (Target_Typ)
12901              and then not Is_Generic_Type (Root_Type (Target_Typ))
12902              and then Nkind (Operand) = N_Integer_Literal
12903              and then Opnd_Typ = Universal_Integer
12904            then
12905               Convert_To_And_Rewrite (Root_Type (Target_Typ), Operand);
12906               Analyze_And_Resolve (Operand);
12907
12908            --  If the expression is a conversion to universal integer of an
12909            --  an expression with an integer type, then we can eliminate the
12910            --  intermediate conversion to universal integer.
12911
12912            elsif Nkind (Operand) = N_Type_Conversion
12913              and then Entity (Subtype_Mark (Operand)) = Universal_Integer
12914              and then Is_Integer_Type (Etype (Expression (Operand)))
12915            then
12916               Rewrite (Operand, Relocate_Node (Expression (Operand)));
12917               Analyze_And_Resolve (Operand);
12918            end if;
12919         end;
12920      end if;
12921   end Simplify_Type_Conversion;
12922
12923   ------------------------------
12924   -- Try_User_Defined_Literal --
12925   ------------------------------
12926
12927   function Try_User_Defined_Literal
12928     (N   : Node_Id;
12929      Typ : Entity_Id) return Boolean
12930   is
12931   begin
12932      if Nkind (N) in N_Op_Add | N_Op_Divide | N_Op_Mod | N_Op_Multiply
12933        | N_Op_Rem | N_Op_Subtract
12934      then
12935
12936         --  Both operands must have the same type as the context.
12937         --  (ignoring for now fixed-point and exponentiation ops).
12938
12939         if Has_Applicable_User_Defined_Literal (Right_Opnd (N), Typ) then
12940            Resolve (Left_Opnd (N), Typ);
12941            Analyze_And_Resolve (N, Typ);
12942            return True;
12943         end if;
12944
12945         if
12946           Has_Applicable_User_Defined_Literal (Left_Opnd (N), Typ)
12947         then
12948            Resolve (Right_Opnd (N), Typ);
12949            Analyze_And_Resolve (N, Typ);
12950            return True;
12951
12952         else
12953            return False;
12954         end if;
12955
12956      elsif Nkind (N) in N_Binary_Op then
12957         --  For other operators the context does not impose a type on
12958         --  the operands, but their types must match.
12959
12960         if (Nkind (Left_Opnd (N))
12961           not in N_Integer_Literal | N_String_Literal | N_Real_Literal)
12962         and then
12963           Has_Applicable_User_Defined_Literal
12964             (Right_Opnd (N), Etype (Left_Opnd (N)))
12965         then
12966            Analyze_And_Resolve (N, Typ);
12967            return True;
12968
12969         elsif (Nkind (Right_Opnd (N))
12970           not in N_Integer_Literal | N_String_Literal | N_Real_Literal)
12971         and then
12972           Has_Applicable_User_Defined_Literal
12973             (Left_Opnd (N), Etype (Right_Opnd (N)))
12974         then
12975            Analyze_And_Resolve (N, Typ);
12976            return True;
12977         else
12978            return False;
12979         end if;
12980
12981      elsif Nkind (N) in N_Unary_Op
12982        and then
12983          Has_Applicable_User_Defined_Literal (Right_Opnd (N), Typ)
12984      then
12985         Analyze_And_Resolve (N, Typ);
12986         return True;
12987
12988      else   --  Other operators
12989         return False;
12990      end if;
12991   end Try_User_Defined_Literal;
12992
12993   -----------------------------
12994   -- Unique_Fixed_Point_Type --
12995   -----------------------------
12996
12997   function Unique_Fixed_Point_Type (N : Node_Id) return Entity_Id is
12998      procedure Fixed_Point_Error (T1 : Entity_Id; T2 : Entity_Id);
12999      --  Give error messages for true ambiguity. Messages are posted on node
13000      --  N, and entities T1, T2 are the possible interpretations.
13001
13002      -----------------------
13003      -- Fixed_Point_Error --
13004      -----------------------
13005
13006      procedure Fixed_Point_Error (T1 : Entity_Id; T2 : Entity_Id) is
13007      begin
13008         Error_Msg_N ("ambiguous universal_fixed_expression", N);
13009         Error_Msg_NE ("\\possible interpretation as}", N, T1);
13010         Error_Msg_NE ("\\possible interpretation as}", N, T2);
13011      end Fixed_Point_Error;
13012
13013      --  Local variables
13014
13015      ErrN : Node_Id;
13016      Item : Node_Id;
13017      Scop : Entity_Id;
13018      T1   : Entity_Id;
13019      T2   : Entity_Id;
13020
13021   --  Start of processing for Unique_Fixed_Point_Type
13022
13023   begin
13024      --  The operations on Duration are visible, so Duration is always a
13025      --  possible interpretation.
13026
13027      T1 := Standard_Duration;
13028
13029      --  Look for fixed-point types in enclosing scopes
13030
13031      Scop := Current_Scope;
13032      while Scop /= Standard_Standard loop
13033         T2 := First_Entity (Scop);
13034         while Present (T2) loop
13035            if Is_Fixed_Point_Type (T2)
13036              and then Current_Entity (T2) = T2
13037              and then Scope (Base_Type (T2)) = Scop
13038            then
13039               if Present (T1) then
13040                  Fixed_Point_Error (T1, T2);
13041                  return Any_Type;
13042               else
13043                  T1 := T2;
13044               end if;
13045            end if;
13046
13047            Next_Entity (T2);
13048         end loop;
13049
13050         Scop := Scope (Scop);
13051      end loop;
13052
13053      --  Look for visible fixed type declarations in the context
13054
13055      Item := First (Context_Items (Cunit (Current_Sem_Unit)));
13056      while Present (Item) loop
13057         if Nkind (Item) = N_With_Clause then
13058            Scop := Entity (Name (Item));
13059            T2 := First_Entity (Scop);
13060            while Present (T2) loop
13061               if Is_Fixed_Point_Type (T2)
13062                 and then Scope (Base_Type (T2)) = Scop
13063                 and then (Is_Potentially_Use_Visible (T2) or else In_Use (T2))
13064               then
13065                  if Present (T1) then
13066                     Fixed_Point_Error (T1, T2);
13067                     return Any_Type;
13068                  else
13069                     T1 := T2;
13070                  end if;
13071               end if;
13072
13073               Next_Entity (T2);
13074            end loop;
13075         end if;
13076
13077         Next (Item);
13078      end loop;
13079
13080      if Nkind (N) = N_Real_Literal then
13081         Error_Msg_NE ("??real literal interpreted as }!", N, T1);
13082
13083      else
13084         --  When the context is a type conversion, issue the warning on the
13085         --  expression of the conversion because it is the actual operation.
13086
13087         if Nkind (N) in N_Type_Conversion | N_Unchecked_Type_Conversion then
13088            ErrN := Expression (N);
13089         else
13090            ErrN := N;
13091         end if;
13092
13093         Error_Msg_NE
13094           ("??universal_fixed expression interpreted as }!", ErrN, T1);
13095      end if;
13096
13097      return T1;
13098   end Unique_Fixed_Point_Type;
13099
13100   ----------------------
13101   -- Valid_Conversion --
13102   ----------------------
13103
13104   function Valid_Conversion
13105     (N           : Node_Id;
13106      Target      : Entity_Id;
13107      Operand     : Node_Id;
13108      Report_Errs : Boolean := True) return Boolean
13109   is
13110      Target_Type  : constant Entity_Id := Base_Type (Target);
13111      Opnd_Type    : Entity_Id          := Etype (Operand);
13112      Inc_Ancestor : Entity_Id;
13113
13114      function Conversion_Check
13115        (Valid : Boolean;
13116         Msg   : String) return Boolean;
13117      --  Little routine to post Msg if Valid is False, returns Valid value
13118
13119      procedure Conversion_Error_N (Msg : String; N : Node_Or_Entity_Id);
13120      --  If Report_Errs, then calls Errout.Error_Msg_N with its arguments
13121
13122      procedure Conversion_Error_NE
13123        (Msg : String;
13124         N   : Node_Or_Entity_Id;
13125         E   : Node_Or_Entity_Id);
13126      --  If Report_Errs, then calls Errout.Error_Msg_NE with its arguments
13127
13128      function In_Instance_Code return Boolean;
13129      --  Return True if expression is within an instance but is not in one of
13130      --  the actuals of the instantiation. Type conversions within an instance
13131      --  are not rechecked because type visbility may lead to spurious errors,
13132      --  but conversions in an actual for a formal object must be checked.
13133
13134      function Is_Discrim_Of_Bad_Access_Conversion_Argument
13135        (Expr : Node_Id) return Boolean;
13136      --  Implicit anonymous-to-named access type conversions are not allowed
13137      --  if the "statically deeper than" relationship does not apply to the
13138      --  type of the conversion operand. See RM 8.6(28.1) and AARM 8.6(28.d).
13139      --  We deal with most such cases elsewhere so that we can emit more
13140      --  specific error messages (e.g., if the operand is an access parameter
13141      --  or a saooaaat (stand-alone object of an anonymous access type)), but
13142      --  here is where we catch the case where the operand is an access
13143      --  discriminant selected from a dereference of another such "bad"
13144      --  conversion argument.
13145
13146      function Valid_Tagged_Conversion
13147        (Target_Type : Entity_Id;
13148         Opnd_Type   : Entity_Id) return Boolean;
13149      --  Specifically test for validity of tagged conversions
13150
13151      function Valid_Array_Conversion return Boolean;
13152      --  Check index and component conformance, and accessibility levels if
13153      --  the component types are anonymous access types (Ada 2005).
13154
13155      ----------------------
13156      -- Conversion_Check --
13157      ----------------------
13158
13159      function Conversion_Check
13160        (Valid : Boolean;
13161         Msg   : String) return Boolean
13162      is
13163      begin
13164         if not Valid
13165
13166            --  A generic unit has already been analyzed and we have verified
13167            --  that a particular conversion is OK in that context. Since the
13168            --  instance is reanalyzed without relying on the relationships
13169            --  established during the analysis of the generic, it is possible
13170            --  to end up with inconsistent views of private types. Do not emit
13171            --  the error message in such cases. The rest of the machinery in
13172            --  Valid_Conversion still ensures the proper compatibility of
13173            --  target and operand types.
13174
13175           and then not In_Instance_Code
13176         then
13177            Conversion_Error_N (Msg, Operand);
13178         end if;
13179
13180         return Valid;
13181      end Conversion_Check;
13182
13183      ------------------------
13184      -- Conversion_Error_N --
13185      ------------------------
13186
13187      procedure Conversion_Error_N (Msg : String; N : Node_Or_Entity_Id) is
13188      begin
13189         if Report_Errs then
13190            Error_Msg_N (Msg, N);
13191         end if;
13192      end Conversion_Error_N;
13193
13194      -------------------------
13195      -- Conversion_Error_NE --
13196      -------------------------
13197
13198      procedure Conversion_Error_NE
13199        (Msg : String;
13200         N   : Node_Or_Entity_Id;
13201         E   : Node_Or_Entity_Id)
13202      is
13203      begin
13204         if Report_Errs then
13205            Error_Msg_NE (Msg, N, E);
13206         end if;
13207      end Conversion_Error_NE;
13208
13209      ----------------------
13210      -- In_Instance_Code --
13211      ----------------------
13212
13213      function In_Instance_Code return Boolean is
13214         Par : Node_Id;
13215
13216      begin
13217         if not In_Instance then
13218            return False;
13219
13220         else
13221            Par := Parent (N);
13222            while Present (Par) loop
13223
13224               --  The expression is part of an actual object if it appears in
13225               --  the generated object declaration in the instance.
13226
13227               if Nkind (Par) = N_Object_Declaration
13228                 and then Present (Corresponding_Generic_Association (Par))
13229               then
13230                  return False;
13231
13232               else
13233                  exit when
13234                    Nkind (Par) in N_Statement_Other_Than_Procedure_Call
13235                      or else Nkind (Par) in N_Subprogram_Call
13236                      or else Nkind (Par) in N_Declaration;
13237               end if;
13238
13239               Par := Parent (Par);
13240            end loop;
13241
13242            --  Otherwise the expression appears within the instantiated unit
13243
13244            return True;
13245         end if;
13246      end In_Instance_Code;
13247
13248      --------------------------------------------------
13249      -- Is_Discrim_Of_Bad_Access_Conversion_Argument --
13250      --------------------------------------------------
13251
13252      function Is_Discrim_Of_Bad_Access_Conversion_Argument
13253        (Expr : Node_Id) return Boolean
13254      is
13255         Exp_Type : Entity_Id := Base_Type (Etype (Expr));
13256         pragma Assert (Is_Access_Type (Exp_Type));
13257
13258         Associated_Node : Node_Id;
13259         Deref_Prefix : Node_Id;
13260      begin
13261         if not Is_Anonymous_Access_Type (Exp_Type) then
13262            return False;
13263         end if;
13264
13265         pragma Assert (Is_Itype (Exp_Type));
13266         Associated_Node := Associated_Node_For_Itype (Exp_Type);
13267
13268         if Nkind (Associated_Node) /= N_Discriminant_Specification then
13269            return False; -- not the type of an access discriminant
13270         end if;
13271
13272         --  return False if Expr not of form <prefix>.all.Some_Component
13273
13274         if (Nkind (Expr) /= N_Selected_Component)
13275           or else (Nkind (Prefix (Expr)) /= N_Explicit_Dereference)
13276         then
13277            --  conditional expressions, declare expressions ???
13278            return False;
13279         end if;
13280
13281         Deref_Prefix := Prefix (Prefix (Expr));
13282         Exp_Type := Base_Type (Etype (Deref_Prefix));
13283
13284         --  The "statically deeper relationship" does not apply
13285         --  to generic formal access types, so a prefix of such
13286         --  a type is a "bad" prefix.
13287
13288         if Is_Generic_Formal (Exp_Type) then
13289            return True;
13290
13291         --  The "statically deeper relationship" does apply to
13292         --  any other named access type.
13293
13294         elsif not Is_Anonymous_Access_Type (Exp_Type) then
13295            return False;
13296         end if;
13297
13298         pragma Assert (Is_Itype (Exp_Type));
13299         Associated_Node := Associated_Node_For_Itype (Exp_Type);
13300
13301         --  The "statically deeper relationship" applies to some
13302         --  anonymous access types and not to others. Return
13303         --  True for the cases where it does not apply. Also check
13304         --  recursively for the
13305         --     <prefix>.all.Access_Discrim.all.Access_Discrim case,
13306         --  where the correct result depends on <prefix>.
13307
13308         return Nkind (Associated_Node) in
13309                  N_Procedure_Specification |  -- access parameter
13310                  N_Function_Specification  |  -- access parameter
13311                  N_Object_Declaration         -- saooaaat
13312           or else Is_Discrim_Of_Bad_Access_Conversion_Argument (Deref_Prefix);
13313      end Is_Discrim_Of_Bad_Access_Conversion_Argument;
13314
13315      ----------------------------
13316      -- Valid_Array_Conversion --
13317      ----------------------------
13318
13319      function Valid_Array_Conversion return Boolean is
13320         Opnd_Comp_Type : constant Entity_Id := Component_Type (Opnd_Type);
13321         Opnd_Comp_Base : constant Entity_Id := Base_Type (Opnd_Comp_Type);
13322
13323         Opnd_Index      : Node_Id;
13324         Opnd_Index_Type : Entity_Id;
13325
13326         Target_Comp_Type : constant Entity_Id :=
13327                              Component_Type (Target_Type);
13328         Target_Comp_Base : constant Entity_Id :=
13329                              Base_Type (Target_Comp_Type);
13330
13331         Target_Index      : Node_Id;
13332         Target_Index_Type : Entity_Id;
13333
13334      begin
13335         --  Error if wrong number of dimensions
13336
13337         if
13338           Number_Dimensions (Target_Type) /= Number_Dimensions (Opnd_Type)
13339         then
13340            Conversion_Error_N
13341              ("incompatible number of dimensions for conversion", Operand);
13342            return False;
13343
13344         --  Number of dimensions matches
13345
13346         else
13347            --  Loop through indexes of the two arrays
13348
13349            Target_Index := First_Index (Target_Type);
13350            Opnd_Index   := First_Index (Opnd_Type);
13351            while Present (Target_Index) and then Present (Opnd_Index) loop
13352               Target_Index_Type := Etype (Target_Index);
13353               Opnd_Index_Type   := Etype (Opnd_Index);
13354
13355               --  Error if index types are incompatible
13356
13357               if not (Is_Integer_Type (Target_Index_Type)
13358                       and then Is_Integer_Type (Opnd_Index_Type))
13359                 and then (Root_Type (Target_Index_Type)
13360                           /= Root_Type (Opnd_Index_Type))
13361               then
13362                  Conversion_Error_N
13363                    ("incompatible index types for array conversion",
13364                     Operand);
13365                  return False;
13366               end if;
13367
13368               Next_Index (Target_Index);
13369               Next_Index (Opnd_Index);
13370            end loop;
13371
13372            --  If component types have same base type, all set
13373
13374            if Target_Comp_Base  = Opnd_Comp_Base then
13375               null;
13376
13377               --  Here if base types of components are not the same. The only
13378               --  time this is allowed is if we have anonymous access types.
13379
13380               --  The conversion of arrays of anonymous access types can lead
13381               --  to dangling pointers. AI-392 formalizes the accessibility
13382               --  checks that must be applied to such conversions to prevent
13383               --  out-of-scope references.
13384
13385            elsif Ekind (Target_Comp_Base) in
13386                    E_Anonymous_Access_Type
13387                  | E_Anonymous_Access_Subprogram_Type
13388              and then Ekind (Opnd_Comp_Base) = Ekind (Target_Comp_Base)
13389              and then
13390                Subtypes_Statically_Match (Target_Comp_Type, Opnd_Comp_Type)
13391            then
13392               if Type_Access_Level (Target_Type) <
13393                    Deepest_Type_Access_Level (Opnd_Type)
13394               then
13395                  if In_Instance_Body then
13396                     Error_Msg_Warn := SPARK_Mode /= On;
13397                     Conversion_Error_N
13398                       ("source array type has deeper accessibility "
13399                        & "level than target<<", Operand);
13400                     Conversion_Error_N ("\Program_Error [<<", Operand);
13401                     Rewrite (N,
13402                       Make_Raise_Program_Error (Sloc (N),
13403                         Reason => PE_Accessibility_Check_Failed));
13404                     Set_Etype (N, Target_Type);
13405                     return False;
13406
13407                  --  Conversion not allowed because of accessibility levels
13408
13409                  else
13410                     Conversion_Error_N
13411                       ("source array type has deeper accessibility "
13412                        & "level than target", Operand);
13413                     return False;
13414                  end if;
13415
13416               else
13417                  null;
13418               end if;
13419
13420            --  All other cases where component base types do not match
13421
13422            else
13423               Conversion_Error_N
13424                 ("incompatible component types for array conversion",
13425                  Operand);
13426               return False;
13427            end if;
13428
13429            --  Check that component subtypes statically match. For numeric
13430            --  types this means that both must be either constrained or
13431            --  unconstrained. For enumeration types the bounds must match.
13432            --  All of this is checked in Subtypes_Statically_Match.
13433
13434            if not Subtypes_Statically_Match
13435                     (Target_Comp_Type, Opnd_Comp_Type)
13436            then
13437               Conversion_Error_N
13438                 ("component subtypes must statically match", Operand);
13439               return False;
13440            end if;
13441         end if;
13442
13443         return True;
13444      end Valid_Array_Conversion;
13445
13446      -----------------------------
13447      -- Valid_Tagged_Conversion --
13448      -----------------------------
13449
13450      function Valid_Tagged_Conversion
13451        (Target_Type : Entity_Id;
13452         Opnd_Type   : Entity_Id) return Boolean
13453      is
13454      begin
13455         --  Upward conversions are allowed (RM 4.6(22))
13456
13457         if Covers (Target_Type, Opnd_Type)
13458           or else Is_Ancestor (Target_Type, Opnd_Type)
13459         then
13460            return True;
13461
13462         --  Downward conversion are allowed if the operand is class-wide
13463         --  (RM 4.6(23)).
13464
13465         elsif Is_Class_Wide_Type (Opnd_Type)
13466           and then Covers (Opnd_Type, Target_Type)
13467         then
13468            return True;
13469
13470         elsif Covers (Opnd_Type, Target_Type)
13471           or else Is_Ancestor (Opnd_Type, Target_Type)
13472         then
13473            return
13474              Conversion_Check (False,
13475                "downward conversion of tagged objects not allowed");
13476
13477         --  Ada 2005 (AI-251): The conversion to/from interface types is
13478         --  always valid. The types involved may be class-wide (sub)types.
13479
13480         elsif Is_Interface (Etype (Base_Type (Target_Type)))
13481           or else Is_Interface (Etype (Base_Type (Opnd_Type)))
13482         then
13483            return True;
13484
13485         --  If the operand is a class-wide type obtained through a limited_
13486         --  with clause, and the context includes the nonlimited view, use
13487         --  it to determine whether the conversion is legal.
13488
13489         elsif Is_Class_Wide_Type (Opnd_Type)
13490           and then From_Limited_With (Opnd_Type)
13491           and then Present (Non_Limited_View (Etype (Opnd_Type)))
13492           and then Is_Interface (Non_Limited_View (Etype (Opnd_Type)))
13493         then
13494            return True;
13495
13496         elsif Is_Access_Type (Opnd_Type)
13497           and then Is_Interface (Directly_Designated_Type (Opnd_Type))
13498         then
13499            return True;
13500
13501         else
13502            Conversion_Error_NE
13503              ("invalid tagged conversion, not compatible with}",
13504               N, First_Subtype (Opnd_Type));
13505            return False;
13506         end if;
13507      end Valid_Tagged_Conversion;
13508
13509   --  Start of processing for Valid_Conversion
13510
13511   begin
13512      Check_Parameterless_Call (Operand);
13513
13514      if Is_Overloaded (Operand) then
13515         declare
13516            I   : Interp_Index;
13517            I1  : Interp_Index;
13518            It  : Interp;
13519            It1 : Interp;
13520            N1  : Entity_Id;
13521            T1  : Entity_Id;
13522
13523         begin
13524            --  Remove procedure calls, which syntactically cannot appear in
13525            --  this context, but which cannot be removed by type checking,
13526            --  because the context does not impose a type.
13527
13528            --  The node may be labelled overloaded, but still contain only one
13529            --  interpretation because others were discarded earlier. If this
13530            --  is the case, retain the single interpretation if legal.
13531
13532            Get_First_Interp (Operand, I, It);
13533            Opnd_Type := It.Typ;
13534            Get_Next_Interp (I, It);
13535
13536            if Present (It.Typ)
13537              and then Opnd_Type /= Standard_Void_Type
13538            then
13539               --  More than one candidate interpretation is available
13540
13541               Get_First_Interp (Operand, I, It);
13542               while Present (It.Typ) loop
13543                  if It.Typ = Standard_Void_Type then
13544                     Remove_Interp (I);
13545                  end if;
13546
13547                  --  When compiling for a system where Address is of a visible
13548                  --  integer type, spurious ambiguities can be produced when
13549                  --  arithmetic operations have a literal operand and return
13550                  --  System.Address or a descendant of it. These ambiguities
13551                  --  are usually resolved by the context, but for conversions
13552                  --  there is no context type and the removal of the spurious
13553                  --  operations must be done explicitly here.
13554
13555                  if not Address_Is_Private
13556                    and then Is_Descendant_Of_Address (It.Typ)
13557                  then
13558                     Remove_Interp (I);
13559                  end if;
13560
13561                  Get_Next_Interp (I, It);
13562               end loop;
13563            end if;
13564
13565            Get_First_Interp (Operand, I, It);
13566            I1  := I;
13567            It1 := It;
13568
13569            if No (It.Typ) then
13570               Conversion_Error_N ("illegal operand in conversion", Operand);
13571               return False;
13572            end if;
13573
13574            Get_Next_Interp (I, It);
13575
13576            if Present (It.Typ) then
13577               N1  := It1.Nam;
13578               T1  := It1.Typ;
13579               It1 := Disambiguate (Operand, I1, I, Any_Type);
13580
13581               if It1 = No_Interp then
13582                  Conversion_Error_N
13583                    ("ambiguous operand in conversion", Operand);
13584
13585                  --  If the interpretation involves a standard operator, use
13586                  --  the location of the type, which may be user-defined.
13587
13588                  if Sloc (It.Nam) = Standard_Location then
13589                     Error_Msg_Sloc := Sloc (It.Typ);
13590                  else
13591                     Error_Msg_Sloc := Sloc (It.Nam);
13592                  end if;
13593
13594                  Conversion_Error_N -- CODEFIX
13595                    ("\\possible interpretation#!", Operand);
13596
13597                  if Sloc (N1) = Standard_Location then
13598                     Error_Msg_Sloc := Sloc (T1);
13599                  else
13600                     Error_Msg_Sloc := Sloc (N1);
13601                  end if;
13602
13603                  Conversion_Error_N -- CODEFIX
13604                    ("\\possible interpretation#!", Operand);
13605
13606                  return False;
13607               end if;
13608            end if;
13609
13610            Set_Etype (Operand, It1.Typ);
13611            Opnd_Type := It1.Typ;
13612         end;
13613      end if;
13614
13615      --  Deal with conversion of integer type to address if the pragma
13616      --  Allow_Integer_Address is in effect. We convert the conversion to
13617      --  an unchecked conversion in this case and we are all done.
13618
13619      if Address_Integer_Convert_OK (Opnd_Type, Target_Type) then
13620         Rewrite (N, Unchecked_Convert_To (Target_Type, Expression (N)));
13621         Analyze_And_Resolve (N, Target_Type);
13622         return True;
13623      end if;
13624
13625      --  If we are within a child unit, check whether the type of the
13626      --  expression has an ancestor in a parent unit, in which case it
13627      --  belongs to its derivation class even if the ancestor is private.
13628      --  See RM 7.3.1 (5.2/3).
13629
13630      Inc_Ancestor := Get_Incomplete_View_Of_Ancestor (Opnd_Type);
13631
13632      --  Numeric types
13633
13634      if Is_Numeric_Type (Target_Type) then
13635
13636         --  A universal fixed expression can be converted to any numeric type
13637
13638         if Opnd_Type = Universal_Fixed then
13639            return True;
13640
13641         --  Also no need to check when in an instance or inlined body, because
13642         --  the legality has been established when the template was analyzed.
13643         --  Furthermore, numeric conversions may occur where only a private
13644         --  view of the operand type is visible at the instantiation point.
13645         --  This results in a spurious error if we check that the operand type
13646         --  is a numeric type.
13647
13648         --  Note: in a previous version of this unit, the following tests were
13649         --  applied only for generated code (Comes_From_Source set to False),
13650         --  but in fact the test is required for source code as well, since
13651         --  this situation can arise in source code.
13652
13653         elsif In_Instance_Code or else In_Inlined_Body then
13654            return True;
13655
13656         --  Otherwise we need the conversion check
13657
13658         else
13659            return Conversion_Check
13660                     (Is_Numeric_Type (Opnd_Type)
13661                       or else
13662                         (Present (Inc_Ancestor)
13663                           and then Is_Numeric_Type (Inc_Ancestor)),
13664                      "illegal operand for numeric conversion");
13665         end if;
13666
13667      --  Array types
13668
13669      elsif Is_Array_Type (Target_Type) then
13670         if not Is_Array_Type (Opnd_Type)
13671           or else Opnd_Type = Any_Composite
13672           or else Opnd_Type = Any_String
13673         then
13674            Conversion_Error_N
13675              ("illegal operand for array conversion", Operand);
13676            return False;
13677
13678         else
13679            return Valid_Array_Conversion;
13680         end if;
13681
13682      --  Ada 2005 (AI-251): Internally generated conversions of access to
13683      --  interface types added to force the displacement of the pointer to
13684      --  reference the corresponding dispatch table.
13685
13686      elsif not Comes_From_Source (N)
13687         and then Is_Access_Type (Target_Type)
13688         and then Is_Interface (Designated_Type (Target_Type))
13689      then
13690         return True;
13691
13692      --  Ada 2005 (AI-251): Anonymous access types where target references an
13693      --  interface type.
13694
13695      elsif Is_Access_Type (Opnd_Type)
13696        and then Ekind (Target_Type) in
13697                   E_General_Access_Type | E_Anonymous_Access_Type
13698        and then Is_Interface (Directly_Designated_Type (Target_Type))
13699      then
13700         --  Check the static accessibility rule of 4.6(17). Note that the
13701         --  check is not enforced when within an instance body, since the
13702         --  RM requires such cases to be caught at run time.
13703
13704         --  If the operand is a rewriting of an allocator no check is needed
13705         --  because there are no accessibility issues.
13706
13707         if Nkind (Original_Node (N)) = N_Allocator then
13708            null;
13709
13710         elsif Ekind (Target_Type) /= E_Anonymous_Access_Type then
13711            if Type_Access_Level (Opnd_Type) >
13712               Deepest_Type_Access_Level (Target_Type)
13713            then
13714               --  In an instance, this is a run-time check, but one we know
13715               --  will fail, so generate an appropriate warning. The raise
13716               --  will be generated by Expand_N_Type_Conversion.
13717
13718               if In_Instance_Body then
13719                  Error_Msg_Warn := SPARK_Mode /= On;
13720                  Conversion_Error_N
13721                    ("cannot convert local pointer to non-local access type<<",
13722                     Operand);
13723                  Conversion_Error_N ("\Program_Error [<<", Operand);
13724
13725               else
13726                  Conversion_Error_N
13727                    ("cannot convert local pointer to non-local access type",
13728                     Operand);
13729                  return False;
13730               end if;
13731
13732            --  Special accessibility checks are needed in the case of access
13733            --  discriminants declared for a limited type.
13734
13735            elsif Ekind (Opnd_Type) = E_Anonymous_Access_Type
13736              and then not Is_Local_Anonymous_Access (Opnd_Type)
13737            then
13738               --  When the operand is a selected access discriminant the check
13739               --  needs to be made against the level of the object denoted by
13740               --  the prefix of the selected name (Accessibility_Level handles
13741               --  checking the prefix of the operand for this case).
13742
13743               if Nkind (Operand) = N_Selected_Component
13744                 and then Static_Accessibility_Level
13745                            (Operand, Zero_On_Dynamic_Level)
13746                              > Deepest_Type_Access_Level (Target_Type)
13747               then
13748                  --  In an instance, this is a run-time check, but one we know
13749                  --  will fail, so generate an appropriate warning. The raise
13750                  --  will be generated by Expand_N_Type_Conversion.
13751
13752                  if In_Instance_Body then
13753                     Error_Msg_Warn := SPARK_Mode /= On;
13754                     Conversion_Error_N
13755                       ("cannot convert access discriminant to non-local "
13756                        & "access type<<", Operand);
13757                     Conversion_Error_N ("\Program_Error [<<", Operand);
13758
13759                  --  Real error if not in instance body
13760
13761                  else
13762                     Conversion_Error_N
13763                       ("cannot convert access discriminant to non-local "
13764                        & "access type", Operand);
13765                     return False;
13766                  end if;
13767               end if;
13768
13769               --  The case of a reference to an access discriminant from
13770               --  within a limited type declaration (which will appear as
13771               --  a discriminal) is always illegal because the level of the
13772               --  discriminant is considered to be deeper than any (nameable)
13773               --  access type.
13774
13775               if Is_Entity_Name (Operand)
13776                 and then not Is_Local_Anonymous_Access (Opnd_Type)
13777                 and then
13778                   Ekind (Entity (Operand)) in E_In_Parameter | E_Constant
13779                 and then Present (Discriminal_Link (Entity (Operand)))
13780               then
13781                  Conversion_Error_N
13782                    ("discriminant has deeper accessibility level than target",
13783                     Operand);
13784                  return False;
13785               end if;
13786            end if;
13787         end if;
13788
13789         return True;
13790
13791      --  General and anonymous access types
13792
13793      elsif Ekind (Target_Type) in
13794              E_General_Access_Type | E_Anonymous_Access_Type
13795          and then
13796            Conversion_Check
13797              (Is_Access_Type (Opnd_Type)
13798                and then
13799                  Ekind (Opnd_Type) not in
13800                    E_Access_Subprogram_Type |
13801                    E_Access_Protected_Subprogram_Type,
13802               "must be an access-to-object type")
13803      then
13804         if Is_Access_Constant (Opnd_Type)
13805           and then not Is_Access_Constant (Target_Type)
13806         then
13807            Conversion_Error_N
13808              ("access-to-constant operand type not allowed", Operand);
13809            return False;
13810         end if;
13811
13812         --  Check the static accessibility rule of 4.6(17). Note that the
13813         --  check is not enforced when within an instance body, since the RM
13814         --  requires such cases to be caught at run time.
13815
13816         if Ekind (Target_Type) /= E_Anonymous_Access_Type
13817           or else Is_Local_Anonymous_Access (Target_Type)
13818           or else Nkind (Associated_Node_For_Itype (Target_Type)) =
13819                     N_Object_Declaration
13820         then
13821            --  Ada 2012 (AI05-0149): Perform legality checking on implicit
13822            --  conversions from an anonymous access type to a named general
13823            --  access type. Such conversions are not allowed in the case of
13824            --  access parameters and stand-alone objects of an anonymous
13825            --  access type. The implicit conversion case is recognized by
13826            --  testing that Comes_From_Source is False and that it's been
13827            --  rewritten. The Comes_From_Source test isn't sufficient because
13828            --  nodes in inlined calls to predefined library routines can have
13829            --  Comes_From_Source set to False. (Is there a better way to test
13830            --  for implicit conversions???).
13831            --
13832            --  Do not treat a rewritten 'Old attribute reference like other
13833            --  rewrite substitutions. This makes a difference, for example,
13834            --  in the case where we are generating the expansion of a
13835            --  membership test of the form
13836            --     Saooaaat'Old in Named_Access_Type
13837            --  because in this case Valid_Conversion needs to return True
13838            --  (otherwise the expansion will be False - see the call site
13839            --  in exp_ch4.adb).
13840
13841            if Ada_Version >= Ada_2012
13842              and then not Comes_From_Source (N)
13843              and then Is_Rewrite_Substitution (N)
13844              and then not Is_Attribute_Old (Original_Node (N))
13845              and then Ekind (Base_Type (Target_Type)) = E_General_Access_Type
13846              and then Ekind (Opnd_Type) = E_Anonymous_Access_Type
13847            then
13848               if Is_Itype (Opnd_Type) then
13849
13850                  --  When applying restriction No_Dynamic_Accessibility_Check,
13851                  --  implicit conversions are allowed when the operand type is
13852                  --  not deeper than the target type.
13853
13854                  if No_Dynamic_Accessibility_Checks_Enabled (N) then
13855                     if Type_Access_Level (Opnd_Type)
13856                          > Deepest_Type_Access_Level (Target_Type)
13857                     then
13858                        Conversion_Error_N
13859                          ("operand has deeper level than target", Operand);
13860                     end if;
13861
13862                  --  Implicit conversions aren't allowed for objects of an
13863                  --  anonymous access type, since such objects have nonstatic
13864                  --  levels in Ada 2012.
13865
13866                  elsif Nkind (Associated_Node_For_Itype (Opnd_Type))
13867                          = N_Object_Declaration
13868                  then
13869                     Conversion_Error_N
13870                       ("implicit conversion of stand-alone anonymous "
13871                        & "access object not allowed", Operand);
13872                     return False;
13873
13874                  --  Implicit conversions aren't allowed for anonymous access
13875                  --  parameters. We exclude anonymous access results as well
13876                  --  as universal_access "=".
13877
13878                  elsif not Is_Local_Anonymous_Access (Opnd_Type)
13879                    and then Nkind (Associated_Node_For_Itype (Opnd_Type)) in
13880                               N_Function_Specification |
13881                               N_Procedure_Specification
13882                    and then Nkind (Parent (N)) not in N_Op_Eq | N_Op_Ne
13883                  then
13884                     Conversion_Error_N
13885                       ("implicit conversion of anonymous access parameter "
13886                        & "not allowed", Operand);
13887                     return False;
13888
13889                  --  Detect access discriminant values that are illegal
13890                  --  implicit anonymous-to-named access conversion operands.
13891
13892                  elsif Is_Discrim_Of_Bad_Access_Conversion_Argument (Operand)
13893                  then
13894                     Conversion_Error_N
13895                       ("implicit conversion of anonymous access value "
13896                        & "not allowed", Operand);
13897                     return False;
13898
13899                  --  In other cases, the level of the operand's type must be
13900                  --  statically less deep than that of the target type, else
13901                  --  implicit conversion is disallowed (by RM12-8.6(27.1/3)).
13902
13903                  elsif Type_Access_Level (Opnd_Type) >
13904                    Deepest_Type_Access_Level (Target_Type)
13905                  then
13906                     Conversion_Error_N
13907                       ("implicit conversion of anonymous access value "
13908                        & "violates accessibility", Operand);
13909                     return False;
13910                  end if;
13911               end if;
13912
13913            --  Check if the operand is deeper than the target type, taking
13914            --  care to avoid the case where we are converting a result of a
13915            --  function returning an anonymous access type since the "master
13916            --  of the call" would be target type of the conversion unless
13917            --  the target type is anonymous access as well - see RM 3.10.2
13918            --  (10.3/3).
13919
13920            --  Note that when the restriction No_Dynamic_Accessibility_Checks
13921            --  is in effect wei also want to proceed with the conversion check
13922            --  described above.
13923
13924            elsif Type_Access_Level (Opnd_Type, Assoc_Ent => Operand)
13925                    > Deepest_Type_Access_Level (Target_Type)
13926              and then (Nkind (Associated_Node_For_Itype (Opnd_Type))
13927                          /= N_Function_Specification
13928                        or else Ekind (Target_Type) in Anonymous_Access_Kind
13929                        or else No_Dynamic_Accessibility_Checks_Enabled (N))
13930
13931              --  Check we are not in a return value ???
13932
13933              and then (not In_Return_Value (N)
13934                         or else
13935                           Nkind (Associated_Node_For_Itype (Target_Type))
13936                             = N_Component_Declaration)
13937            then
13938               --  In an instance, this is a run-time check, but one we know
13939               --  will fail, so generate an appropriate warning. The raise
13940               --  will be generated by Expand_N_Type_Conversion.
13941
13942               if In_Instance_Body then
13943                  Error_Msg_Warn := SPARK_Mode /= On;
13944                  Conversion_Error_N
13945                    ("cannot convert local pointer to non-local access type<<",
13946                     Operand);
13947                  Conversion_Error_N ("\Program_Error [<<", Operand);
13948
13949               --  If not in an instance body, this is a real error
13950
13951               else
13952                  --  Avoid generation of spurious error message
13953
13954                  if not Error_Posted (N) then
13955                     Conversion_Error_N
13956                      ("cannot convert local pointer to non-local access type",
13957                       Operand);
13958                  end if;
13959
13960                  return False;
13961               end if;
13962
13963            --  Special accessibility checks are needed in the case of access
13964            --  discriminants declared for a limited type.
13965
13966            elsif Ekind (Opnd_Type) = E_Anonymous_Access_Type
13967              and then not Is_Local_Anonymous_Access (Opnd_Type)
13968            then
13969               --  When the operand is a selected access discriminant the check
13970               --  needs to be made against the level of the object denoted by
13971               --  the prefix of the selected name (Accessibility_Level handles
13972               --  checking the prefix of the operand for this case).
13973
13974               if Nkind (Operand) = N_Selected_Component
13975                 and then Static_Accessibility_Level
13976                            (Operand, Zero_On_Dynamic_Level)
13977                              > Deepest_Type_Access_Level (Target_Type)
13978               then
13979                  --  In an instance, this is a run-time check, but one we know
13980                  --  will fail, so generate an appropriate warning. The raise
13981                  --  will be generated by Expand_N_Type_Conversion.
13982
13983                  if In_Instance_Body then
13984                     Error_Msg_Warn := SPARK_Mode /= On;
13985                     Conversion_Error_N
13986                       ("cannot convert access discriminant to non-local "
13987                        & "access type<<", Operand);
13988                     Conversion_Error_N ("\Program_Error [<<", Operand);
13989
13990                  --  If not in an instance body, this is a real error
13991
13992                  else
13993                     Conversion_Error_N
13994                       ("cannot convert access discriminant to non-local "
13995                        & "access type", Operand);
13996                     return False;
13997                  end if;
13998               end if;
13999
14000               --  The case of a reference to an access discriminant from
14001               --  within a limited type declaration (which will appear as
14002               --  a discriminal) is always illegal because the level of the
14003               --  discriminant is considered to be deeper than any (nameable)
14004               --  access type.
14005
14006               if Is_Entity_Name (Operand)
14007                 and then
14008                   Ekind (Entity (Operand)) in E_In_Parameter | E_Constant
14009                 and then Present (Discriminal_Link (Entity (Operand)))
14010               then
14011                  Conversion_Error_N
14012                    ("discriminant has deeper accessibility level than target",
14013                     Operand);
14014                  return False;
14015               end if;
14016            end if;
14017         end if;
14018
14019         --  In the presence of limited_with clauses we have to use nonlimited
14020         --  views, if available.
14021
14022         Check_Limited : declare
14023            function Full_Designated_Type (T : Entity_Id) return Entity_Id;
14024            --  Helper function to handle limited views
14025
14026            --------------------------
14027            -- Full_Designated_Type --
14028            --------------------------
14029
14030            function Full_Designated_Type (T : Entity_Id) return Entity_Id is
14031               Desig : constant Entity_Id := Designated_Type (T);
14032
14033            begin
14034               --  Handle the limited view of a type
14035
14036               if From_Limited_With (Desig)
14037                 and then Has_Non_Limited_View (Desig)
14038               then
14039                  return Available_View (Desig);
14040               else
14041                  return Desig;
14042               end if;
14043            end Full_Designated_Type;
14044
14045            --  Local Declarations
14046
14047            Target : constant Entity_Id := Full_Designated_Type (Target_Type);
14048            Opnd   : constant Entity_Id := Full_Designated_Type (Opnd_Type);
14049
14050            Same_Base : constant Boolean :=
14051                          Base_Type (Target) = Base_Type (Opnd);
14052
14053         --  Start of processing for Check_Limited
14054
14055         begin
14056            if Is_Tagged_Type (Target) then
14057               return Valid_Tagged_Conversion (Target, Opnd);
14058
14059            else
14060               if not Same_Base then
14061                  Conversion_Error_NE
14062                    ("target designated type not compatible with }",
14063                     N, Base_Type (Opnd));
14064                  return False;
14065
14066               --  Ada 2005 AI-384: legality rule is symmetric in both
14067               --  designated types. The conversion is legal (with possible
14068               --  constraint check) if either designated type is
14069               --  unconstrained.
14070
14071               elsif Subtypes_Statically_Match (Target, Opnd)
14072                 or else
14073                   (Has_Discriminants (Target)
14074                     and then
14075                      (not Is_Constrained (Opnd)
14076                        or else not Is_Constrained (Target)))
14077               then
14078                  --  Special case, if Value_Size has been used to make the
14079                  --  sizes different, the conversion is not allowed even
14080                  --  though the subtypes statically match.
14081
14082                  if Known_Static_RM_Size (Target)
14083                    and then Known_Static_RM_Size (Opnd)
14084                    and then RM_Size (Target) /= RM_Size (Opnd)
14085                  then
14086                     Conversion_Error_NE
14087                       ("target designated subtype not compatible with }",
14088                        N, Opnd);
14089                     Conversion_Error_NE
14090                       ("\because sizes of the two designated subtypes differ",
14091                        N, Opnd);
14092                     return False;
14093
14094                  --  Normal case where conversion is allowed
14095
14096                  else
14097                     return True;
14098                  end if;
14099
14100               else
14101                  Error_Msg_NE
14102                    ("target designated subtype not compatible with }",
14103                     N, Opnd);
14104                  return False;
14105               end if;
14106            end if;
14107         end Check_Limited;
14108
14109      --  Access to subprogram types. If the operand is an access parameter,
14110      --  the type has a deeper accessibility that any master, and cannot be
14111      --  assigned. We must make an exception if the conversion is part of an
14112      --  assignment and the target is the return object of an extended return
14113      --  statement, because in that case the accessibility check takes place
14114      --  after the return.
14115
14116      elsif Is_Access_Subprogram_Type (Target_Type)
14117
14118        --  Note: this test of Opnd_Type is there to prevent entering this
14119        --  branch in the case of a remote access to subprogram type, which
14120        --  is internally represented as an E_Record_Type.
14121
14122        and then Is_Access_Type (Opnd_Type)
14123      then
14124         if Ekind (Base_Type (Opnd_Type)) = E_Anonymous_Access_Subprogram_Type
14125           and then Is_Entity_Name (Operand)
14126           and then Ekind (Entity (Operand)) = E_In_Parameter
14127           and then
14128             (Nkind (Parent (N)) /= N_Assignment_Statement
14129               or else not Is_Entity_Name (Name (Parent (N)))
14130               or else not Is_Return_Object (Entity (Name (Parent (N)))))
14131         then
14132            Conversion_Error_N
14133              ("illegal attempt to store anonymous access to subprogram",
14134               Operand);
14135            Conversion_Error_N
14136              ("\value has deeper accessibility than any master "
14137               & "(RM 3.10.2 (13))",
14138               Operand);
14139
14140            Error_Msg_NE
14141             ("\use named access type for& instead of access parameter",
14142               Operand, Entity (Operand));
14143         end if;
14144
14145         --  Check that the designated types are subtype conformant
14146
14147         Check_Subtype_Conformant (New_Id  => Designated_Type (Target_Type),
14148                                   Old_Id  => Designated_Type (Opnd_Type),
14149                                   Err_Loc => N);
14150
14151         --  Check the static accessibility rule of 4.6(20)
14152
14153         if Type_Access_Level (Opnd_Type) >
14154            Deepest_Type_Access_Level (Target_Type)
14155         then
14156            Conversion_Error_N
14157              ("operand type has deeper accessibility level than target",
14158               Operand);
14159
14160         --  Check that if the operand type is declared in a generic body,
14161         --  then the target type must be declared within that same body
14162         --  (enforces last sentence of 4.6(20)).
14163
14164         elsif Present (Enclosing_Generic_Body (Opnd_Type)) then
14165            declare
14166               O_Gen : constant Node_Id :=
14167                         Enclosing_Generic_Body (Opnd_Type);
14168
14169               T_Gen : Node_Id;
14170
14171            begin
14172               T_Gen := Enclosing_Generic_Body (Target_Type);
14173               while Present (T_Gen) and then T_Gen /= O_Gen loop
14174                  T_Gen := Enclosing_Generic_Body (T_Gen);
14175               end loop;
14176
14177               if T_Gen /= O_Gen then
14178                  Conversion_Error_N
14179                    ("target type must be declared in same generic body "
14180                     & "as operand type", N);
14181               end if;
14182            end;
14183         end if;
14184
14185         --  Check that the strub modes are compatible.
14186         --  We wish to reject explicit conversions only for
14187         --  incompatible modes.
14188
14189         return Conversion_Check
14190                  (Compatible_Strub_Modes
14191                     (Designated_Type (Target_Type),
14192                      Designated_Type (Opnd_Type)),
14193                   "incompatible `strub` modes");
14194
14195      --  Remote access to subprogram types
14196
14197      elsif Is_Remote_Access_To_Subprogram_Type (Target_Type)
14198        and then Is_Remote_Access_To_Subprogram_Type (Opnd_Type)
14199      then
14200         --  It is valid to convert from one RAS type to another provided
14201         --  that their specification statically match.
14202
14203         --  Note: at this point, remote access to subprogram types have been
14204         --  expanded to their E_Record_Type representation, and we need to
14205         --  go back to the original access type definition using the
14206         --  Corresponding_Remote_Type attribute in order to check that the
14207         --  designated profiles match.
14208
14209         pragma Assert (Ekind (Target_Type) = E_Record_Type);
14210         pragma Assert (Ekind (Opnd_Type) = E_Record_Type);
14211
14212         Check_Subtype_Conformant
14213           (New_Id  =>
14214              Designated_Type (Corresponding_Remote_Type (Target_Type)),
14215            Old_Id  =>
14216              Designated_Type (Corresponding_Remote_Type (Opnd_Type)),
14217            Err_Loc =>
14218              N);
14219
14220         --  Check that the strub modes are compatible.
14221         --  We wish to reject explicit conversions only for
14222         --  incompatible modes.
14223
14224         return Conversion_Check
14225                  (Compatible_Strub_Modes
14226                     (Designated_Type (Target_Type),
14227                      Designated_Type (Opnd_Type)),
14228                   "incompatible `strub` modes");
14229
14230      --  If it was legal in the generic, it's legal in the instance
14231
14232      elsif In_Instance_Body then
14233         return True;
14234
14235      --  If both are tagged types, check legality of view conversions
14236
14237      elsif Is_Tagged_Type (Target_Type)
14238              and then
14239            Is_Tagged_Type (Opnd_Type)
14240      then
14241         return Valid_Tagged_Conversion (Target_Type, Opnd_Type);
14242
14243      --  Types derived from the same root type are convertible
14244
14245      elsif Root_Type (Target_Type) = Root_Type (Opnd_Type) then
14246         return True;
14247
14248      --  In an instance or an inlined body, there may be inconsistent views of
14249      --  the same type, or of types derived from a common root.
14250
14251      elsif (In_Instance or In_Inlined_Body)
14252        and then
14253          Root_Type (Underlying_Type (Target_Type)) =
14254          Root_Type (Underlying_Type (Opnd_Type))
14255      then
14256         return True;
14257
14258      --  Special check for common access type error case
14259
14260      elsif Ekind (Target_Type) = E_Access_Type
14261         and then Is_Access_Type (Opnd_Type)
14262      then
14263         Conversion_Error_N ("target type must be general access type!", N);
14264         Conversion_Error_NE -- CODEFIX
14265            ("\add ALL to }!", N, Target_Type);
14266         return False;
14267
14268      --  Here we have a real conversion error
14269
14270      else
14271         --  Check for missing regular with_clause when only a limited view of
14272         --  target is available.
14273
14274         if From_Limited_With (Opnd_Type) and then In_Package_Body then
14275            Conversion_Error_NE
14276              ("invalid conversion, not compatible with limited view of }",
14277               N, Opnd_Type);
14278            Conversion_Error_NE
14279              ("\add with_clause for& to current unit!", N, Scope (Opnd_Type));
14280
14281         elsif Is_Access_Type (Opnd_Type)
14282           and then From_Limited_With (Designated_Type (Opnd_Type))
14283           and then In_Package_Body
14284         then
14285            Conversion_Error_NE
14286              ("invalid conversion, not compatible with }", N, Opnd_Type);
14287            Conversion_Error_NE
14288              ("\add with_clause for& to current unit!",
14289               N, Scope (Designated_Type (Opnd_Type)));
14290
14291         else
14292            Conversion_Error_NE
14293              ("invalid conversion, not compatible with }", N, Opnd_Type);
14294         end if;
14295
14296         return False;
14297      end if;
14298   end Valid_Conversion;
14299
14300end Sem_Res;
14301