OSDN Git Service

2007-09-26 Thomas Quinot <quinot@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / checks.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                               C H E C K S                                --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2007, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Debug;    use Debug;
28 with Einfo;    use Einfo;
29 with Errout;   use Errout;
30 with Exp_Ch2;  use Exp_Ch2;
31 with Exp_Ch11; use Exp_Ch11;
32 with Exp_Pakd; use Exp_Pakd;
33 with Exp_Util; use Exp_Util;
34 with Elists;   use Elists;
35 with Eval_Fat; use Eval_Fat;
36 with Freeze;   use Freeze;
37 with Lib;      use Lib;
38 with Nlists;   use Nlists;
39 with Nmake;    use Nmake;
40 with Opt;      use Opt;
41 with Output;   use Output;
42 with Restrict; use Restrict;
43 with Rident;   use Rident;
44 with Rtsfind;  use Rtsfind;
45 with Sem;      use Sem;
46 with Sem_Eval; use Sem_Eval;
47 with Sem_Ch3;  use Sem_Ch3;
48 with Sem_Ch8;  use Sem_Ch8;
49 with Sem_Res;  use Sem_Res;
50 with Sem_Util; use Sem_Util;
51 with Sem_Warn; use Sem_Warn;
52 with Sinfo;    use Sinfo;
53 with Sinput;   use Sinput;
54 with Snames;   use Snames;
55 with Sprint;   use Sprint;
56 with Stand;    use Stand;
57 with Targparm; use Targparm;
58 with Tbuild;   use Tbuild;
59 with Ttypes;   use Ttypes;
60 with Urealp;   use Urealp;
61 with Validsw;  use Validsw;
62
63 package body Checks is
64
65    --  General note: many of these routines are concerned with generating
66    --  checking code to make sure that constraint error is raised at runtime.
67    --  Clearly this code is only needed if the expander is active, since
68    --  otherwise we will not be generating code or going into the runtime
69    --  execution anyway.
70
71    --  We therefore disconnect most of these checks if the expander is
72    --  inactive. This has the additional benefit that we do not need to
73    --  worry about the tree being messed up by previous errors (since errors
74    --  turn off expansion anyway).
75
76    --  There are a few exceptions to the above rule. For instance routines
77    --  such as Apply_Scalar_Range_Check that do not insert any code can be
78    --  safely called even when the Expander is inactive (but Errors_Detected
79    --  is 0). The benefit of executing this code when expansion is off, is
80    --  the ability to emit constraint error warning for static expressions
81    --  even when we are not generating code.
82
83    -------------------------------------
84    -- Suppression of Redundant Checks --
85    -------------------------------------
86
87    --  This unit implements a limited circuit for removal of redundant
88    --  checks. The processing is based on a tracing of simple sequential
89    --  flow. For any sequence of statements, we save expressions that are
90    --  marked to be checked, and then if the same expression appears later
91    --  with the same check, then under certain circumstances, the second
92    --  check can be suppressed.
93
94    --  Basically, we can suppress the check if we know for certain that
95    --  the previous expression has been elaborated (together with its
96    --  check), and we know that the exception frame is the same, and that
97    --  nothing has happened to change the result of the exception.
98
99    --  Let us examine each of these three conditions in turn to describe
100    --  how we ensure that this condition is met.
101
102    --  First, we need to know for certain that the previous expression has
103    --  been executed. This is done principly by the mechanism of calling
104    --  Conditional_Statements_Begin at the start of any statement sequence
105    --  and Conditional_Statements_End at the end. The End call causes all
106    --  checks remembered since the Begin call to be discarded. This does
107    --  miss a few cases, notably the case of a nested BEGIN-END block with
108    --  no exception handlers. But the important thing is to be conservative.
109    --  The other protection is that all checks are discarded if a label
110    --  is encountered, since then the assumption of sequential execution
111    --  is violated, and we don't know enough about the flow.
112
113    --  Second, we need to know that the exception frame is the same. We
114    --  do this by killing all remembered checks when we enter a new frame.
115    --  Again, that's over-conservative, but generally the cases we can help
116    --  with are pretty local anyway (like the body of a loop for example).
117
118    --  Third, we must be sure to forget any checks which are no longer valid.
119    --  This is done by two mechanisms, first the Kill_Checks_Variable call is
120    --  used to note any changes to local variables. We only attempt to deal
121    --  with checks involving local variables, so we do not need to worry
122    --  about global variables. Second, a call to any non-global procedure
123    --  causes us to abandon all stored checks, since such a all may affect
124    --  the values of any local variables.
125
126    --  The following define the data structures used to deal with remembering
127    --  checks so that redundant checks can be eliminated as described above.
128
129    --  Right now, the only expressions that we deal with are of the form of
130    --  simple local objects (either declared locally, or IN parameters) or
131    --  such objects plus/minus a compile time known constant. We can do
132    --  more later on if it seems worthwhile, but this catches many simple
133    --  cases in practice.
134
135    --  The following record type reflects a single saved check. An entry
136    --  is made in the stack of saved checks if and only if the expression
137    --  has been elaborated with the indicated checks.
138
139    type Saved_Check is record
140       Killed : Boolean;
141       --  Set True if entry is killed by Kill_Checks
142
143       Entity : Entity_Id;
144       --  The entity involved in the expression that is checked
145
146       Offset : Uint;
147       --  A compile time value indicating the result of adding or
148       --  subtracting a compile time value. This value is to be
149       --  added to the value of the Entity. A value of zero is
150       --  used for the case of a simple entity reference.
151
152       Check_Type : Character;
153       --  This is set to 'R' for a range check (in which case Target_Type
154       --  is set to the target type for the range check) or to 'O' for an
155       --  overflow check (in which case Target_Type is set to Empty).
156
157       Target_Type : Entity_Id;
158       --  Used only if Do_Range_Check is set. Records the target type for
159       --  the check. We need this, because a check is a duplicate only if
160       --  it has a the same target type (or more accurately one with a
161       --  range that is smaller or equal to the stored target type of a
162       --  saved check).
163    end record;
164
165    --  The following table keeps track of saved checks. Rather than use an
166    --  extensible table. We just use a table of fixed size, and we discard
167    --  any saved checks that do not fit. That's very unlikely to happen and
168    --  this is only an optimization in any case.
169
170    Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
171    --  Array of saved checks
172
173    Num_Saved_Checks : Nat := 0;
174    --  Number of saved checks
175
176    --  The following stack keeps track of statement ranges. It is treated
177    --  as a stack. When Conditional_Statements_Begin is called, an entry
178    --  is pushed onto this stack containing the value of Num_Saved_Checks
179    --  at the time of the call. Then when Conditional_Statements_End is
180    --  called, this value is popped off and used to reset Num_Saved_Checks.
181
182    --  Note: again, this is a fixed length stack with a size that should
183    --  always be fine. If the value of the stack pointer goes above the
184    --  limit, then we just forget all saved checks.
185
186    Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
187    Saved_Checks_TOS : Nat := 0;
188
189    -----------------------
190    -- Local Subprograms --
191    -----------------------
192
193    procedure Apply_Float_Conversion_Check
194      (Ck_Node    : Node_Id;
195       Target_Typ : Entity_Id);
196    --  The checks on a conversion from a floating-point type to an integer
197    --  type are delicate. They have to be performed before conversion, they
198    --  have to raise an exception when the operand is a NaN, and rounding must
199    --  be taken into account to determine the safe bounds of the operand.
200
201    procedure Apply_Selected_Length_Checks
202      (Ck_Node    : Node_Id;
203       Target_Typ : Entity_Id;
204       Source_Typ : Entity_Id;
205       Do_Static  : Boolean);
206    --  This is the subprogram that does all the work for Apply_Length_Check
207    --  and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
208    --  described for the above routines. The Do_Static flag indicates that
209    --  only a static check is to be done.
210
211    procedure Apply_Selected_Range_Checks
212      (Ck_Node    : Node_Id;
213       Target_Typ : Entity_Id;
214       Source_Typ : Entity_Id;
215       Do_Static  : Boolean);
216    --  This is the subprogram that does all the work for Apply_Range_Check.
217    --  Expr, Target_Typ and Source_Typ are as described for the above
218    --  routine. The Do_Static flag indicates that only a static check is
219    --  to be done.
220
221    type Check_Type is new Check_Id range Access_Check .. Division_Check;
222    function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
223    --  This function is used to see if an access or division by zero check is
224    --  needed. The check is to be applied to a single variable appearing in the
225    --  source, and N is the node for the reference. If N is not of this form,
226    --  True is returned with no further processing. If N is of the right form,
227    --  then further processing determines if the given Check is needed.
228    --
229    --  The particular circuit is to see if we have the case of a check that is
230    --  not needed because it appears in the right operand of a short circuited
231    --  conditional where the left operand guards the check. For example:
232    --
233    --    if Var = 0 or else Q / Var > 12 then
234    --       ...
235    --    end if;
236    --
237    --  In this example, the division check is not required. At the same time
238    --  we can issue warnings for suspicious use of non-short-circuited forms,
239    --  such as:
240    --
241    --    if Var = 0 or Q / Var > 12 then
242    --       ...
243    --    end if;
244
245    procedure Find_Check
246      (Expr        : Node_Id;
247       Check_Type  : Character;
248       Target_Type : Entity_Id;
249       Entry_OK    : out Boolean;
250       Check_Num   : out Nat;
251       Ent         : out Entity_Id;
252       Ofs         : out Uint);
253    --  This routine is used by Enable_Range_Check and Enable_Overflow_Check
254    --  to see if a check is of the form for optimization, and if so, to see
255    --  if it has already been performed. Expr is the expression to check,
256    --  and Check_Type is 'R' for a range check, 'O' for an overflow check.
257    --  Target_Type is the target type for a range check, and Empty for an
258    --  overflow check. If the entry is not of the form for optimization,
259    --  then Entry_OK is set to False, and the remaining out parameters
260    --  are undefined. If the entry is OK, then Ent/Ofs are set to the
261    --  entity and offset from the expression. Check_Num is the number of
262    --  a matching saved entry in Saved_Checks, or zero if no such entry
263    --  is located.
264
265    function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
266    --  If a discriminal is used in constraining a prival, Return reference
267    --  to the discriminal of the protected body (which renames the parameter
268    --  of the enclosing protected operation). This clumsy transformation is
269    --  needed because privals are created too late and their actual subtypes
270    --  are not available when analysing the bodies of the protected operations.
271    --  This function is called whenever the bound is an entity and the scope
272    --  indicates a protected operation. If the bound is an in-parameter of
273    --  a protected operation that is not a prival, the function returns the
274    --  bound itself.
275    --  To be cleaned up???
276
277    function Guard_Access
278      (Cond    : Node_Id;
279       Loc     : Source_Ptr;
280       Ck_Node : Node_Id) return Node_Id;
281    --  In the access type case, guard the test with a test to ensure
282    --  that the access value is non-null, since the checks do not
283    --  not apply to null access values.
284
285    procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
286    --  Called by Apply_{Length,Range}_Checks to rewrite the tree with the
287    --  Constraint_Error node.
288
289    function Range_Or_Validity_Checks_Suppressed
290      (Expr : Node_Id) return Boolean;
291    --  Returns True if either range or validity checks or both are suppressed
292    --  for the type of the given expression, or, if the expression is the name
293    --  of an entity, if these checks are suppressed for the entity.
294
295    function Selected_Length_Checks
296      (Ck_Node    : Node_Id;
297       Target_Typ : Entity_Id;
298       Source_Typ : Entity_Id;
299       Warn_Node  : Node_Id) return Check_Result;
300    --  Like Apply_Selected_Length_Checks, except it doesn't modify
301    --  anything, just returns a list of nodes as described in the spec of
302    --  this package for the Range_Check function.
303
304    function Selected_Range_Checks
305      (Ck_Node    : Node_Id;
306       Target_Typ : Entity_Id;
307       Source_Typ : Entity_Id;
308       Warn_Node  : Node_Id) return Check_Result;
309    --  Like Apply_Selected_Range_Checks, except it doesn't modify anything,
310    --  just returns a list of nodes as described in the spec of this package
311    --  for the Range_Check function.
312
313    ------------------------------
314    -- Access_Checks_Suppressed --
315    ------------------------------
316
317    function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
318    begin
319       if Present (E) and then Checks_May_Be_Suppressed (E) then
320          return Is_Check_Suppressed (E, Access_Check);
321       else
322          return Scope_Suppress (Access_Check);
323       end if;
324    end Access_Checks_Suppressed;
325
326    -------------------------------------
327    -- Accessibility_Checks_Suppressed --
328    -------------------------------------
329
330    function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
331    begin
332       if Present (E) and then Checks_May_Be_Suppressed (E) then
333          return Is_Check_Suppressed (E, Accessibility_Check);
334       else
335          return Scope_Suppress (Accessibility_Check);
336       end if;
337    end Accessibility_Checks_Suppressed;
338
339    -----------------------------
340    -- Activate_Division_Check --
341    -----------------------------
342
343    procedure Activate_Division_Check (N : Node_Id) is
344    begin
345       Set_Do_Division_Check (N, True);
346       Possible_Local_Raise (N, Standard_Constraint_Error);
347    end Activate_Division_Check;
348
349    -----------------------------
350    -- Activate_Overflow_Check --
351    -----------------------------
352
353    procedure Activate_Overflow_Check (N : Node_Id) is
354    begin
355       Set_Do_Overflow_Check (N, True);
356       Possible_Local_Raise (N, Standard_Constraint_Error);
357    end Activate_Overflow_Check;
358
359    --------------------------
360    -- Activate_Range_Check --
361    --------------------------
362
363    procedure Activate_Range_Check (N : Node_Id) is
364    begin
365       Set_Do_Range_Check (N, True);
366       Possible_Local_Raise (N, Standard_Constraint_Error);
367    end Activate_Range_Check;
368
369    ---------------------------------
370    -- Alignment_Checks_Suppressed --
371    ---------------------------------
372
373    function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
374    begin
375       if Present (E) and then Checks_May_Be_Suppressed (E) then
376          return Is_Check_Suppressed (E, Alignment_Check);
377       else
378          return Scope_Suppress (Alignment_Check);
379       end if;
380    end Alignment_Checks_Suppressed;
381
382    -------------------------
383    -- Append_Range_Checks --
384    -------------------------
385
386    procedure Append_Range_Checks
387      (Checks       : Check_Result;
388       Stmts        : List_Id;
389       Suppress_Typ : Entity_Id;
390       Static_Sloc  : Source_Ptr;
391       Flag_Node    : Node_Id)
392    is
393       Internal_Flag_Node   : constant Node_Id    := Flag_Node;
394       Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
395
396       Checks_On : constant Boolean :=
397                     (not Index_Checks_Suppressed (Suppress_Typ))
398                        or else
399                     (not Range_Checks_Suppressed (Suppress_Typ));
400
401    begin
402       --  For now we just return if Checks_On is false, however this should
403       --  be enhanced to check for an always True value in the condition
404       --  and to generate a compilation warning???
405
406       if not Checks_On then
407          return;
408       end if;
409
410       for J in 1 .. 2 loop
411          exit when No (Checks (J));
412
413          if Nkind (Checks (J)) = N_Raise_Constraint_Error
414            and then Present (Condition (Checks (J)))
415          then
416             if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
417                Append_To (Stmts, Checks (J));
418                Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
419             end if;
420
421          else
422             Append_To
423               (Stmts,
424                 Make_Raise_Constraint_Error (Internal_Static_Sloc,
425                   Reason => CE_Range_Check_Failed));
426          end if;
427       end loop;
428    end Append_Range_Checks;
429
430    ------------------------
431    -- Apply_Access_Check --
432    ------------------------
433
434    procedure Apply_Access_Check (N : Node_Id) is
435       P : constant Node_Id := Prefix (N);
436
437    begin
438       --  We do not need checks if we are not generating code (i.e. the
439       --  expander is not active). This is not just an optimization, there
440       --  are cases (e.g. with pragma Debug) where generating the checks
441       --  can cause real trouble).
442
443       if not Expander_Active then
444          return;
445       end if;
446
447       --  No check if short circuiting makes check unnecessary
448
449       if not Check_Needed (P, Access_Check) then
450          return;
451       end if;
452
453       --  Otherwise go ahead and install the check
454
455       Install_Null_Excluding_Check (P);
456    end Apply_Access_Check;
457
458    -------------------------------
459    -- Apply_Accessibility_Check --
460    -------------------------------
461
462    procedure Apply_Accessibility_Check (N : Node_Id; Typ : Entity_Id) is
463       Loc         : constant Source_Ptr := Sloc (N);
464       Param_Ent   : constant Entity_Id  := Param_Entity (N);
465       Param_Level : Node_Id;
466       Type_Level  : Node_Id;
467
468    begin
469       if Inside_A_Generic then
470          return;
471
472       --  Only apply the run-time check if the access parameter
473       --  has an associated extra access level parameter and
474       --  when the level of the type is less deep than the level
475       --  of the access parameter.
476
477       elsif Present (Param_Ent)
478          and then Present (Extra_Accessibility (Param_Ent))
479          and then UI_Gt (Object_Access_Level (N),
480                          Type_Access_Level (Typ))
481          and then not Accessibility_Checks_Suppressed (Param_Ent)
482          and then not Accessibility_Checks_Suppressed (Typ)
483       then
484          Param_Level :=
485            New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
486
487          Type_Level :=
488            Make_Integer_Literal (Loc, Type_Access_Level (Typ));
489
490          --  Raise Program_Error if the accessibility level of the the access
491          --  parameter is deeper than the level of the target access type.
492
493          Insert_Action (N,
494            Make_Raise_Program_Error (Loc,
495              Condition =>
496                Make_Op_Gt (Loc,
497                  Left_Opnd  => Param_Level,
498                  Right_Opnd => Type_Level),
499              Reason => PE_Accessibility_Check_Failed));
500
501          Analyze_And_Resolve (N);
502       end if;
503    end Apply_Accessibility_Check;
504
505    --------------------------------
506    -- Apply_Address_Clause_Check --
507    --------------------------------
508
509    procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
510       AC   : constant Node_Id    := Address_Clause (E);
511       Loc  : constant Source_Ptr := Sloc (AC);
512       Typ  : constant Entity_Id  := Etype (E);
513       Aexp : constant Node_Id    := Expression (AC);
514
515       Expr : Node_Id;
516       --  Address expression (not necessarily the same as Aexp, for example
517       --  when Aexp is a reference to a constant, in which case Expr gets
518       --  reset to reference the value expression of the constant.
519
520       Size_Warning_Output : Boolean := False;
521       --  If we output a size warning we set this True, to stop generating
522       --  what is likely to be an unuseful redundant alignment warning.
523
524       procedure Compile_Time_Bad_Alignment;
525       --  Post error warnings when alignment is known to be incompatible. Note
526       --  that we do not go as far as inserting a raise of Program_Error since
527       --  this is an erroneous case, and it may happen that we are lucky and an
528       --  underaligned address turns out to be OK after all. Also this warning
529       --  is suppressed if we already complained about the size.
530
531       --------------------------------
532       -- Compile_Time_Bad_Alignment --
533       --------------------------------
534
535       procedure Compile_Time_Bad_Alignment is
536       begin
537          if not Size_Warning_Output
538            and then Address_Clause_Overlay_Warnings
539          then
540             Error_Msg_FE
541               ("?specified address for& may be inconsistent with alignment ",
542                Aexp, E);
543             Error_Msg_FE
544               ("\?program execution may be erroneous (RM 13.3(27))",
545                Aexp, E);
546          end if;
547       end Compile_Time_Bad_Alignment;
548
549    --  Start of processing for Apply_Address_Clause_Check
550
551    begin
552       --  First obtain expression from address clause
553
554       Expr := Expression (AC);
555
556       --  The following loop digs for the real expression to use in the check
557
558       loop
559          --  For constant, get constant expression
560
561          if Is_Entity_Name (Expr)
562            and then Ekind (Entity (Expr)) = E_Constant
563          then
564             Expr := Constant_Value (Entity (Expr));
565
566          --  For unchecked conversion, get result to convert
567
568          elsif Nkind (Expr) = N_Unchecked_Type_Conversion then
569             Expr := Expression (Expr);
570
571          --  For (common case) of To_Address call, get argument
572
573          elsif Nkind (Expr) = N_Function_Call
574            and then Is_Entity_Name (Name (Expr))
575            and then Is_RTE (Entity (Name (Expr)), RE_To_Address)
576          then
577             Expr := First (Parameter_Associations (Expr));
578
579             if Nkind (Expr) = N_Parameter_Association then
580                Expr := Explicit_Actual_Parameter (Expr);
581             end if;
582
583          --  We finally have the real expression
584
585          else
586             exit;
587          end if;
588       end loop;
589
590       --  Output a warning if we have the situation of
591
592       --      for X'Address use Y'Address
593
594       --  and X and Y both have known object sizes, and Y is smaller than X
595
596       if Nkind (Expr) = N_Attribute_Reference
597         and then Attribute_Name (Expr) = Name_Address
598         and then Is_Entity_Name (Prefix (Expr))
599       then
600          declare
601             Exp_Ent  : constant Entity_Id := Entity (Prefix (Expr));
602             Obj_Size : Uint := No_Uint;
603             Exp_Size : Uint := No_Uint;
604
605          begin
606             if Known_Esize (E) then
607                Obj_Size := Esize (E);
608             elsif Known_Esize (Etype (E)) then
609                Obj_Size := Esize (Etype (E));
610             end if;
611
612             if Known_Esize (Exp_Ent) then
613                Exp_Size := Esize (Exp_Ent);
614             elsif Known_Esize (Etype (Exp_Ent)) then
615                Exp_Size := Esize (Etype (Exp_Ent));
616             end if;
617
618             if Obj_Size /= No_Uint
619               and then Exp_Size /= No_Uint
620               and then Obj_Size > Exp_Size
621               and then not Warnings_Off (E)
622             then
623                if Address_Clause_Overlay_Warnings then
624                   Error_Msg_FE
625                     ("?& overlays smaller object", Aexp, E);
626                   Error_Msg_FE
627                     ("\?program execution may be erroneous", Aexp, E);
628                   Size_Warning_Output := True;
629                end if;
630             end if;
631          end;
632       end if;
633
634       --  See if alignment check needed. Note that we never need a check if the
635       --  maximum alignment is one, since the check will always succeed.
636
637       --  Note: we do not check for checks suppressed here, since that check
638       --  was done in Sem_Ch13 when the address clause was processed. We are
639       --  only called if checks were not suppressed. The reason for this is
640       --  that we have to delay the call to Apply_Alignment_Check till freeze
641       --  time (so that all types etc are elaborated), but we have to check
642       --  the status of check suppressing at the point of the address clause.
643
644       if No (AC)
645         or else not Check_Address_Alignment (AC)
646         or else Maximum_Alignment = 1
647       then
648          return;
649       end if;
650
651       --  See if we know that Expr is a bad alignment at compile time
652
653       if Compile_Time_Known_Value (Expr)
654         and then (Known_Alignment (E) or else Known_Alignment (Typ))
655       then
656          declare
657             AL : Uint := Alignment (Typ);
658
659          begin
660             --  The object alignment might be more restrictive than the
661             --  type alignment.
662
663             if Known_Alignment (E) then
664                AL := Alignment (E);
665             end if;
666
667             if Expr_Value (Expr) mod AL /= 0 then
668                Compile_Time_Bad_Alignment;
669             else
670                return;
671             end if;
672          end;
673
674       --  If the expression has the form X'Address, then we can find out if
675       --  the object X has an alignment that is compatible with the object E.
676
677       elsif Nkind (Expr) = N_Attribute_Reference
678         and then Attribute_Name (Expr) = Name_Address
679       then
680          declare
681             AR : constant Alignment_Result :=
682                    Has_Compatible_Alignment (E, Prefix (Expr));
683          begin
684             if AR = Known_Compatible then
685                return;
686             elsif AR = Known_Incompatible then
687                Compile_Time_Bad_Alignment;
688             end if;
689          end;
690       end if;
691
692       --  Here we do not know if the value is acceptable. Stricly we don't have
693       --  to do anything, since if the alignment is bad, we have an erroneous
694       --  program. However we are allowed to check for erroneous conditions and
695       --  we decide to do this by default if the check is not suppressed.
696
697       --  However, don't do the check if elaboration code is unwanted
698
699       if Restriction_Active (No_Elaboration_Code) then
700          return;
701
702       --  Generate a check to raise PE if alignment may be inappropriate
703
704       else
705          --  If the original expression is a non-static constant, use the
706          --  name of the constant itself rather than duplicating its
707          --  defining expression, which was extracted above.
708
709          --  Note: Expr is empty if the address-clause is applied to in-mode
710          --  actuals (allowed by 13.1(22)).
711
712          if not Present (Expr)
713            or else
714              (Is_Entity_Name (Expression (AC))
715                and then Ekind (Entity (Expression (AC))) = E_Constant
716                and then Nkind (Parent (Entity (Expression (AC))))
717                                  = N_Object_Declaration)
718          then
719             Expr := New_Copy_Tree (Expression (AC));
720          else
721             Remove_Side_Effects (Expr);
722          end if;
723
724          Insert_After_And_Analyze (N,
725            Make_Raise_Program_Error (Loc,
726              Condition =>
727                Make_Op_Ne (Loc,
728                  Left_Opnd =>
729                    Make_Op_Mod (Loc,
730                      Left_Opnd =>
731                        Unchecked_Convert_To
732                          (RTE (RE_Integer_Address), Expr),
733                      Right_Opnd =>
734                        Make_Attribute_Reference (Loc,
735                          Prefix => New_Occurrence_Of (E, Loc),
736                          Attribute_Name => Name_Alignment)),
737                  Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
738              Reason => PE_Misaligned_Address_Value),
739            Suppress => All_Checks);
740          return;
741       end if;
742
743    exception
744       --  If we have some missing run time component in configurable run time
745       --  mode then just skip the check (it is not required in any case).
746
747       when RE_Not_Available =>
748          return;
749    end Apply_Address_Clause_Check;
750
751    -------------------------------------
752    -- Apply_Arithmetic_Overflow_Check --
753    -------------------------------------
754
755    --  This routine is called only if the type is an integer type, and
756    --  a software arithmetic overflow check must be performed for op
757    --  (add, subtract, multiply). The check is performed only if
758    --  Software_Overflow_Checking is enabled and Do_Overflow_Check
759    --  is set. In this case we expand the operation into a more complex
760    --  sequence of tests that ensures that overflow is properly caught.
761
762    procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
763       Loc   : constant Source_Ptr := Sloc (N);
764       Typ   : constant Entity_Id  := Etype (N);
765       Rtyp  : constant Entity_Id  := Root_Type (Typ);
766       Siz   : constant Int        := UI_To_Int (Esize (Rtyp));
767       Dsiz  : constant Int        := Siz * 2;
768       Opnod : Node_Id;
769       Ctyp  : Entity_Id;
770       Opnd  : Node_Id;
771       Cent  : RE_Id;
772
773    begin
774       --  Skip this if overflow checks are done in back end, or the overflow
775       --  flag is not set anyway, or we are not doing code expansion.
776       --  Special case CLI target, where arithmetic overflow checks can be
777       --  performed for integer and long_integer
778
779       if Backend_Overflow_Checks_On_Target
780         or else (VM_Target = CLI_Target and then Siz >= Standard_Integer_Size)
781         or else not Do_Overflow_Check (N)
782         or else not Expander_Active
783       then
784          return;
785       end if;
786
787       --  Otherwise, we generate the full general code for front end overflow
788       --  detection, which works by doing arithmetic in a larger type:
789
790       --    x op y
791
792       --  is expanded into
793
794       --    Typ (Checktyp (x) op Checktyp (y));
795
796       --  where Typ is the type of the original expression, and Checktyp is
797       --  an integer type of sufficient length to hold the largest possible
798       --  result.
799
800       --  In the case where check type exceeds the size of Long_Long_Integer,
801       --  we use a different approach, expanding to:
802
803       --    typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
804
805       --  where xxx is Add, Multiply or Subtract as appropriate
806
807       --  Find check type if one exists
808
809       if Dsiz <= Standard_Integer_Size then
810          Ctyp := Standard_Integer;
811
812       elsif Dsiz <= Standard_Long_Long_Integer_Size then
813          Ctyp := Standard_Long_Long_Integer;
814
815       --  No check type exists, use runtime call
816
817       else
818          if Nkind (N) = N_Op_Add then
819             Cent := RE_Add_With_Ovflo_Check;
820
821          elsif Nkind (N) = N_Op_Multiply then
822             Cent := RE_Multiply_With_Ovflo_Check;
823
824          else
825             pragma Assert (Nkind (N) = N_Op_Subtract);
826             Cent := RE_Subtract_With_Ovflo_Check;
827          end if;
828
829          Rewrite (N,
830            OK_Convert_To (Typ,
831              Make_Function_Call (Loc,
832                Name => New_Reference_To (RTE (Cent), Loc),
833                Parameter_Associations => New_List (
834                  OK_Convert_To (RTE (RE_Integer_64), Left_Opnd  (N)),
835                  OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
836
837          Analyze_And_Resolve (N, Typ);
838          return;
839       end if;
840
841       --  If we fall through, we have the case where we do the arithmetic in
842       --  the next higher type and get the check by conversion. In these cases
843       --  Ctyp is set to the type to be used as the check type.
844
845       Opnod := Relocate_Node (N);
846
847       Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
848
849       Analyze (Opnd);
850       Set_Etype (Opnd, Ctyp);
851       Set_Analyzed (Opnd, True);
852       Set_Left_Opnd (Opnod, Opnd);
853
854       Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
855
856       Analyze (Opnd);
857       Set_Etype (Opnd, Ctyp);
858       Set_Analyzed (Opnd, True);
859       Set_Right_Opnd (Opnod, Opnd);
860
861       --  The type of the operation changes to the base type of the check type,
862       --  and we reset the overflow check indication, since clearly no overflow
863       --  is possible now that we are using a double length type. We also set
864       --  the Analyzed flag to avoid a recursive attempt to expand the node.
865
866       Set_Etype             (Opnod, Base_Type (Ctyp));
867       Set_Do_Overflow_Check (Opnod, False);
868       Set_Analyzed          (Opnod, True);
869
870       --  Now build the outer conversion
871
872       Opnd := OK_Convert_To (Typ, Opnod);
873       Analyze (Opnd);
874       Set_Etype (Opnd, Typ);
875
876       --  In the discrete type case, we directly generate the range check for
877       --  the outer operand. This range check will implement the required
878       --  overflow check.
879
880       if Is_Discrete_Type (Typ) then
881          Rewrite (N, Opnd);
882          Generate_Range_Check (Expression (N), Typ, CE_Overflow_Check_Failed);
883
884       --  For other types, we enable overflow checking on the conversion,
885       --  after setting the node as analyzed to prevent recursive attempts
886       --  to expand the conversion node.
887
888       else
889          Set_Analyzed (Opnd, True);
890          Enable_Overflow_Check (Opnd);
891          Rewrite (N, Opnd);
892       end if;
893
894    exception
895       when RE_Not_Available =>
896          return;
897    end Apply_Arithmetic_Overflow_Check;
898
899    ----------------------------
900    -- Apply_Constraint_Check --
901    ----------------------------
902
903    procedure Apply_Constraint_Check
904      (N          : Node_Id;
905       Typ        : Entity_Id;
906       No_Sliding : Boolean := False)
907    is
908       Desig_Typ : Entity_Id;
909
910    begin
911       if Inside_A_Generic then
912          return;
913
914       elsif Is_Scalar_Type (Typ) then
915          Apply_Scalar_Range_Check (N, Typ);
916
917       elsif Is_Array_Type (Typ) then
918
919          --  A useful optimization: an aggregate with only an others clause
920          --  always has the right bounds.
921
922          if Nkind (N) = N_Aggregate
923            and then No (Expressions (N))
924            and then Nkind
925             (First (Choices (First (Component_Associations (N)))))
926               = N_Others_Choice
927          then
928             return;
929          end if;
930
931          if Is_Constrained (Typ) then
932             Apply_Length_Check (N, Typ);
933
934             if No_Sliding then
935                Apply_Range_Check (N, Typ);
936             end if;
937          else
938             Apply_Range_Check (N, Typ);
939          end if;
940
941       elsif (Is_Record_Type (Typ)
942                or else Is_Private_Type (Typ))
943         and then Has_Discriminants (Base_Type (Typ))
944         and then Is_Constrained (Typ)
945       then
946          Apply_Discriminant_Check (N, Typ);
947
948       elsif Is_Access_Type (Typ) then
949
950          Desig_Typ := Designated_Type (Typ);
951
952          --  No checks necessary if expression statically null
953
954          if Known_Null (N) then
955             if Can_Never_Be_Null (Typ) then
956                Install_Null_Excluding_Check (N);
957             end if;
958
959          --  No sliding possible on access to arrays
960
961          elsif Is_Array_Type (Desig_Typ) then
962             if Is_Constrained (Desig_Typ) then
963                Apply_Length_Check (N, Typ);
964             end if;
965
966             Apply_Range_Check (N, Typ);
967
968          elsif Has_Discriminants (Base_Type (Desig_Typ))
969             and then Is_Constrained (Desig_Typ)
970          then
971             Apply_Discriminant_Check (N, Typ);
972          end if;
973
974          --  Apply the the 2005 Null_Excluding check. Note that we do not apply
975          --  this check if the constraint node is illegal, as shown by having
976          --  an error posted. This additional guard prevents cascaded errors
977          --  and compiler aborts on illegal programs involving Ada 2005 checks.
978
979          if Can_Never_Be_Null (Typ)
980            and then not Can_Never_Be_Null (Etype (N))
981            and then not Error_Posted (N)
982          then
983             Install_Null_Excluding_Check (N);
984          end if;
985       end if;
986    end Apply_Constraint_Check;
987
988    ------------------------------
989    -- Apply_Discriminant_Check --
990    ------------------------------
991
992    procedure Apply_Discriminant_Check
993      (N   : Node_Id;
994       Typ : Entity_Id;
995       Lhs : Node_Id := Empty)
996    is
997       Loc       : constant Source_Ptr := Sloc (N);
998       Do_Access : constant Boolean    := Is_Access_Type (Typ);
999       S_Typ     : Entity_Id  := Etype (N);
1000       Cond      : Node_Id;
1001       T_Typ     : Entity_Id;
1002
1003       function Is_Aliased_Unconstrained_Component return Boolean;
1004       --  It is possible for an aliased component to have a nominal
1005       --  unconstrained subtype (through instantiation). If this is a
1006       --  discriminated component assigned in the expansion of an aggregate
1007       --  in an initialization, the check must be suppressed. This unusual
1008       --  situation requires a predicate of its own.
1009
1010       ----------------------------------------
1011       -- Is_Aliased_Unconstrained_Component --
1012       ----------------------------------------
1013
1014       function Is_Aliased_Unconstrained_Component return Boolean is
1015          Comp : Entity_Id;
1016          Pref : Node_Id;
1017
1018       begin
1019          if Nkind (Lhs) /= N_Selected_Component then
1020             return False;
1021          else
1022             Comp := Entity (Selector_Name (Lhs));
1023             Pref := Prefix (Lhs);
1024          end if;
1025
1026          if Ekind (Comp) /= E_Component
1027            or else not Is_Aliased (Comp)
1028          then
1029             return False;
1030          end if;
1031
1032          return not Comes_From_Source (Pref)
1033            and then In_Instance
1034            and then not Is_Constrained (Etype (Comp));
1035       end Is_Aliased_Unconstrained_Component;
1036
1037    --  Start of processing for Apply_Discriminant_Check
1038
1039    begin
1040       if Do_Access then
1041          T_Typ := Designated_Type (Typ);
1042       else
1043          T_Typ := Typ;
1044       end if;
1045
1046       --  Nothing to do if discriminant checks are suppressed or else no code
1047       --  is to be generated
1048
1049       if not Expander_Active
1050         or else Discriminant_Checks_Suppressed (T_Typ)
1051       then
1052          return;
1053       end if;
1054
1055       --  No discriminant checks necessary for an access when expression is
1056       --  statically Null. This is not only an optimization, it is fundamental
1057       --  because otherwise discriminant checks may be generated in init procs
1058       --  for types containing an access to a not-yet-frozen record, causing a
1059       --  deadly forward reference.
1060
1061       --  Also, if the expression is of an access type whose designated type is
1062       --  incomplete, then the access value must be null and we suppress the
1063       --  check.
1064
1065       if Known_Null (N) then
1066          return;
1067
1068       elsif Is_Access_Type (S_Typ) then
1069          S_Typ := Designated_Type (S_Typ);
1070
1071          if Ekind (S_Typ) = E_Incomplete_Type then
1072             return;
1073          end if;
1074       end if;
1075
1076       --  If an assignment target is present, then we need to generate the
1077       --  actual subtype if the target is a parameter or aliased object with
1078       --  an unconstrained nominal subtype.
1079
1080       --  Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1081       --  subtype to the parameter and dereference cases, since other aliased
1082       --  objects are unconstrained (unless the nominal subtype is explicitly
1083       --  constrained). (But we also need to test for renamings???)
1084
1085       if Present (Lhs)
1086         and then (Present (Param_Entity (Lhs))
1087                    or else (Ada_Version < Ada_05
1088                              and then not Is_Constrained (T_Typ)
1089                              and then Is_Aliased_View (Lhs)
1090                              and then not Is_Aliased_Unconstrained_Component)
1091                    or else (Ada_Version >= Ada_05
1092                              and then not Is_Constrained (T_Typ)
1093                              and then Nkind (Lhs) = N_Explicit_Dereference
1094                              and then Nkind (Original_Node (Lhs)) /=
1095                                         N_Function_Call))
1096       then
1097          T_Typ := Get_Actual_Subtype (Lhs);
1098       end if;
1099
1100       --  Nothing to do if the type is unconstrained (this is the case where
1101       --  the actual subtype in the RM sense of N is unconstrained and no check
1102       --  is required).
1103
1104       if not Is_Constrained (T_Typ) then
1105          return;
1106
1107       --  Ada 2005: nothing to do if the type is one for which there is a
1108       --  partial view that is constrained.
1109
1110       elsif Ada_Version >= Ada_05
1111         and then Has_Constrained_Partial_View (Base_Type (T_Typ))
1112       then
1113          return;
1114       end if;
1115
1116       --  Nothing to do if the type is an Unchecked_Union
1117
1118       if Is_Unchecked_Union (Base_Type (T_Typ)) then
1119          return;
1120       end if;
1121
1122       --  Suppress checks if the subtypes are the same. the check must be
1123       --  preserved in an assignment to a formal, because the constraint is
1124       --  given by the actual.
1125
1126       if Nkind (Original_Node (N)) /= N_Allocator
1127         and then (No (Lhs)
1128           or else not Is_Entity_Name (Lhs)
1129           or else No (Param_Entity (Lhs)))
1130       then
1131          if (Etype (N) = Typ
1132               or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1133            and then not Is_Aliased_View (Lhs)
1134          then
1135             return;
1136          end if;
1137
1138       --  We can also eliminate checks on allocators with a subtype mark that
1139       --  coincides with the context type. The context type may be a subtype
1140       --  without a constraint (common case, a generic actual).
1141
1142       elsif Nkind (Original_Node (N)) = N_Allocator
1143         and then Is_Entity_Name (Expression (Original_Node (N)))
1144       then
1145          declare
1146             Alloc_Typ : constant Entity_Id :=
1147                           Entity (Expression (Original_Node (N)));
1148
1149          begin
1150             if Alloc_Typ = T_Typ
1151               or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1152                         and then Is_Entity_Name (
1153                           Subtype_Indication (Parent (T_Typ)))
1154                         and then Alloc_Typ = Base_Type (T_Typ))
1155
1156             then
1157                return;
1158             end if;
1159          end;
1160       end if;
1161
1162       --  See if we have a case where the types are both constrained, and all
1163       --  the constraints are constants. In this case, we can do the check
1164       --  successfully at compile time.
1165
1166       --  We skip this check for the case where the node is a rewritten`
1167       --  allocator, because it already carries the context subtype, and
1168       --  extracting the discriminants from the aggregate is messy.
1169
1170       if Is_Constrained (S_Typ)
1171         and then Nkind (Original_Node (N)) /= N_Allocator
1172       then
1173          declare
1174             DconT : Elmt_Id;
1175             Discr : Entity_Id;
1176             DconS : Elmt_Id;
1177             ItemS : Node_Id;
1178             ItemT : Node_Id;
1179
1180          begin
1181             --  S_Typ may not have discriminants in the case where it is a
1182             --  private type completed by a default discriminated type. In that
1183             --  case, we need to get the constraints from the underlying_type.
1184             --  If the underlying type is unconstrained (i.e. has no default
1185             --  discriminants) no check is needed.
1186
1187             if Has_Discriminants (S_Typ) then
1188                Discr := First_Discriminant (S_Typ);
1189                DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1190
1191             else
1192                Discr := First_Discriminant (Underlying_Type (S_Typ));
1193                DconS :=
1194                  First_Elmt
1195                    (Discriminant_Constraint (Underlying_Type (S_Typ)));
1196
1197                if No (DconS) then
1198                   return;
1199                end if;
1200
1201                --  A further optimization: if T_Typ is derived from S_Typ
1202                --  without imposing a constraint, no check is needed.
1203
1204                if Nkind (Original_Node (Parent (T_Typ))) =
1205                  N_Full_Type_Declaration
1206                then
1207                   declare
1208                      Type_Def : constant Node_Id :=
1209                                  Type_Definition
1210                                    (Original_Node (Parent (T_Typ)));
1211                   begin
1212                      if Nkind (Type_Def) = N_Derived_Type_Definition
1213                        and then Is_Entity_Name (Subtype_Indication (Type_Def))
1214                        and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1215                      then
1216                         return;
1217                      end if;
1218                   end;
1219                end if;
1220             end if;
1221
1222             DconT  := First_Elmt (Discriminant_Constraint (T_Typ));
1223
1224             while Present (Discr) loop
1225                ItemS := Node (DconS);
1226                ItemT := Node (DconT);
1227
1228                --  For a discriminated component type constrained by the
1229                --  current instance of an enclosing type, there is no
1230                --  applicable discriminant check.
1231
1232                if Nkind (ItemT) = N_Attribute_Reference
1233                  and then Is_Access_Type (Etype (ItemT))
1234                  and then Is_Entity_Name (Prefix (ItemT))
1235                  and then Is_Type (Entity (Prefix (ItemT)))
1236                then
1237                   return;
1238                end if;
1239
1240                exit when
1241                  not Is_OK_Static_Expression (ItemS)
1242                    or else
1243                  not Is_OK_Static_Expression (ItemT);
1244
1245                if Expr_Value (ItemS) /= Expr_Value (ItemT) then
1246                   if Do_Access then   --  needs run-time check.
1247                      exit;
1248                   else
1249                      Apply_Compile_Time_Constraint_Error
1250                        (N, "incorrect value for discriminant&?",
1251                         CE_Discriminant_Check_Failed, Ent => Discr);
1252                      return;
1253                   end if;
1254                end if;
1255
1256                Next_Elmt (DconS);
1257                Next_Elmt (DconT);
1258                Next_Discriminant (Discr);
1259             end loop;
1260
1261             if No (Discr) then
1262                return;
1263             end if;
1264          end;
1265       end if;
1266
1267       --  Here we need a discriminant check. First build the expression
1268       --  for the comparisons of the discriminants:
1269
1270       --    (n.disc1 /= typ.disc1) or else
1271       --    (n.disc2 /= typ.disc2) or else
1272       --     ...
1273       --    (n.discn /= typ.discn)
1274
1275       Cond := Build_Discriminant_Checks (N, T_Typ);
1276
1277       --  If Lhs is set and is a parameter, then the condition is
1278       --  guarded by: lhs'constrained and then (condition built above)
1279
1280       if Present (Param_Entity (Lhs)) then
1281          Cond :=
1282            Make_And_Then (Loc,
1283              Left_Opnd =>
1284                Make_Attribute_Reference (Loc,
1285                  Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1286                  Attribute_Name => Name_Constrained),
1287              Right_Opnd => Cond);
1288       end if;
1289
1290       if Do_Access then
1291          Cond := Guard_Access (Cond, Loc, N);
1292       end if;
1293
1294       Insert_Action (N,
1295         Make_Raise_Constraint_Error (Loc,
1296           Condition => Cond,
1297           Reason    => CE_Discriminant_Check_Failed));
1298    end Apply_Discriminant_Check;
1299
1300    ------------------------
1301    -- Apply_Divide_Check --
1302    ------------------------
1303
1304    procedure Apply_Divide_Check (N : Node_Id) is
1305       Loc   : constant Source_Ptr := Sloc (N);
1306       Typ   : constant Entity_Id  := Etype (N);
1307       Left  : constant Node_Id    := Left_Opnd (N);
1308       Right : constant Node_Id    := Right_Opnd (N);
1309
1310       LLB : Uint;
1311       Llo : Uint;
1312       Lhi : Uint;
1313       LOK : Boolean;
1314       Rlo : Uint;
1315       Rhi : Uint;
1316       ROK : Boolean;
1317
1318    begin
1319       if Expander_Active
1320         and then not Backend_Divide_Checks_On_Target
1321         and then Check_Needed (Right, Division_Check)
1322       then
1323          Determine_Range (Right, ROK, Rlo, Rhi);
1324
1325          --  See if division by zero possible, and if so generate test. This
1326          --  part of the test is not controlled by the -gnato switch.
1327
1328          if Do_Division_Check (N) then
1329             if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1330                Insert_Action (N,
1331                  Make_Raise_Constraint_Error (Loc,
1332                    Condition =>
1333                      Make_Op_Eq (Loc,
1334                        Left_Opnd  => Duplicate_Subexpr_Move_Checks (Right),
1335                        Right_Opnd => Make_Integer_Literal (Loc, 0)),
1336                    Reason => CE_Divide_By_Zero));
1337             end if;
1338          end if;
1339
1340          --  Test for extremely annoying case of xxx'First divided by -1
1341
1342          if Do_Overflow_Check (N) then
1343             if Nkind (N) = N_Op_Divide
1344               and then Is_Signed_Integer_Type (Typ)
1345             then
1346                Determine_Range (Left, LOK, Llo, Lhi);
1347                LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1348
1349                if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1350                  and then
1351                  ((not LOK) or else (Llo = LLB))
1352                then
1353                   Insert_Action (N,
1354                     Make_Raise_Constraint_Error (Loc,
1355                       Condition =>
1356                         Make_And_Then (Loc,
1357
1358                            Make_Op_Eq (Loc,
1359                              Left_Opnd  =>
1360                                Duplicate_Subexpr_Move_Checks (Left),
1361                              Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1362
1363                            Make_Op_Eq (Loc,
1364                              Left_Opnd =>
1365                                Duplicate_Subexpr (Right),
1366                              Right_Opnd =>
1367                                Make_Integer_Literal (Loc, -1))),
1368                       Reason => CE_Overflow_Check_Failed));
1369                end if;
1370             end if;
1371          end if;
1372       end if;
1373    end Apply_Divide_Check;
1374
1375    ----------------------------------
1376    -- Apply_Float_Conversion_Check --
1377    ----------------------------------
1378
1379    --  Let F and I be the source and target types of the conversion. The RM
1380    --  specifies that a floating-point value X is rounded to the nearest
1381    --  integer, with halfway cases being rounded away from zero. The rounded
1382    --  value of X is checked against I'Range.
1383
1384    --  The catch in the above paragraph is that there is no good way to know
1385    --  whether the round-to-integer operation resulted in overflow. A remedy is
1386    --  to perform a range check in the floating-point domain instead, however:
1387
1388    --      (1)  The bounds may not be known at compile time
1389    --      (2)  The check must take into account rounding or truncation.
1390    --      (3)  The range of type I may not be exactly representable in F.
1391    --      (4)  For the rounding case, The end-points I'First - 0.5 and
1392    --           I'Last + 0.5 may or may not be in range, depending on the
1393    --           sign of  I'First and I'Last.
1394    --      (5)  X may be a NaN, which will fail any comparison
1395
1396    --  The following steps correctly convert X with rounding:
1397
1398    --      (1) If either I'First or I'Last is not known at compile time, use
1399    --          I'Base instead of I in the next three steps and perform a
1400    --          regular range check against I'Range after conversion.
1401    --      (2) If I'First - 0.5 is representable in F then let Lo be that
1402    --          value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1403    --          F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1404    --          In other words, take one of the closest floating-point numbers
1405    --          (which is an integer value) to I'First, and see if it is in
1406    --          range or not.
1407    --      (3) If I'Last + 0.5 is representable in F then let Hi be that value
1408    --          and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1409    --          F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1410    --      (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1411    --                     or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1412
1413    --  For the truncating case, replace steps (2) and (3) as follows:
1414    --      (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1415    --          be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1416    --          Lo_OK be True.
1417    --      (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1418    --          be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1419    --          Hi_OK be False
1420
1421    procedure Apply_Float_Conversion_Check
1422      (Ck_Node    : Node_Id;
1423       Target_Typ : Entity_Id)
1424    is
1425       LB          : constant Node_Id    := Type_Low_Bound (Target_Typ);
1426       HB          : constant Node_Id    := Type_High_Bound (Target_Typ);
1427       Loc         : constant Source_Ptr := Sloc (Ck_Node);
1428       Expr_Type   : constant Entity_Id  := Base_Type (Etype (Ck_Node));
1429       Target_Base : constant Entity_Id  :=
1430                       Implementation_Base_Type (Target_Typ);
1431
1432       Par : constant Node_Id := Parent (Ck_Node);
1433       pragma Assert (Nkind (Par) = N_Type_Conversion);
1434       --  Parent of check node, must be a type conversion
1435
1436       Truncate  : constant Boolean := Float_Truncate (Par);
1437       Max_Bound : constant Uint :=
1438                     UI_Expon
1439                       (Machine_Radix (Expr_Type),
1440                        Machine_Mantissa (Expr_Type) - 1) - 1;
1441
1442       --  Largest bound, so bound plus or minus half is a machine number of F
1443
1444       Ifirst, Ilast : Uint;
1445       --  Bounds of integer type
1446
1447       Lo, Hi : Ureal;
1448       --  Bounds to check in floating-point domain
1449
1450       Lo_OK, Hi_OK : Boolean;
1451       --  True iff Lo resp. Hi belongs to I'Range
1452
1453       Lo_Chk, Hi_Chk : Node_Id;
1454       --  Expressions that are False iff check fails
1455
1456       Reason : RT_Exception_Code;
1457
1458    begin
1459       if not Compile_Time_Known_Value (LB)
1460           or not Compile_Time_Known_Value (HB)
1461       then
1462          declare
1463             --  First check that the value falls in the range of the base type,
1464             --  to prevent overflow during conversion and then perform a
1465             --  regular range check against the (dynamic) bounds.
1466
1467             pragma Assert (Target_Base /= Target_Typ);
1468
1469             Temp : constant Entity_Id :=
1470                     Make_Defining_Identifier (Loc,
1471                       Chars => New_Internal_Name ('T'));
1472
1473          begin
1474             Apply_Float_Conversion_Check (Ck_Node, Target_Base);
1475             Set_Etype (Temp, Target_Base);
1476
1477             Insert_Action (Parent (Par),
1478               Make_Object_Declaration (Loc,
1479                 Defining_Identifier => Temp,
1480                 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
1481                 Expression => New_Copy_Tree (Par)),
1482                 Suppress => All_Checks);
1483
1484             Insert_Action (Par,
1485               Make_Raise_Constraint_Error (Loc,
1486                 Condition =>
1487                   Make_Not_In (Loc,
1488                     Left_Opnd  => New_Occurrence_Of (Temp, Loc),
1489                     Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
1490                 Reason => CE_Range_Check_Failed));
1491             Rewrite (Par, New_Occurrence_Of (Temp, Loc));
1492
1493             return;
1494          end;
1495       end if;
1496
1497       --  Get the bounds of the target type
1498
1499       Ifirst := Expr_Value (LB);
1500       Ilast  := Expr_Value (HB);
1501
1502       --  Check against lower bound
1503
1504       if Truncate and then Ifirst > 0 then
1505          Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
1506          Lo_OK := False;
1507
1508       elsif Truncate then
1509          Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
1510          Lo_OK := True;
1511
1512       elsif abs (Ifirst) < Max_Bound then
1513          Lo := UR_From_Uint (Ifirst) - Ureal_Half;
1514          Lo_OK := (Ifirst > 0);
1515
1516       else
1517          Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
1518          Lo_OK := (Lo >= UR_From_Uint (Ifirst));
1519       end if;
1520
1521       if Lo_OK then
1522
1523          --  Lo_Chk := (X >= Lo)
1524
1525          Lo_Chk := Make_Op_Ge (Loc,
1526                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1527                      Right_Opnd => Make_Real_Literal (Loc, Lo));
1528
1529       else
1530          --  Lo_Chk := (X > Lo)
1531
1532          Lo_Chk := Make_Op_Gt (Loc,
1533                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1534                      Right_Opnd => Make_Real_Literal (Loc, Lo));
1535       end if;
1536
1537       --  Check against higher bound
1538
1539       if Truncate and then Ilast < 0 then
1540          Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
1541          Lo_OK := False;
1542
1543       elsif Truncate then
1544          Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
1545          Hi_OK := True;
1546
1547       elsif abs (Ilast) < Max_Bound then
1548          Hi := UR_From_Uint (Ilast) + Ureal_Half;
1549          Hi_OK := (Ilast < 0);
1550       else
1551          Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
1552          Hi_OK := (Hi <= UR_From_Uint (Ilast));
1553       end if;
1554
1555       if Hi_OK then
1556
1557          --  Hi_Chk := (X <= Hi)
1558
1559          Hi_Chk := Make_Op_Le (Loc,
1560                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1561                      Right_Opnd => Make_Real_Literal (Loc, Hi));
1562
1563       else
1564          --  Hi_Chk := (X < Hi)
1565
1566          Hi_Chk := Make_Op_Lt (Loc,
1567                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1568                      Right_Opnd => Make_Real_Literal (Loc, Hi));
1569       end if;
1570
1571       --  If the bounds of the target type are the same as those of the base
1572       --  type, the check is an overflow check as a range check is not
1573       --  performed in these cases.
1574
1575       if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
1576         and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
1577       then
1578          Reason := CE_Overflow_Check_Failed;
1579       else
1580          Reason := CE_Range_Check_Failed;
1581       end if;
1582
1583       --  Raise CE if either conditions does not hold
1584
1585       Insert_Action (Ck_Node,
1586         Make_Raise_Constraint_Error (Loc,
1587           Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
1588           Reason    => Reason));
1589    end Apply_Float_Conversion_Check;
1590
1591    ------------------------
1592    -- Apply_Length_Check --
1593    ------------------------
1594
1595    procedure Apply_Length_Check
1596      (Ck_Node    : Node_Id;
1597       Target_Typ : Entity_Id;
1598       Source_Typ : Entity_Id := Empty)
1599    is
1600    begin
1601       Apply_Selected_Length_Checks
1602         (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1603    end Apply_Length_Check;
1604
1605    -----------------------
1606    -- Apply_Range_Check --
1607    -----------------------
1608
1609    procedure Apply_Range_Check
1610      (Ck_Node    : Node_Id;
1611       Target_Typ : Entity_Id;
1612       Source_Typ : Entity_Id := Empty)
1613    is
1614    begin
1615       Apply_Selected_Range_Checks
1616         (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1617    end Apply_Range_Check;
1618
1619    ------------------------------
1620    -- Apply_Scalar_Range_Check --
1621    ------------------------------
1622
1623    --  Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
1624    --  off if it is already set on.
1625
1626    procedure Apply_Scalar_Range_Check
1627      (Expr       : Node_Id;
1628       Target_Typ : Entity_Id;
1629       Source_Typ : Entity_Id := Empty;
1630       Fixed_Int  : Boolean   := False)
1631    is
1632       Parnt   : constant Node_Id := Parent (Expr);
1633       S_Typ   : Entity_Id;
1634       Arr     : Node_Id   := Empty;  -- initialize to prevent warning
1635       Arr_Typ : Entity_Id := Empty;  -- initialize to prevent warning
1636       OK      : Boolean;
1637
1638       Is_Subscr_Ref : Boolean;
1639       --  Set true if Expr is a subscript
1640
1641       Is_Unconstrained_Subscr_Ref : Boolean;
1642       --  Set true if Expr is a subscript of an unconstrained array. In this
1643       --  case we do not attempt to do an analysis of the value against the
1644       --  range of the subscript, since we don't know the actual subtype.
1645
1646       Int_Real : Boolean;
1647       --  Set to True if Expr should be regarded as a real value even though
1648       --  the type of Expr might be discrete.
1649
1650       procedure Bad_Value;
1651       --  Procedure called if value is determined to be out of range
1652
1653       ---------------
1654       -- Bad_Value --
1655       ---------------
1656
1657       procedure Bad_Value is
1658       begin
1659          Apply_Compile_Time_Constraint_Error
1660            (Expr, "value not in range of}?", CE_Range_Check_Failed,
1661             Ent => Target_Typ,
1662             Typ => Target_Typ);
1663       end Bad_Value;
1664
1665    --  Start of processing for Apply_Scalar_Range_Check
1666
1667    begin
1668       --  Return if check obviously not needed
1669
1670       if
1671          --  Not needed inside generic
1672
1673          Inside_A_Generic
1674
1675          --  Not needed if previous error
1676
1677          or else Target_Typ = Any_Type
1678          or else Nkind (Expr) = N_Error
1679
1680          --  Not needed for non-scalar type
1681
1682          or else not Is_Scalar_Type (Target_Typ)
1683
1684          --  Not needed if we know node raises CE already
1685
1686          or else Raises_Constraint_Error (Expr)
1687       then
1688          return;
1689       end if;
1690
1691       --  Now, see if checks are suppressed
1692
1693       Is_Subscr_Ref :=
1694         Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
1695
1696       if Is_Subscr_Ref then
1697          Arr := Prefix (Parnt);
1698          Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
1699       end if;
1700
1701       if not Do_Range_Check (Expr) then
1702
1703          --  Subscript reference. Check for Index_Checks suppressed
1704
1705          if Is_Subscr_Ref then
1706
1707             --  Check array type and its base type
1708
1709             if Index_Checks_Suppressed (Arr_Typ)
1710               or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
1711             then
1712                return;
1713
1714             --  Check array itself if it is an entity name
1715
1716             elsif Is_Entity_Name (Arr)
1717               and then Index_Checks_Suppressed (Entity (Arr))
1718             then
1719                return;
1720
1721             --  Check expression itself if it is an entity name
1722
1723             elsif Is_Entity_Name (Expr)
1724               and then Index_Checks_Suppressed (Entity (Expr))
1725             then
1726                return;
1727             end if;
1728
1729          --  All other cases, check for Range_Checks suppressed
1730
1731          else
1732             --  Check target type and its base type
1733
1734             if Range_Checks_Suppressed (Target_Typ)
1735               or else Range_Checks_Suppressed (Base_Type (Target_Typ))
1736             then
1737                return;
1738
1739             --  Check expression itself if it is an entity name
1740
1741             elsif Is_Entity_Name (Expr)
1742               and then Range_Checks_Suppressed (Entity (Expr))
1743             then
1744                return;
1745
1746             --  If Expr is part of an assignment statement, then check left
1747             --  side of assignment if it is an entity name.
1748
1749             elsif Nkind (Parnt) = N_Assignment_Statement
1750               and then Is_Entity_Name (Name (Parnt))
1751               and then Range_Checks_Suppressed (Entity (Name (Parnt)))
1752             then
1753                return;
1754             end if;
1755          end if;
1756       end if;
1757
1758       --  Do not set range checks if they are killed
1759
1760       if Nkind (Expr) = N_Unchecked_Type_Conversion
1761         and then Kill_Range_Check (Expr)
1762       then
1763          return;
1764       end if;
1765
1766       --  Do not set range checks for any values from System.Scalar_Values
1767       --  since the whole idea of such values is to avoid checking them!
1768
1769       if Is_Entity_Name (Expr)
1770         and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
1771       then
1772          return;
1773       end if;
1774
1775       --  Now see if we need a check
1776
1777       if No (Source_Typ) then
1778          S_Typ := Etype (Expr);
1779       else
1780          S_Typ := Source_Typ;
1781       end if;
1782
1783       if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
1784          return;
1785       end if;
1786
1787       Is_Unconstrained_Subscr_Ref :=
1788         Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
1789
1790       --  Always do a range check if the source type includes infinities and
1791       --  the target type does not include infinities. We do not do this if
1792       --  range checks are killed.
1793
1794       if Is_Floating_Point_Type (S_Typ)
1795         and then Has_Infinities (S_Typ)
1796         and then not Has_Infinities (Target_Typ)
1797       then
1798          Enable_Range_Check (Expr);
1799       end if;
1800
1801       --  Return if we know expression is definitely in the range of the target
1802       --  type as determined by Determine_Range. Right now we only do this for
1803       --  discrete types, and not fixed-point or floating-point types.
1804
1805       --  The additional less-precise tests below catch these cases
1806
1807       --  Note: skip this if we are given a source_typ, since the point of
1808       --  supplying a Source_Typ is to stop us looking at the expression.
1809       --  We could sharpen this test to be out parameters only ???
1810
1811       if Is_Discrete_Type (Target_Typ)
1812         and then Is_Discrete_Type (Etype (Expr))
1813         and then not Is_Unconstrained_Subscr_Ref
1814         and then No (Source_Typ)
1815       then
1816          declare
1817             Tlo : constant Node_Id := Type_Low_Bound  (Target_Typ);
1818             Thi : constant Node_Id := Type_High_Bound (Target_Typ);
1819             Lo  : Uint;
1820             Hi  : Uint;
1821
1822          begin
1823             if Compile_Time_Known_Value (Tlo)
1824               and then Compile_Time_Known_Value (Thi)
1825             then
1826                declare
1827                   Lov : constant Uint := Expr_Value (Tlo);
1828                   Hiv : constant Uint := Expr_Value (Thi);
1829
1830                begin
1831                   --  If range is null, we for sure have a constraint error
1832                   --  (we don't even need to look at the value involved,
1833                   --  since all possible values will raise CE).
1834
1835                   if Lov > Hiv then
1836                      Bad_Value;
1837                      return;
1838                   end if;
1839
1840                   --  Otherwise determine range of value
1841
1842                   Determine_Range (Expr, OK, Lo, Hi);
1843
1844                   if OK then
1845
1846                      --  If definitely in range, all OK
1847
1848                      if Lo >= Lov and then Hi <= Hiv then
1849                         return;
1850
1851                      --  If definitely not in range, warn
1852
1853                      elsif Lov > Hi or else Hiv < Lo then
1854                         Bad_Value;
1855                         return;
1856
1857                      --  Otherwise we don't know
1858
1859                      else
1860                         null;
1861                      end if;
1862                   end if;
1863                end;
1864             end if;
1865          end;
1866       end if;
1867
1868       Int_Real :=
1869         Is_Floating_Point_Type (S_Typ)
1870           or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
1871
1872       --  Check if we can determine at compile time whether Expr is in the
1873       --  range of the target type. Note that if S_Typ is within the bounds
1874       --  of Target_Typ then this must be the case. This check is meaningful
1875       --  only if this is not a conversion between integer and real types.
1876
1877       if not Is_Unconstrained_Subscr_Ref
1878         and then
1879            Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
1880         and then
1881           (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
1882              or else
1883            Is_In_Range (Expr, Target_Typ, Fixed_Int, Int_Real))
1884       then
1885          return;
1886
1887       elsif Is_Out_Of_Range (Expr, Target_Typ, Fixed_Int, Int_Real) then
1888          Bad_Value;
1889          return;
1890
1891       --  In the floating-point case, we only do range checks if the type is
1892       --  constrained. We definitely do NOT want range checks for unconstrained
1893       --  types, since we want to have infinities
1894
1895       elsif Is_Floating_Point_Type (S_Typ) then
1896          if Is_Constrained (S_Typ) then
1897             Enable_Range_Check (Expr);
1898          end if;
1899
1900       --  For all other cases we enable a range check unconditionally
1901
1902       else
1903          Enable_Range_Check (Expr);
1904          return;
1905       end if;
1906    end Apply_Scalar_Range_Check;
1907
1908    ----------------------------------
1909    -- Apply_Selected_Length_Checks --
1910    ----------------------------------
1911
1912    procedure Apply_Selected_Length_Checks
1913      (Ck_Node    : Node_Id;
1914       Target_Typ : Entity_Id;
1915       Source_Typ : Entity_Id;
1916       Do_Static  : Boolean)
1917    is
1918       Cond     : Node_Id;
1919       R_Result : Check_Result;
1920       R_Cno    : Node_Id;
1921
1922       Loc         : constant Source_Ptr := Sloc (Ck_Node);
1923       Checks_On   : constant Boolean :=
1924                       (not Index_Checks_Suppressed (Target_Typ))
1925                         or else
1926                       (not Length_Checks_Suppressed (Target_Typ));
1927
1928    begin
1929       if not Expander_Active then
1930          return;
1931       end if;
1932
1933       R_Result :=
1934         Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
1935
1936       for J in 1 .. 2 loop
1937          R_Cno := R_Result (J);
1938          exit when No (R_Cno);
1939
1940          --  A length check may mention an Itype which is attached to a
1941          --  subsequent node. At the top level in a package this can cause
1942          --  an order-of-elaboration problem, so we make sure that the itype
1943          --  is referenced now.
1944
1945          if Ekind (Current_Scope) = E_Package
1946            and then Is_Compilation_Unit (Current_Scope)
1947          then
1948             Ensure_Defined (Target_Typ, Ck_Node);
1949
1950             if Present (Source_Typ) then
1951                Ensure_Defined (Source_Typ, Ck_Node);
1952
1953             elsif Is_Itype (Etype (Ck_Node)) then
1954                Ensure_Defined (Etype (Ck_Node), Ck_Node);
1955             end if;
1956          end if;
1957
1958          --  If the item is a conditional raise of constraint error, then have
1959          --  a look at what check is being performed and ???
1960
1961          if Nkind (R_Cno) = N_Raise_Constraint_Error
1962            and then Present (Condition (R_Cno))
1963          then
1964             Cond := Condition (R_Cno);
1965
1966             --  Case where node does not now have a dynamic check
1967
1968             if not Has_Dynamic_Length_Check (Ck_Node) then
1969
1970                --  If checks are on, just insert the check
1971
1972                if Checks_On then
1973                   Insert_Action (Ck_Node, R_Cno);
1974
1975                   if not Do_Static then
1976                      Set_Has_Dynamic_Length_Check (Ck_Node);
1977                   end if;
1978
1979                --  If checks are off, then analyze the length check after
1980                --  temporarily attaching it to the tree in case the relevant
1981                --  condition can be evaluted at compile time. We still want a
1982                --  compile time warning in this case.
1983
1984                else
1985                   Set_Parent (R_Cno, Ck_Node);
1986                   Analyze (R_Cno);
1987                end if;
1988             end if;
1989
1990             --  Output a warning if the condition is known to be True
1991
1992             if Is_Entity_Name (Cond)
1993               and then Entity (Cond) = Standard_True
1994             then
1995                Apply_Compile_Time_Constraint_Error
1996                  (Ck_Node, "wrong length for array of}?",
1997                   CE_Length_Check_Failed,
1998                   Ent => Target_Typ,
1999                   Typ => Target_Typ);
2000
2001             --  If we were only doing a static check, or if checks are not
2002             --  on, then we want to delete the check, since it is not needed.
2003             --  We do this by replacing the if statement by a null statement
2004
2005             elsif Do_Static or else not Checks_On then
2006                Remove_Warning_Messages (R_Cno);
2007                Rewrite (R_Cno, Make_Null_Statement (Loc));
2008             end if;
2009
2010          else
2011             Install_Static_Check (R_Cno, Loc);
2012          end if;
2013       end loop;
2014    end Apply_Selected_Length_Checks;
2015
2016    ---------------------------------
2017    -- Apply_Selected_Range_Checks --
2018    ---------------------------------
2019
2020    procedure Apply_Selected_Range_Checks
2021      (Ck_Node    : Node_Id;
2022       Target_Typ : Entity_Id;
2023       Source_Typ : Entity_Id;
2024       Do_Static  : Boolean)
2025    is
2026       Cond     : Node_Id;
2027       R_Result : Check_Result;
2028       R_Cno    : Node_Id;
2029
2030       Loc       : constant Source_Ptr := Sloc (Ck_Node);
2031       Checks_On : constant Boolean :=
2032                     (not Index_Checks_Suppressed (Target_Typ))
2033                       or else
2034                     (not Range_Checks_Suppressed (Target_Typ));
2035
2036    begin
2037       if not Expander_Active or else not Checks_On then
2038          return;
2039       end if;
2040
2041       R_Result :=
2042         Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2043
2044       for J in 1 .. 2 loop
2045
2046          R_Cno := R_Result (J);
2047          exit when No (R_Cno);
2048
2049          --  If the item is a conditional raise of constraint error, then have
2050          --  a look at what check is being performed and ???
2051
2052          if Nkind (R_Cno) = N_Raise_Constraint_Error
2053            and then Present (Condition (R_Cno))
2054          then
2055             Cond := Condition (R_Cno);
2056
2057             if not Has_Dynamic_Range_Check (Ck_Node) then
2058                Insert_Action (Ck_Node, R_Cno);
2059
2060                if not Do_Static then
2061                   Set_Has_Dynamic_Range_Check (Ck_Node);
2062                end if;
2063             end if;
2064
2065             --  Output a warning if the condition is known to be True
2066
2067             if Is_Entity_Name (Cond)
2068               and then Entity (Cond) = Standard_True
2069             then
2070                --  Since an N_Range is technically not an expression, we have
2071                --  to set one of the bounds to C_E and then just flag the
2072                --  N_Range. The warning message will point to the lower bound
2073                --  and complain about a range, which seems OK.
2074
2075                if Nkind (Ck_Node) = N_Range then
2076                   Apply_Compile_Time_Constraint_Error
2077                     (Low_Bound (Ck_Node), "static range out of bounds of}?",
2078                      CE_Range_Check_Failed,
2079                      Ent => Target_Typ,
2080                      Typ => Target_Typ);
2081
2082                   Set_Raises_Constraint_Error (Ck_Node);
2083
2084                else
2085                   Apply_Compile_Time_Constraint_Error
2086                     (Ck_Node, "static value out of range of}?",
2087                      CE_Range_Check_Failed,
2088                      Ent => Target_Typ,
2089                      Typ => Target_Typ);
2090                end if;
2091
2092             --  If we were only doing a static check, or if checks are not
2093             --  on, then we want to delete the check, since it is not needed.
2094             --  We do this by replacing the if statement by a null statement
2095
2096             elsif Do_Static or else not Checks_On then
2097                Remove_Warning_Messages (R_Cno);
2098                Rewrite (R_Cno, Make_Null_Statement (Loc));
2099             end if;
2100
2101          else
2102             Install_Static_Check (R_Cno, Loc);
2103          end if;
2104       end loop;
2105    end Apply_Selected_Range_Checks;
2106
2107    -------------------------------
2108    -- Apply_Static_Length_Check --
2109    -------------------------------
2110
2111    procedure Apply_Static_Length_Check
2112      (Expr       : Node_Id;
2113       Target_Typ : Entity_Id;
2114       Source_Typ : Entity_Id := Empty)
2115    is
2116    begin
2117       Apply_Selected_Length_Checks
2118         (Expr, Target_Typ, Source_Typ, Do_Static => True);
2119    end Apply_Static_Length_Check;
2120
2121    -------------------------------------
2122    -- Apply_Subscript_Validity_Checks --
2123    -------------------------------------
2124
2125    procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
2126       Sub : Node_Id;
2127
2128    begin
2129       pragma Assert (Nkind (Expr) = N_Indexed_Component);
2130
2131       --  Loop through subscripts
2132
2133       Sub := First (Expressions (Expr));
2134       while Present (Sub) loop
2135
2136          --  Check one subscript. Note that we do not worry about enumeration
2137          --  type with holes, since we will convert the value to a Pos value
2138          --  for the subscript, and that convert will do the necessary validity
2139          --  check.
2140
2141          Ensure_Valid (Sub, Holes_OK => True);
2142
2143          --  Move to next subscript
2144
2145          Sub := Next (Sub);
2146       end loop;
2147    end Apply_Subscript_Validity_Checks;
2148
2149    ----------------------------------
2150    -- Apply_Type_Conversion_Checks --
2151    ----------------------------------
2152
2153    procedure Apply_Type_Conversion_Checks (N : Node_Id) is
2154       Target_Type : constant Entity_Id := Etype (N);
2155       Target_Base : constant Entity_Id := Base_Type (Target_Type);
2156       Expr        : constant Node_Id   := Expression (N);
2157       Expr_Type   : constant Entity_Id := Etype (Expr);
2158
2159    begin
2160       if Inside_A_Generic then
2161          return;
2162
2163       --  Skip these checks if serious errors detected, there are some nasty
2164       --  situations of incomplete trees that blow things up.
2165
2166       elsif Serious_Errors_Detected > 0 then
2167          return;
2168
2169       --  Scalar type conversions of the form Target_Type (Expr) require a
2170       --  range check if we cannot be sure that Expr is in the base type of
2171       --  Target_Typ and also that Expr is in the range of Target_Typ. These
2172       --  are not quite the same condition from an implementation point of
2173       --  view, but clearly the second includes the first.
2174
2175       elsif Is_Scalar_Type (Target_Type) then
2176          declare
2177             Conv_OK  : constant Boolean := Conversion_OK (N);
2178             --  If the Conversion_OK flag on the type conversion is set and no
2179             --  floating point type is involved in the type conversion then
2180             --  fixed point values must be read as integral values.
2181
2182             Float_To_Int : constant Boolean :=
2183                              Is_Floating_Point_Type (Expr_Type)
2184                                and then Is_Integer_Type (Target_Type);
2185
2186          begin
2187             if not Overflow_Checks_Suppressed (Target_Base)
2188               and then not In_Subrange_Of (Expr_Type, Target_Base, Conv_OK)
2189               and then not Float_To_Int
2190             then
2191                Activate_Overflow_Check (N);
2192             end if;
2193
2194             if not Range_Checks_Suppressed (Target_Type)
2195               and then not Range_Checks_Suppressed (Expr_Type)
2196             then
2197                if Float_To_Int then
2198                   Apply_Float_Conversion_Check (Expr, Target_Type);
2199                else
2200                   Apply_Scalar_Range_Check
2201                     (Expr, Target_Type, Fixed_Int => Conv_OK);
2202                end if;
2203             end if;
2204          end;
2205
2206       elsif Comes_From_Source (N)
2207         and then Is_Record_Type (Target_Type)
2208         and then Is_Derived_Type (Target_Type)
2209         and then not Is_Tagged_Type (Target_Type)
2210         and then not Is_Constrained (Target_Type)
2211         and then Present (Stored_Constraint (Target_Type))
2212       then
2213          --  An unconstrained derived type may have inherited discriminant
2214          --  Build an actual discriminant constraint list using the stored
2215          --  constraint, to verify that the expression of the parent type
2216          --  satisfies the constraints imposed by the (unconstrained!)
2217          --  derived type. This applies to value conversions, not to view
2218          --  conversions of tagged types.
2219
2220          declare
2221             Loc         : constant Source_Ptr := Sloc (N);
2222             Cond        : Node_Id;
2223             Constraint  : Elmt_Id;
2224             Discr_Value : Node_Id;
2225             Discr       : Entity_Id;
2226
2227             New_Constraints : constant Elist_Id := New_Elmt_List;
2228             Old_Constraints : constant Elist_Id :=
2229                                 Discriminant_Constraint (Expr_Type);
2230
2231          begin
2232             Constraint := First_Elmt (Stored_Constraint (Target_Type));
2233             while Present (Constraint) loop
2234                Discr_Value := Node (Constraint);
2235
2236                if Is_Entity_Name (Discr_Value)
2237                  and then Ekind (Entity (Discr_Value)) = E_Discriminant
2238                then
2239                   Discr := Corresponding_Discriminant (Entity (Discr_Value));
2240
2241                   if Present (Discr)
2242                     and then Scope (Discr) = Base_Type (Expr_Type)
2243                   then
2244                      --  Parent is constrained by new discriminant. Obtain
2245                      --  Value of original discriminant in expression. If the
2246                      --  new discriminant has been used to constrain more than
2247                      --  one of the stored discriminants, this will provide the
2248                      --  required consistency check.
2249
2250                      Append_Elmt (
2251                         Make_Selected_Component (Loc,
2252                           Prefix =>
2253                             Duplicate_Subexpr_No_Checks
2254                               (Expr, Name_Req => True),
2255                           Selector_Name =>
2256                             Make_Identifier (Loc, Chars (Discr))),
2257                                 New_Constraints);
2258
2259                   else
2260                      --  Discriminant of more remote ancestor ???
2261
2262                      return;
2263                   end if;
2264
2265                --  Derived type definition has an explicit value for this
2266                --  stored discriminant.
2267
2268                else
2269                   Append_Elmt
2270                     (Duplicate_Subexpr_No_Checks (Discr_Value),
2271                      New_Constraints);
2272                end if;
2273
2274                Next_Elmt (Constraint);
2275             end loop;
2276
2277             --  Use the unconstrained expression type to retrieve the
2278             --  discriminants of the parent, and apply momentarily the
2279             --  discriminant constraint synthesized above.
2280
2281             Set_Discriminant_Constraint (Expr_Type, New_Constraints);
2282             Cond := Build_Discriminant_Checks (Expr, Expr_Type);
2283             Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
2284
2285             Insert_Action (N,
2286               Make_Raise_Constraint_Error (Loc,
2287                 Condition => Cond,
2288                 Reason    => CE_Discriminant_Check_Failed));
2289          end;
2290
2291       --  For arrays, conversions are applied during expansion, to take into
2292       --  accounts changes of representation. The checks become range checks on
2293       --  the base type or length checks on the subtype, depending on whether
2294       --  the target type is unconstrained or constrained.
2295
2296       else
2297          null;
2298       end if;
2299    end Apply_Type_Conversion_Checks;
2300
2301    ----------------------------------------------
2302    -- Apply_Universal_Integer_Attribute_Checks --
2303    ----------------------------------------------
2304
2305    procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
2306       Loc : constant Source_Ptr := Sloc (N);
2307       Typ : constant Entity_Id  := Etype (N);
2308
2309    begin
2310       if Inside_A_Generic then
2311          return;
2312
2313       --  Nothing to do if checks are suppressed
2314
2315       elsif Range_Checks_Suppressed (Typ)
2316         and then Overflow_Checks_Suppressed (Typ)
2317       then
2318          return;
2319
2320       --  Nothing to do if the attribute does not come from source. The
2321       --  internal attributes we generate of this type do not need checks,
2322       --  and furthermore the attempt to check them causes some circular
2323       --  elaboration orders when dealing with packed types.
2324
2325       elsif not Comes_From_Source (N) then
2326          return;
2327
2328       --  If the prefix is a selected component that depends on a discriminant
2329       --  the check may improperly expose a discriminant instead of using
2330       --  the bounds of the object itself. Set the type of the attribute to
2331       --  the base type of the context, so that a check will be imposed when
2332       --  needed (e.g. if the node appears as an index).
2333
2334       elsif Nkind (Prefix (N)) = N_Selected_Component
2335         and then Ekind (Typ) = E_Signed_Integer_Subtype
2336         and then Depends_On_Discriminant (Scalar_Range (Typ))
2337       then
2338          Set_Etype (N, Base_Type (Typ));
2339
2340       --  Otherwise, replace the attribute node with a type conversion node
2341       --  whose expression is the attribute, retyped to universal integer, and
2342       --  whose subtype mark is the target type. The call to analyze this
2343       --  conversion will set range and overflow checks as required for proper
2344       --  detection of an out of range value.
2345
2346       else
2347          Set_Etype    (N, Universal_Integer);
2348          Set_Analyzed (N, True);
2349
2350          Rewrite (N,
2351            Make_Type_Conversion (Loc,
2352              Subtype_Mark => New_Occurrence_Of (Typ, Loc),
2353              Expression   => Relocate_Node (N)));
2354
2355          Analyze_And_Resolve (N, Typ);
2356          return;
2357       end if;
2358
2359    end Apply_Universal_Integer_Attribute_Checks;
2360
2361    -------------------------------
2362    -- Build_Discriminant_Checks --
2363    -------------------------------
2364
2365    function Build_Discriminant_Checks
2366      (N     : Node_Id;
2367       T_Typ : Entity_Id) return Node_Id
2368    is
2369       Loc      : constant Source_Ptr := Sloc (N);
2370       Cond     : Node_Id;
2371       Disc     : Elmt_Id;
2372       Disc_Ent : Entity_Id;
2373       Dref     : Node_Id;
2374       Dval     : Node_Id;
2375
2376       function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
2377
2378       ----------------------------------
2379       -- Aggregate_Discriminant_Value --
2380       ----------------------------------
2381
2382       function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
2383          Assoc : Node_Id;
2384
2385       begin
2386          --  The aggregate has been normalized with named associations. We use
2387          --  the Chars field to locate the discriminant to take into account
2388          --  discriminants in derived types, which carry the same name as those
2389          --  in the parent.
2390
2391          Assoc := First (Component_Associations (N));
2392          while Present (Assoc) loop
2393             if Chars (First (Choices (Assoc))) = Chars (Disc) then
2394                return Expression (Assoc);
2395             else
2396                Next (Assoc);
2397             end if;
2398          end loop;
2399
2400          --  Discriminant must have been found in the loop above
2401
2402          raise Program_Error;
2403       end Aggregate_Discriminant_Val;
2404
2405    --  Start of processing for Build_Discriminant_Checks
2406
2407    begin
2408       --  Loop through discriminants evolving the condition
2409
2410       Cond := Empty;
2411       Disc := First_Elmt (Discriminant_Constraint (T_Typ));
2412
2413       --  For a fully private type, use the discriminants of the parent type
2414
2415       if Is_Private_Type (T_Typ)
2416         and then No (Full_View (T_Typ))
2417       then
2418          Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
2419       else
2420          Disc_Ent := First_Discriminant (T_Typ);
2421       end if;
2422
2423       while Present (Disc) loop
2424          Dval := Node (Disc);
2425
2426          if Nkind (Dval) = N_Identifier
2427            and then Ekind (Entity (Dval)) = E_Discriminant
2428          then
2429             Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
2430          else
2431             Dval := Duplicate_Subexpr_No_Checks (Dval);
2432          end if;
2433
2434          --  If we have an Unchecked_Union node, we can infer the discriminants
2435          --  of the node.
2436
2437          if Is_Unchecked_Union (Base_Type (T_Typ)) then
2438             Dref := New_Copy (
2439               Get_Discriminant_Value (
2440                 First_Discriminant (T_Typ),
2441                 T_Typ,
2442                 Stored_Constraint (T_Typ)));
2443
2444          elsif Nkind (N) = N_Aggregate then
2445             Dref :=
2446                Duplicate_Subexpr_No_Checks
2447                  (Aggregate_Discriminant_Val (Disc_Ent));
2448
2449          else
2450             Dref :=
2451               Make_Selected_Component (Loc,
2452                 Prefix =>
2453                   Duplicate_Subexpr_No_Checks (N, Name_Req => True),
2454                 Selector_Name =>
2455                   Make_Identifier (Loc, Chars (Disc_Ent)));
2456
2457             Set_Is_In_Discriminant_Check (Dref);
2458          end if;
2459
2460          Evolve_Or_Else (Cond,
2461            Make_Op_Ne (Loc,
2462              Left_Opnd => Dref,
2463              Right_Opnd => Dval));
2464
2465          Next_Elmt (Disc);
2466          Next_Discriminant (Disc_Ent);
2467       end loop;
2468
2469       return Cond;
2470    end Build_Discriminant_Checks;
2471
2472    ------------------
2473    -- Check_Needed --
2474    ------------------
2475
2476    function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
2477       N : Node_Id;
2478       P : Node_Id;
2479       K : Node_Kind;
2480       L : Node_Id;
2481       R : Node_Id;
2482
2483    begin
2484       --  Always check if not simple entity
2485
2486       if Nkind (Nod) not in N_Has_Entity
2487         or else not Comes_From_Source (Nod)
2488       then
2489          return True;
2490       end if;
2491
2492       --  Look up tree for short circuit
2493
2494       N := Nod;
2495       loop
2496          P := Parent (N);
2497          K := Nkind (P);
2498
2499          if K not in N_Subexpr then
2500             return True;
2501
2502          --  Or/Or Else case, left operand must be equality test
2503
2504          elsif K = N_Op_Or or else K = N_Or_Else then
2505             exit when N = Right_Opnd (P)
2506               and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2507
2508          --  And/And then case, left operand must be inequality test
2509
2510          elsif K = N_Op_And or else K = N_And_Then then
2511             exit when N = Right_Opnd (P)
2512               and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2513          end if;
2514
2515          N := P;
2516       end loop;
2517
2518       --  If we fall through the loop, then we have a conditional with an
2519       --  appropriate test as its left operand. So test further.
2520
2521       L := Left_Opnd (P);
2522
2523       if Nkind (L) = N_Op_Not then
2524          L := Right_Opnd (L);
2525       end if;
2526
2527       R := Right_Opnd (L);
2528       L := Left_Opnd (L);
2529
2530       --  Left operand of test must match original variable
2531
2532       if Nkind (L) not in N_Has_Entity
2533         or else Entity (L) /= Entity (Nod)
2534       then
2535          return True;
2536       end if;
2537
2538       --  Right operand of test must be key value (zero or null)
2539
2540       case Check is
2541          when Access_Check =>
2542             if not Known_Null (R) then
2543                return True;
2544             end if;
2545
2546          when Division_Check =>
2547             if not Compile_Time_Known_Value (R)
2548               or else Expr_Value (R) /= Uint_0
2549             then
2550                return True;
2551             end if;
2552
2553          when others =>
2554             raise Program_Error;
2555       end case;
2556
2557       --  Here we have the optimizable case, warn if not short-circuited
2558
2559       if K = N_Op_And or else K = N_Op_Or then
2560          case Check is
2561             when Access_Check =>
2562                Error_Msg_N
2563                  ("Constraint_Error may be raised (access check)?",
2564                   Parent (Nod));
2565             when Division_Check =>
2566                Error_Msg_N
2567                  ("Constraint_Error may be raised (zero divide)?",
2568                   Parent (Nod));
2569
2570             when others =>
2571                raise Program_Error;
2572          end case;
2573
2574          if K = N_Op_And then
2575             Error_Msg_N ("use `AND THEN` instead of AND?", P);
2576          else
2577             Error_Msg_N ("use `OR ELSE` instead of OR?", P);
2578          end if;
2579
2580          --  If not short-circuited, we need the ckeck
2581
2582          return True;
2583
2584       --  If short-circuited, we can omit the check
2585
2586       else
2587          return False;
2588       end if;
2589    end Check_Needed;
2590
2591    -----------------------------------
2592    -- Check_Valid_Lvalue_Subscripts --
2593    -----------------------------------
2594
2595    procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
2596    begin
2597       --  Skip this if range checks are suppressed
2598
2599       if Range_Checks_Suppressed (Etype (Expr)) then
2600          return;
2601
2602       --  Only do this check for expressions that come from source. We assume
2603       --  that expander generated assignments explicitly include any necessary
2604       --  checks. Note that this is not just an optimization, it avoids
2605       --  infinite recursions!
2606
2607       elsif not Comes_From_Source (Expr) then
2608          return;
2609
2610       --  For a selected component, check the prefix
2611
2612       elsif Nkind (Expr) = N_Selected_Component then
2613          Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2614          return;
2615
2616       --  Case of indexed component
2617
2618       elsif Nkind (Expr) = N_Indexed_Component then
2619          Apply_Subscript_Validity_Checks (Expr);
2620
2621          --  Prefix may itself be or contain an indexed component, and these
2622          --  subscripts need checking as well.
2623
2624          Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2625       end if;
2626    end Check_Valid_Lvalue_Subscripts;
2627
2628    ----------------------------------
2629    -- Null_Exclusion_Static_Checks --
2630    ----------------------------------
2631
2632    procedure Null_Exclusion_Static_Checks (N : Node_Id) is
2633       Error_Node : Node_Id;
2634       Expr       : Node_Id;
2635       Has_Null   : constant Boolean := Has_Null_Exclusion (N);
2636       K          : constant Node_Kind := Nkind (N);
2637       Typ        : Entity_Id;
2638
2639    begin
2640       pragma Assert
2641         (K = N_Component_Declaration
2642            or else K = N_Discriminant_Specification
2643            or else K = N_Function_Specification
2644            or else K = N_Object_Declaration
2645            or else K = N_Parameter_Specification);
2646
2647       if K = N_Function_Specification then
2648          Typ := Etype (Defining_Entity (N));
2649       else
2650          Typ := Etype (Defining_Identifier (N));
2651       end if;
2652
2653       case K is
2654          when N_Component_Declaration =>
2655             if Present (Access_Definition (Component_Definition (N))) then
2656                Error_Node := Component_Definition (N);
2657             else
2658                Error_Node := Subtype_Indication (Component_Definition (N));
2659             end if;
2660
2661          when N_Discriminant_Specification =>
2662             Error_Node    := Discriminant_Type (N);
2663
2664          when N_Function_Specification =>
2665             Error_Node    := Result_Definition (N);
2666
2667          when N_Object_Declaration =>
2668             Error_Node    := Object_Definition (N);
2669
2670          when N_Parameter_Specification =>
2671             Error_Node    := Parameter_Type (N);
2672
2673          when others =>
2674             raise Program_Error;
2675       end case;
2676
2677       if Has_Null then
2678
2679          --  Enforce legality rule 3.10 (13): A null exclusion can only be
2680          --  applied to an access [sub]type.
2681
2682          if not Is_Access_Type (Typ) then
2683             Error_Msg_N
2684               ("`NOT NULL` allowed only for an access type", Error_Node);
2685
2686          --  Enforce legality rule RM 3.10(14/1): A null exclusion can only
2687          --  be applied to a [sub]type that does not exclude null already.
2688
2689          elsif Can_Never_Be_Null (Typ)
2690
2691             --  No need to check itypes that have a null exclusion because
2692             --  they are already examined at their point of creation.
2693
2694            and then not Is_Itype (Typ)
2695          then
2696             Error_Msg_NE
2697               ("`NOT NULL` not allowed (& already excludes null)",
2698                Error_Node, Typ);
2699          end if;
2700       end if;
2701
2702       --  Check that null-excluding objects are always initialized
2703
2704       if K = N_Object_Declaration
2705         and then No (Expression (N))
2706         and then not No_Initialization (N)
2707       then
2708          --  Add an expression that assigns null. This node is needed by
2709          --  Apply_Compile_Time_Constraint_Error, which will replace this with
2710          --  a Constraint_Error node.
2711
2712          Set_Expression (N, Make_Null (Sloc (N)));
2713          Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
2714
2715          Apply_Compile_Time_Constraint_Error
2716            (N      => Expression (N),
2717             Msg    => "(Ada 2005) null-excluding objects must be initialized?",
2718             Reason => CE_Null_Not_Allowed);
2719       end if;
2720
2721       --  Check that a null-excluding component, formal or object is not
2722       --  being assigned a null value. Otherwise generate a warning message
2723       --  and replace Expression (N) by a N_Contraint_Error node.
2724
2725       if K /= N_Function_Specification then
2726          Expr := Expression (N);
2727
2728          if Present (Expr) and then Known_Null (Expr) then
2729             case K is
2730                when N_Component_Declaration      |
2731                     N_Discriminant_Specification =>
2732                   Apply_Compile_Time_Constraint_Error
2733                     (N      => Expr,
2734                      Msg    => "(Ada 2005) null not allowed " &
2735                                "in null-excluding components?",
2736                      Reason => CE_Null_Not_Allowed);
2737
2738                when N_Object_Declaration =>
2739                   Apply_Compile_Time_Constraint_Error
2740                     (N      => Expr,
2741                      Msg    => "(Ada 2005) null not allowed " &
2742                                "in null-excluding objects?",
2743                      Reason => CE_Null_Not_Allowed);
2744
2745                when N_Parameter_Specification =>
2746                   Apply_Compile_Time_Constraint_Error
2747                     (N      => Expr,
2748                      Msg    => "(Ada 2005) null not allowed " &
2749                                "in null-excluding formals?",
2750                      Reason => CE_Null_Not_Allowed);
2751
2752                when others =>
2753                   null;
2754             end case;
2755          end if;
2756       end if;
2757    end Null_Exclusion_Static_Checks;
2758
2759    ----------------------------------
2760    -- Conditional_Statements_Begin --
2761    ----------------------------------
2762
2763    procedure Conditional_Statements_Begin is
2764    begin
2765       Saved_Checks_TOS := Saved_Checks_TOS + 1;
2766
2767       --  If stack overflows, kill all checks, that way we know to simply reset
2768       --  the number of saved checks to zero on return. This should never occur
2769       --  in practice.
2770
2771       if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2772          Kill_All_Checks;
2773
2774       --  In the normal case, we just make a new stack entry saving the current
2775       --  number of saved checks for a later restore.
2776
2777       else
2778          Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
2779
2780          if Debug_Flag_CC then
2781             w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
2782                Num_Saved_Checks);
2783          end if;
2784       end if;
2785    end Conditional_Statements_Begin;
2786
2787    --------------------------------
2788    -- Conditional_Statements_End --
2789    --------------------------------
2790
2791    procedure Conditional_Statements_End is
2792    begin
2793       pragma Assert (Saved_Checks_TOS > 0);
2794
2795       --  If the saved checks stack overflowed, then we killed all checks, so
2796       --  setting the number of saved checks back to zero is correct. This
2797       --  should never occur in practice.
2798
2799       if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2800          Num_Saved_Checks := 0;
2801
2802       --  In the normal case, restore the number of saved checks from the top
2803       --  stack entry.
2804
2805       else
2806          Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
2807          if Debug_Flag_CC then
2808             w ("Conditional_Statements_End: Num_Saved_Checks = ",
2809                Num_Saved_Checks);
2810          end if;
2811       end if;
2812
2813       Saved_Checks_TOS := Saved_Checks_TOS - 1;
2814    end Conditional_Statements_End;
2815
2816    ---------------------
2817    -- Determine_Range --
2818    ---------------------
2819
2820    Cache_Size : constant := 2 ** 10;
2821    type Cache_Index is range 0 .. Cache_Size - 1;
2822    --  Determine size of below cache (power of 2 is more efficient!)
2823
2824    Determine_Range_Cache_N  : array (Cache_Index) of Node_Id;
2825    Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
2826    Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
2827    --  The above arrays are used to implement a small direct cache for
2828    --  Determine_Range calls. Because of the way Determine_Range recursively
2829    --  traces subexpressions, and because overflow checking calls the routine
2830    --  on the way up the tree, a quadratic behavior can otherwise be
2831    --  encountered in large expressions. The cache entry for node N is stored
2832    --  in the (N mod Cache_Size) entry, and can be validated by checking the
2833    --  actual node value stored there.
2834
2835    procedure Determine_Range
2836      (N  : Node_Id;
2837       OK : out Boolean;
2838       Lo : out Uint;
2839       Hi : out Uint)
2840    is
2841       Typ : constant Entity_Id := Etype (N);
2842
2843       Lo_Left : Uint;
2844       Hi_Left : Uint;
2845       --  Lo and Hi bounds of left operand
2846
2847       Lo_Right : Uint;
2848       Hi_Right : Uint;
2849       --  Lo and Hi bounds of right (or only) operand
2850
2851       Bound : Node_Id;
2852       --  Temp variable used to hold a bound node
2853
2854       Hbound : Uint;
2855       --  High bound of base type of expression
2856
2857       Lor : Uint;
2858       Hir : Uint;
2859       --  Refined values for low and high bounds, after tightening
2860
2861       OK1 : Boolean;
2862       --  Used in lower level calls to indicate if call succeeded
2863
2864       Cindex : Cache_Index;
2865       --  Used to search cache
2866
2867       function OK_Operands return Boolean;
2868       --  Used for binary operators. Determines the ranges of the left and
2869       --  right operands, and if they are both OK, returns True, and puts
2870       --  the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left
2871
2872       -----------------
2873       -- OK_Operands --
2874       -----------------
2875
2876       function OK_Operands return Boolean is
2877       begin
2878          Determine_Range (Left_Opnd  (N), OK1, Lo_Left,  Hi_Left);
2879
2880          if not OK1 then
2881             return False;
2882          end if;
2883
2884          Determine_Range (Right_Opnd (N), OK1, Lo_Right, Hi_Right);
2885          return OK1;
2886       end OK_Operands;
2887
2888    --  Start of processing for Determine_Range
2889
2890    begin
2891       --  Prevent junk warnings by initializing range variables
2892
2893       Lo  := No_Uint;
2894       Hi  := No_Uint;
2895       Lor := No_Uint;
2896       Hir := No_Uint;
2897
2898       --  If the type is not discrete, or is undefined, then we can't do
2899       --  anything about determining the range.
2900
2901       if No (Typ) or else not Is_Discrete_Type (Typ)
2902         or else Error_Posted (N)
2903       then
2904          OK := False;
2905          return;
2906       end if;
2907
2908       --  For all other cases, we can determine the range
2909
2910       OK := True;
2911
2912       --  If value is compile time known, then the possible range is the one
2913       --  value that we know this expression definitely has!
2914
2915       if Compile_Time_Known_Value (N) then
2916          Lo := Expr_Value (N);
2917          Hi := Lo;
2918          return;
2919       end if;
2920
2921       --  Return if already in the cache
2922
2923       Cindex := Cache_Index (N mod Cache_Size);
2924
2925       if Determine_Range_Cache_N (Cindex) = N then
2926          Lo := Determine_Range_Cache_Lo (Cindex);
2927          Hi := Determine_Range_Cache_Hi (Cindex);
2928          return;
2929       end if;
2930
2931       --  Otherwise, start by finding the bounds of the type of the expression,
2932       --  the value cannot be outside this range (if it is, then we have an
2933       --  overflow situation, which is a separate check, we are talking here
2934       --  only about the expression value).
2935
2936       --  We use the actual bound unless it is dynamic, in which case use the
2937       --  corresponding base type bound if possible. If we can't get a bound
2938       --  then we figure we can't determine the range (a peculiar case, that
2939       --  perhaps cannot happen, but there is no point in bombing in this
2940       --  optimization circuit.
2941
2942       --  First the low bound
2943
2944       Bound := Type_Low_Bound (Typ);
2945
2946       if Compile_Time_Known_Value (Bound) then
2947          Lo := Expr_Value (Bound);
2948
2949       elsif Compile_Time_Known_Value (Type_Low_Bound (Base_Type (Typ))) then
2950          Lo := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
2951
2952       else
2953          OK := False;
2954          return;
2955       end if;
2956
2957       --  Now the high bound
2958
2959       Bound := Type_High_Bound (Typ);
2960
2961       --  We need the high bound of the base type later on, and this should
2962       --  always be compile time known. Again, it is not clear that this
2963       --  can ever be false, but no point in bombing.
2964
2965       if Compile_Time_Known_Value (Type_High_Bound (Base_Type (Typ))) then
2966          Hbound := Expr_Value (Type_High_Bound (Base_Type (Typ)));
2967          Hi := Hbound;
2968
2969       else
2970          OK := False;
2971          return;
2972       end if;
2973
2974       --  If we have a static subtype, then that may have a tighter bound so
2975       --  use the upper bound of the subtype instead in this case.
2976
2977       if Compile_Time_Known_Value (Bound) then
2978          Hi := Expr_Value (Bound);
2979       end if;
2980
2981       --  We may be able to refine this value in certain situations. If any
2982       --  refinement is possible, then Lor and Hir are set to possibly tighter
2983       --  bounds, and OK1 is set to True.
2984
2985       case Nkind (N) is
2986
2987          --  For unary plus, result is limited by range of operand
2988
2989          when N_Op_Plus =>
2990             Determine_Range (Right_Opnd (N), OK1, Lor, Hir);
2991
2992          --  For unary minus, determine range of operand, and negate it
2993
2994          when N_Op_Minus =>
2995             Determine_Range (Right_Opnd (N), OK1, Lo_Right, Hi_Right);
2996
2997             if OK1 then
2998                Lor := -Hi_Right;
2999                Hir := -Lo_Right;
3000             end if;
3001
3002          --  For binary addition, get range of each operand and do the
3003          --  addition to get the result range.
3004
3005          when N_Op_Add =>
3006             if OK_Operands then
3007                Lor := Lo_Left + Lo_Right;
3008                Hir := Hi_Left + Hi_Right;
3009             end if;
3010
3011          --  Division is tricky. The only case we consider is where the right
3012          --  operand is a positive constant, and in this case we simply divide
3013          --  the bounds of the left operand
3014
3015          when N_Op_Divide =>
3016             if OK_Operands then
3017                if Lo_Right = Hi_Right
3018                  and then Lo_Right > 0
3019                then
3020                   Lor := Lo_Left / Lo_Right;
3021                   Hir := Hi_Left / Lo_Right;
3022
3023                else
3024                   OK1 := False;
3025                end if;
3026             end if;
3027
3028          --  For binary subtraction, get range of each operand and do the worst
3029          --  case subtraction to get the result range.
3030
3031          when N_Op_Subtract =>
3032             if OK_Operands then
3033                Lor := Lo_Left - Hi_Right;
3034                Hir := Hi_Left - Lo_Right;
3035             end if;
3036
3037          --  For MOD, if right operand is a positive constant, then result must
3038          --  be in the allowable range of mod results.
3039
3040          when N_Op_Mod =>
3041             if OK_Operands then
3042                if Lo_Right = Hi_Right
3043                  and then Lo_Right /= 0
3044                then
3045                   if Lo_Right > 0 then
3046                      Lor := Uint_0;
3047                      Hir := Lo_Right - 1;
3048
3049                   else -- Lo_Right < 0
3050                      Lor := Lo_Right + 1;
3051                      Hir := Uint_0;
3052                   end if;
3053
3054                else
3055                   OK1 := False;
3056                end if;
3057             end if;
3058
3059          --  For REM, if right operand is a positive constant, then result must
3060          --  be in the allowable range of mod results.
3061
3062          when N_Op_Rem =>
3063             if OK_Operands then
3064                if Lo_Right = Hi_Right
3065                  and then Lo_Right /= 0
3066                then
3067                   declare
3068                      Dval : constant Uint := (abs Lo_Right) - 1;
3069
3070                   begin
3071                      --  The sign of the result depends on the sign of the
3072                      --  dividend (but not on the sign of the divisor, hence
3073                      --  the abs operation above).
3074
3075                      if Lo_Left < 0 then
3076                         Lor := -Dval;
3077                      else
3078                         Lor := Uint_0;
3079                      end if;
3080
3081                      if Hi_Left < 0 then
3082                         Hir := Uint_0;
3083                      else
3084                         Hir := Dval;
3085                      end if;
3086                   end;
3087
3088                else
3089                   OK1 := False;
3090                end if;
3091             end if;
3092
3093          --  Attribute reference cases
3094
3095          when N_Attribute_Reference =>
3096             case Attribute_Name (N) is
3097
3098                --  For Pos/Val attributes, we can refine the range using the
3099                --  possible range of values of the attribute expression
3100
3101                when Name_Pos | Name_Val =>
3102                   Determine_Range (First (Expressions (N)), OK1, Lor, Hir);
3103
3104                --  For Length attribute, use the bounds of the corresponding
3105                --  index type to refine the range.
3106
3107                when Name_Length =>
3108                   declare
3109                      Atyp : Entity_Id := Etype (Prefix (N));
3110                      Inum : Nat;
3111                      Indx : Node_Id;
3112
3113                      LL, LU : Uint;
3114                      UL, UU : Uint;
3115
3116                   begin
3117                      if Is_Access_Type (Atyp) then
3118                         Atyp := Designated_Type (Atyp);
3119                      end if;
3120
3121                      --  For string literal, we know exact value
3122
3123                      if Ekind (Atyp) = E_String_Literal_Subtype then
3124                         OK := True;
3125                         Lo := String_Literal_Length (Atyp);
3126                         Hi := String_Literal_Length (Atyp);
3127                         return;
3128                      end if;
3129
3130                      --  Otherwise check for expression given
3131
3132                      if No (Expressions (N)) then
3133                         Inum := 1;
3134                      else
3135                         Inum :=
3136                           UI_To_Int (Expr_Value (First (Expressions (N))));
3137                      end if;
3138
3139                      Indx := First_Index (Atyp);
3140                      for J in 2 .. Inum loop
3141                         Indx := Next_Index (Indx);
3142                      end loop;
3143
3144                      Determine_Range
3145                        (Type_Low_Bound (Etype (Indx)), OK1, LL, LU);
3146
3147                      if OK1 then
3148                         Determine_Range
3149                           (Type_High_Bound (Etype (Indx)), OK1, UL, UU);
3150
3151                         if OK1 then
3152
3153                            --  The maximum value for Length is the biggest
3154                            --  possible gap between the values of the bounds.
3155                            --  But of course, this value cannot be negative.
3156
3157                            Hir := UI_Max (Uint_0, UU - LL);
3158
3159                            --  For constrained arrays, the minimum value for
3160                            --  Length is taken from the actual value of the
3161                            --  bounds, since the index will be exactly of
3162                            --  this subtype.
3163
3164                            if Is_Constrained (Atyp) then
3165                               Lor := UI_Max (Uint_0, UL - LU);
3166
3167                            --  For an unconstrained array, the minimum value
3168                            --  for length is always zero.
3169
3170                            else
3171                               Lor := Uint_0;
3172                            end if;
3173                         end if;
3174                      end if;
3175                   end;
3176
3177                --  No special handling for other attributes
3178                --  Probably more opportunities exist here ???
3179
3180                when others =>
3181                   OK1 := False;
3182
3183             end case;
3184
3185          --  For type conversion from one discrete type to another, we can
3186          --  refine the range using the converted value.
3187
3188          when N_Type_Conversion =>
3189             Determine_Range (Expression (N), OK1, Lor, Hir);
3190
3191          --  Nothing special to do for all other expression kinds
3192
3193          when others =>
3194             OK1 := False;
3195             Lor := No_Uint;
3196             Hir := No_Uint;
3197       end case;
3198
3199       --  At this stage, if OK1 is true, then we know that the actual
3200       --  result of the computed expression is in the range Lor .. Hir.
3201       --  We can use this to restrict the possible range of results.
3202
3203       if OK1 then
3204
3205          --  If the refined value of the low bound is greater than the
3206          --  type high bound, then reset it to the more restrictive
3207          --  value. However, we do NOT do this for the case of a modular
3208          --  type where the possible upper bound on the value is above the
3209          --  base type high bound, because that means the result could wrap.
3210
3211          if Lor > Lo
3212            and then not (Is_Modular_Integer_Type (Typ)
3213                            and then Hir > Hbound)
3214          then
3215             Lo := Lor;
3216          end if;
3217
3218          --  Similarly, if the refined value of the high bound is less
3219          --  than the value so far, then reset it to the more restrictive
3220          --  value. Again, we do not do this if the refined low bound is
3221          --  negative for a modular type, since this would wrap.
3222
3223          if Hir < Hi
3224            and then not (Is_Modular_Integer_Type (Typ)
3225                           and then Lor < Uint_0)
3226          then
3227             Hi := Hir;
3228          end if;
3229       end if;
3230
3231       --  Set cache entry for future call and we are all done
3232
3233       Determine_Range_Cache_N  (Cindex) := N;
3234       Determine_Range_Cache_Lo (Cindex) := Lo;
3235       Determine_Range_Cache_Hi (Cindex) := Hi;
3236       return;
3237
3238    --  If any exception occurs, it means that we have some bug in the compiler
3239    --  possibly triggered by a previous error, or by some unforseen peculiar
3240    --  occurrence. However, this is only an optimization attempt, so there is
3241    --  really no point in crashing the compiler. Instead we just decide, too
3242    --  bad, we can't figure out a range in this case after all.
3243
3244    exception
3245       when others =>
3246
3247          --  Debug flag K disables this behavior (useful for debugging)
3248
3249          if Debug_Flag_K then
3250             raise;
3251          else
3252             OK := False;
3253             Lo := No_Uint;
3254             Hi := No_Uint;
3255             return;
3256          end if;
3257    end Determine_Range;
3258
3259    ------------------------------------
3260    -- Discriminant_Checks_Suppressed --
3261    ------------------------------------
3262
3263    function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
3264    begin
3265       if Present (E) then
3266          if Is_Unchecked_Union (E) then
3267             return True;
3268          elsif Checks_May_Be_Suppressed (E) then
3269             return Is_Check_Suppressed (E, Discriminant_Check);
3270          end if;
3271       end if;
3272
3273       return Scope_Suppress (Discriminant_Check);
3274    end Discriminant_Checks_Suppressed;
3275
3276    --------------------------------
3277    -- Division_Checks_Suppressed --
3278    --------------------------------
3279
3280    function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
3281    begin
3282       if Present (E) and then Checks_May_Be_Suppressed (E) then
3283          return Is_Check_Suppressed (E, Division_Check);
3284       else
3285          return Scope_Suppress (Division_Check);
3286       end if;
3287    end Division_Checks_Suppressed;
3288
3289    -----------------------------------
3290    -- Elaboration_Checks_Suppressed --
3291    -----------------------------------
3292
3293    function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
3294    begin
3295       --  The complication in this routine is that if we are in the dynamic
3296       --  model of elaboration, we also check All_Checks, since All_Checks
3297       --  does not set Elaboration_Check explicitly.
3298
3299       if Present (E) then
3300          if Kill_Elaboration_Checks (E) then
3301             return True;
3302
3303          elsif Checks_May_Be_Suppressed (E) then
3304             if Is_Check_Suppressed (E, Elaboration_Check) then
3305                return True;
3306             elsif Dynamic_Elaboration_Checks then
3307                return Is_Check_Suppressed (E, All_Checks);
3308             else
3309                return False;
3310             end if;
3311          end if;
3312       end if;
3313
3314       if Scope_Suppress (Elaboration_Check) then
3315          return True;
3316       elsif Dynamic_Elaboration_Checks then
3317          return Scope_Suppress (All_Checks);
3318       else
3319          return False;
3320       end if;
3321    end Elaboration_Checks_Suppressed;
3322
3323    ---------------------------
3324    -- Enable_Overflow_Check --
3325    ---------------------------
3326
3327    procedure Enable_Overflow_Check (N : Node_Id) is
3328       Typ : constant Entity_Id  := Base_Type (Etype (N));
3329       Chk : Nat;
3330       OK  : Boolean;
3331       Ent : Entity_Id;
3332       Ofs : Uint;
3333       Lo  : Uint;
3334       Hi  : Uint;
3335
3336    begin
3337       if Debug_Flag_CC then
3338          w ("Enable_Overflow_Check for node ", Int (N));
3339          Write_Str ("  Source location = ");
3340          wl (Sloc (N));
3341          pg (Union_Id (N));
3342       end if;
3343
3344       --  Nothing to do if the range of the result is known OK. We skip this
3345       --  for conversions, since the caller already did the check, and in any
3346       --  case the condition for deleting the check for a type conversion is
3347       --  different in any case.
3348
3349       if Nkind (N) /= N_Type_Conversion then
3350          Determine_Range (N, OK, Lo, Hi);
3351
3352          --  Note in the test below that we assume that if a bound of the
3353          --  range is equal to that of the type. That's not quite accurate
3354          --  but we do this for the following reasons:
3355
3356          --   a) The way that Determine_Range works, it will typically report
3357          --      the bounds of the value as being equal to the bounds of the
3358          --      type, because it either can't tell anything more precise, or
3359          --      does not think it is worth the effort to be more precise.
3360
3361          --   b) It is very unusual to have a situation in which this would
3362          --      generate an unnecessary overflow check (an example would be
3363          --      a subtype with a range 0 .. Integer'Last - 1 to which the
3364          --      literal value one is added.
3365
3366          --   c) The alternative is a lot of special casing in this routine
3367          --      which would partially duplicate Determine_Range processing.
3368
3369          if OK
3370            and then Lo > Expr_Value (Type_Low_Bound  (Typ))
3371            and then Hi < Expr_Value (Type_High_Bound (Typ))
3372          then
3373             if Debug_Flag_CC then
3374                w ("No overflow check required");
3375             end if;
3376
3377             return;
3378          end if;
3379       end if;
3380
3381       --  If not in optimizing mode, set flag and we are done. We are also done
3382       --  (and just set the flag) if the type is not a discrete type, since it
3383       --  is not worth the effort to eliminate checks for other than discrete
3384       --  types. In addition, we take this same path if we have stored the
3385       --  maximum number of checks possible already (a very unlikely situation,
3386       --  but we do not want to blow up!)
3387
3388       if Optimization_Level = 0
3389         or else not Is_Discrete_Type (Etype (N))
3390         or else Num_Saved_Checks = Saved_Checks'Last
3391       then
3392          Activate_Overflow_Check (N);
3393
3394          if Debug_Flag_CC then
3395             w ("Optimization off");
3396          end if;
3397
3398          return;
3399       end if;
3400
3401       --  Otherwise evaluate and check the expression
3402
3403       Find_Check
3404         (Expr        => N,
3405          Check_Type  => 'O',
3406          Target_Type => Empty,
3407          Entry_OK    => OK,
3408          Check_Num   => Chk,
3409          Ent         => Ent,
3410          Ofs         => Ofs);
3411
3412       if Debug_Flag_CC then
3413          w ("Called Find_Check");
3414          w ("  OK = ", OK);
3415
3416          if OK then
3417             w ("  Check_Num = ", Chk);
3418             w ("  Ent       = ", Int (Ent));
3419             Write_Str ("  Ofs       = ");
3420             pid (Ofs);
3421          end if;
3422       end if;
3423
3424       --  If check is not of form to optimize, then set flag and we are done
3425
3426       if not OK then
3427          Activate_Overflow_Check (N);
3428          return;
3429       end if;
3430
3431       --  If check is already performed, then return without setting flag
3432
3433       if Chk /= 0 then
3434          if Debug_Flag_CC then
3435             w ("Check suppressed!");
3436          end if;
3437
3438          return;
3439       end if;
3440
3441       --  Here we will make a new entry for the new check
3442
3443       Activate_Overflow_Check (N);
3444       Num_Saved_Checks := Num_Saved_Checks + 1;
3445       Saved_Checks (Num_Saved_Checks) :=
3446         (Killed      => False,
3447          Entity      => Ent,
3448          Offset      => Ofs,
3449          Check_Type  => 'O',
3450          Target_Type => Empty);
3451
3452       if Debug_Flag_CC then
3453          w ("Make new entry, check number = ", Num_Saved_Checks);
3454          w ("  Entity = ", Int (Ent));
3455          Write_Str ("  Offset = ");
3456          pid (Ofs);
3457          w ("  Check_Type = O");
3458          w ("  Target_Type = Empty");
3459       end if;
3460
3461    --  If we get an exception, then something went wrong, probably because of
3462    --  an error in the structure of the tree due to an incorrect program. Or it
3463    --  may be a bug in the optimization circuit. In either case the safest
3464    --  thing is simply to set the check flag unconditionally.
3465
3466    exception
3467       when others =>
3468          Activate_Overflow_Check (N);
3469
3470          if Debug_Flag_CC then
3471             w ("  exception occurred, overflow flag set");
3472          end if;
3473
3474          return;
3475    end Enable_Overflow_Check;
3476
3477    ------------------------
3478    -- Enable_Range_Check --
3479    ------------------------
3480
3481    procedure Enable_Range_Check (N : Node_Id) is
3482       Chk  : Nat;
3483       OK   : Boolean;
3484       Ent  : Entity_Id;
3485       Ofs  : Uint;
3486       Ttyp : Entity_Id;
3487       P    : Node_Id;
3488
3489    begin
3490       --  Return if unchecked type conversion with range check killed. In this
3491       --  case we never set the flag (that's what Kill_Range_Check is about!)
3492
3493       if Nkind (N) = N_Unchecked_Type_Conversion
3494         and then Kill_Range_Check (N)
3495       then
3496          return;
3497       end if;
3498
3499       --  Check for various cases where we should suppress the range check
3500
3501       --  No check if range checks suppressed for type of node
3502
3503       if Present (Etype (N))
3504         and then Range_Checks_Suppressed (Etype (N))
3505       then
3506          return;
3507
3508       --  No check if node is an entity name, and range checks are suppressed
3509       --  for this entity, or for the type of this entity.
3510
3511       elsif Is_Entity_Name (N)
3512         and then (Range_Checks_Suppressed (Entity (N))
3513                     or else Range_Checks_Suppressed (Etype (Entity (N))))
3514       then
3515          return;
3516
3517       --  No checks if index of array, and index checks are suppressed for
3518       --  the array object or the type of the array.
3519
3520       elsif Nkind (Parent (N)) = N_Indexed_Component then
3521          declare
3522             Pref : constant Node_Id := Prefix (Parent (N));
3523          begin
3524             if Is_Entity_Name (Pref)
3525               and then Index_Checks_Suppressed (Entity (Pref))
3526             then
3527                return;
3528             elsif Index_Checks_Suppressed (Etype (Pref)) then
3529                return;
3530             end if;
3531          end;
3532       end if;
3533
3534       --  Debug trace output
3535
3536       if Debug_Flag_CC then
3537          w ("Enable_Range_Check for node ", Int (N));
3538          Write_Str ("  Source location = ");
3539          wl (Sloc (N));
3540          pg (Union_Id (N));
3541       end if;
3542
3543       --  If not in optimizing mode, set flag and we are done. We are also done
3544       --  (and just set the flag) if the type is not a discrete type, since it
3545       --  is not worth the effort to eliminate checks for other than discrete
3546       --  types. In addition, we take this same path if we have stored the
3547       --  maximum number of checks possible already (a very unlikely situation,
3548       --  but we do not want to blow up!)
3549
3550       if Optimization_Level = 0
3551         or else No (Etype (N))
3552         or else not Is_Discrete_Type (Etype (N))
3553         or else Num_Saved_Checks = Saved_Checks'Last
3554       then
3555          Activate_Range_Check (N);
3556
3557          if Debug_Flag_CC then
3558             w ("Optimization off");
3559          end if;
3560
3561          return;
3562       end if;
3563
3564       --  Otherwise find out the target type
3565
3566       P := Parent (N);
3567
3568       --  For assignment, use left side subtype
3569
3570       if Nkind (P) = N_Assignment_Statement
3571         and then Expression (P) = N
3572       then
3573          Ttyp := Etype (Name (P));
3574
3575       --  For indexed component, use subscript subtype
3576
3577       elsif Nkind (P) = N_Indexed_Component then
3578          declare
3579             Atyp : Entity_Id;
3580             Indx : Node_Id;
3581             Subs : Node_Id;
3582
3583          begin
3584             Atyp := Etype (Prefix (P));
3585
3586             if Is_Access_Type (Atyp) then
3587                Atyp := Designated_Type (Atyp);
3588
3589                --  If the prefix is an access to an unconstrained array,
3590                --  perform check unconditionally: it depends on the bounds of
3591                --  an object and we cannot currently recognize whether the test
3592                --  may be redundant.
3593
3594                if not Is_Constrained (Atyp) then
3595                   Activate_Range_Check (N);
3596                   return;
3597                end if;
3598
3599             --  Ditto if the prefix is an explicit dereference whose designated
3600             --  type is unconstrained.
3601
3602             elsif Nkind (Prefix (P)) = N_Explicit_Dereference
3603               and then not Is_Constrained (Atyp)
3604             then
3605                Activate_Range_Check (N);
3606                return;
3607             end if;
3608
3609             Indx := First_Index (Atyp);
3610             Subs := First (Expressions (P));
3611             loop
3612                if Subs = N then
3613                   Ttyp := Etype (Indx);
3614                   exit;
3615                end if;
3616
3617                Next_Index (Indx);
3618                Next (Subs);
3619             end loop;
3620          end;
3621
3622       --  For now, ignore all other cases, they are not so interesting
3623
3624       else
3625          if Debug_Flag_CC then
3626             w ("  target type not found, flag set");
3627          end if;
3628
3629          Activate_Range_Check (N);
3630          return;
3631       end if;
3632
3633       --  Evaluate and check the expression
3634
3635       Find_Check
3636         (Expr        => N,
3637          Check_Type  => 'R',
3638          Target_Type => Ttyp,
3639          Entry_OK    => OK,
3640          Check_Num   => Chk,
3641          Ent         => Ent,
3642          Ofs         => Ofs);
3643
3644       if Debug_Flag_CC then
3645          w ("Called Find_Check");
3646          w ("Target_Typ = ", Int (Ttyp));
3647          w ("  OK = ", OK);
3648
3649          if OK then
3650             w ("  Check_Num = ", Chk);
3651             w ("  Ent       = ", Int (Ent));
3652             Write_Str ("  Ofs       = ");
3653             pid (Ofs);
3654          end if;
3655       end if;
3656
3657       --  If check is not of form to optimize, then set flag and we are done
3658
3659       if not OK then
3660          if Debug_Flag_CC then
3661             w ("  expression not of optimizable type, flag set");
3662          end if;
3663
3664          Activate_Range_Check (N);
3665          return;
3666       end if;
3667
3668       --  If check is already performed, then return without setting flag
3669
3670       if Chk /= 0 then
3671          if Debug_Flag_CC then
3672             w ("Check suppressed!");
3673          end if;
3674
3675          return;
3676       end if;
3677
3678       --  Here we will make a new entry for the new check
3679
3680       Activate_Range_Check (N);
3681       Num_Saved_Checks := Num_Saved_Checks + 1;
3682       Saved_Checks (Num_Saved_Checks) :=
3683         (Killed      => False,
3684          Entity      => Ent,
3685          Offset      => Ofs,
3686          Check_Type  => 'R',
3687          Target_Type => Ttyp);
3688
3689       if Debug_Flag_CC then
3690          w ("Make new entry, check number = ", Num_Saved_Checks);
3691          w ("  Entity = ", Int (Ent));
3692          Write_Str ("  Offset = ");
3693          pid (Ofs);
3694          w ("  Check_Type = R");
3695          w ("  Target_Type = ", Int (Ttyp));
3696          pg (Union_Id (Ttyp));
3697       end if;
3698
3699    --  If we get an exception, then something went wrong, probably because of
3700    --  an error in the structure of the tree due to an incorrect program. Or
3701    --  it may be a bug in the optimization circuit. In either case the safest
3702    --  thing is simply to set the check flag unconditionally.
3703
3704    exception
3705       when others =>
3706          Activate_Range_Check (N);
3707
3708          if Debug_Flag_CC then
3709             w ("  exception occurred, range flag set");
3710          end if;
3711
3712          return;
3713    end Enable_Range_Check;
3714
3715    ------------------
3716    -- Ensure_Valid --
3717    ------------------
3718
3719    procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False) is
3720       Typ : constant Entity_Id  := Etype (Expr);
3721
3722    begin
3723       --  Ignore call if we are not doing any validity checking
3724
3725       if not Validity_Checks_On then
3726          return;
3727
3728       --  Ignore call if range or validity checks suppressed on entity or type
3729
3730       elsif Range_Or_Validity_Checks_Suppressed (Expr) then
3731          return;
3732
3733       --  No check required if expression is from the expander, we assume the
3734       --  expander will generate whatever checks are needed. Note that this is
3735       --  not just an optimization, it avoids infinite recursions!
3736
3737       --  Unchecked conversions must be checked, unless they are initialized
3738       --  scalar values, as in a component assignment in an init proc.
3739
3740       --  In addition, we force a check if Force_Validity_Checks is set
3741
3742       elsif not Comes_From_Source (Expr)
3743         and then not Force_Validity_Checks
3744         and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
3745                     or else Kill_Range_Check (Expr))
3746       then
3747          return;
3748
3749       --  No check required if expression is known to have valid value
3750
3751       elsif Expr_Known_Valid (Expr) then
3752          return;
3753
3754       --  Ignore case of enumeration with holes where the flag is set not to
3755       --  worry about holes, since no special validity check is needed
3756
3757       elsif Is_Enumeration_Type (Typ)
3758         and then Has_Non_Standard_Rep (Typ)
3759         and then Holes_OK
3760       then
3761          return;
3762
3763       --  No check required on the left-hand side of an assignment
3764
3765       elsif Nkind (Parent (Expr)) = N_Assignment_Statement
3766         and then Expr = Name (Parent (Expr))
3767       then
3768          return;
3769
3770       --  No check on a univeral real constant. The context will eventually
3771       --  convert it to a machine number for some target type, or report an
3772       --  illegality.
3773
3774       elsif Nkind (Expr) = N_Real_Literal
3775         and then Etype (Expr) = Universal_Real
3776       then
3777          return;
3778
3779       --  If the expression denotes a component of a packed boolean arrray,
3780       --  no possible check applies. We ignore the old ACATS chestnuts that
3781       --  involve Boolean range True..True.
3782
3783       --  Note: validity checks are generated for expressions that yield a
3784       --  scalar type, when it is possible to create a value that is outside of
3785       --  the type. If this is a one-bit boolean no such value exists. This is
3786       --  an optimization, and it also prevents compiler blowing up during the
3787       --  elaboration of improperly expanded packed array references.
3788
3789       elsif Nkind (Expr) = N_Indexed_Component
3790         and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
3791         and then Root_Type (Etype (Expr)) = Standard_Boolean
3792       then
3793          return;
3794
3795       --  An annoying special case. If this is an out parameter of a scalar
3796       --  type, then the value is not going to be accessed, therefore it is
3797       --  inappropriate to do any validity check at the call site.
3798
3799       else
3800          --  Only need to worry about scalar types
3801
3802          if Is_Scalar_Type (Typ) then
3803             declare
3804                P : Node_Id;
3805                N : Node_Id;
3806                E : Entity_Id;
3807                F : Entity_Id;
3808                A : Node_Id;
3809                L : List_Id;
3810
3811             begin
3812                --  Find actual argument (which may be a parameter association)
3813                --  and the parent of the actual argument (the call statement)
3814
3815                N := Expr;
3816                P := Parent (Expr);
3817
3818                if Nkind (P) = N_Parameter_Association then
3819                   N := P;
3820                   P := Parent (N);
3821                end if;
3822
3823                --  Only need to worry if we are argument of a procedure call
3824                --  since functions don't have out parameters. If this is an
3825                --  indirect or dispatching call, get signature from the
3826                --  subprogram type.
3827
3828                if Nkind (P) = N_Procedure_Call_Statement then
3829                   L := Parameter_Associations (P);
3830
3831                   if Is_Entity_Name (Name (P)) then
3832                      E := Entity (Name (P));
3833                   else
3834                      pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
3835                      E := Etype (Name (P));
3836                   end if;
3837
3838                   --  Only need to worry if there are indeed actuals, and if
3839                   --  this could be a procedure call, otherwise we cannot get a
3840                   --  match (either we are not an argument, or the mode of the
3841                   --  formal is not OUT). This test also filters out the
3842                   --  generic case.
3843
3844                   if Is_Non_Empty_List (L)
3845                     and then Is_Subprogram (E)
3846                   then
3847                      --  This is the loop through parameters, looking for an
3848                      --  OUT parameter for which we are the argument.
3849
3850                      F := First_Formal (E);
3851                      A := First (L);
3852                      while Present (F) loop
3853                         if Ekind (F) = E_Out_Parameter and then A = N then
3854                            return;
3855                         end if;
3856
3857                         Next_Formal (F);
3858                         Next (A);
3859                      end loop;
3860                   end if;
3861                end if;
3862             end;
3863          end if;
3864       end if;
3865
3866       --  If we fall through, a validity check is required
3867
3868       Insert_Valid_Check (Expr);
3869    end Ensure_Valid;
3870
3871    ----------------------
3872    -- Expr_Known_Valid --
3873    ----------------------
3874
3875    function Expr_Known_Valid (Expr : Node_Id) return Boolean is
3876       Typ : constant Entity_Id := Etype (Expr);
3877
3878    begin
3879       --  Non-scalar types are always considered valid, since they never give
3880       --  rise to the issues of erroneous or bounded error behavior that are
3881       --  the concern. In formal reference manual terms the notion of validity
3882       --  only applies to scalar types. Note that even when packed arrays are
3883       --  represented using modular types, they are still arrays semantically,
3884       --  so they are also always valid (in particular, the unused bits can be
3885       --  random rubbish without affecting the validity of the array value).
3886
3887       if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Type (Typ) then
3888          return True;
3889
3890       --  If no validity checking, then everything is considered valid
3891
3892       elsif not Validity_Checks_On then
3893          return True;
3894
3895       --  Floating-point types are considered valid unless floating-point
3896       --  validity checks have been specifically turned on.
3897
3898       elsif Is_Floating_Point_Type (Typ)
3899         and then not Validity_Check_Floating_Point
3900       then
3901          return True;
3902
3903       --  If the expression is the value of an object that is known to be
3904       --  valid, then clearly the expression value itself is valid.
3905
3906       elsif Is_Entity_Name (Expr)
3907         and then Is_Known_Valid (Entity (Expr))
3908       then
3909          return True;
3910
3911       --  References to discriminants are always considered valid. The value
3912       --  of a discriminant gets checked when the object is built. Within the
3913       --  record, we consider it valid, and it is important to do so, since
3914       --  otherwise we can try to generate bogus validity checks which
3915       --  reference discriminants out of scope. Discriminants of concurrent
3916       --  types are excluded for the same reason.
3917
3918       elsif Is_Entity_Name (Expr)
3919         and then Denotes_Discriminant (Expr, Check_Concurrent => True)
3920       then
3921          return True;
3922
3923       --  If the type is one for which all values are known valid, then we are
3924       --  sure that the value is valid except in the slightly odd case where
3925       --  the expression is a reference to a variable whose size has been
3926       --  explicitly set to a value greater than the object size.
3927
3928       elsif Is_Known_Valid (Typ) then
3929          if Is_Entity_Name (Expr)
3930            and then Ekind (Entity (Expr)) = E_Variable
3931            and then Esize (Entity (Expr)) > Esize (Typ)
3932          then
3933             return False;
3934          else
3935             return True;
3936          end if;
3937
3938       --  Integer and character literals always have valid values, where
3939       --  appropriate these will be range checked in any case.
3940
3941       elsif Nkind (Expr) = N_Integer_Literal
3942               or else
3943             Nkind (Expr) = N_Character_Literal
3944       then
3945          return True;
3946
3947       --  If we have a type conversion or a qualification of a known valid
3948       --  value, then the result will always be valid.
3949
3950       elsif Nkind (Expr) = N_Type_Conversion
3951               or else
3952             Nkind (Expr) = N_Qualified_Expression
3953       then
3954          return Expr_Known_Valid (Expression (Expr));
3955
3956       --  The result of any operator is always considered valid, since we
3957       --  assume the necessary checks are done by the operator. For operators
3958       --  on floating-point operations, we must also check when the operation
3959       --  is the right-hand side of an assignment, or is an actual in a call.
3960
3961       elsif Nkind (Expr) in N_Op then
3962          if Is_Floating_Point_Type (Typ)
3963             and then Validity_Check_Floating_Point
3964             and then
3965               (Nkind (Parent (Expr)) = N_Assignment_Statement
3966                 or else Nkind (Parent (Expr)) = N_Function_Call
3967                 or else Nkind (Parent (Expr)) = N_Parameter_Association)
3968          then
3969             return False;
3970          else
3971             return True;
3972          end if;
3973
3974       --  The result of a membership test is always valid, since it is true or
3975       --  false, there are no other possibilities.
3976
3977       elsif Nkind (Expr) in N_Membership_Test then
3978          return True;
3979
3980       --  For all other cases, we do not know the expression is valid
3981
3982       else
3983          return False;
3984       end if;
3985    end Expr_Known_Valid;
3986
3987    ----------------
3988    -- Find_Check --
3989    ----------------
3990
3991    procedure Find_Check
3992      (Expr        : Node_Id;
3993       Check_Type  : Character;
3994       Target_Type : Entity_Id;
3995       Entry_OK    : out Boolean;
3996       Check_Num   : out Nat;
3997       Ent         : out Entity_Id;
3998       Ofs         : out Uint)
3999    is
4000       function Within_Range_Of
4001         (Target_Type : Entity_Id;
4002          Check_Type  : Entity_Id) return Boolean;
4003       --  Given a requirement for checking a range against Target_Type, and
4004       --  and a range Check_Type against which a check has already been made,
4005       --  determines if the check against check type is sufficient to ensure
4006       --  that no check against Target_Type is required.
4007
4008       ---------------------
4009       -- Within_Range_Of --
4010       ---------------------
4011
4012       function Within_Range_Of
4013         (Target_Type : Entity_Id;
4014          Check_Type  : Entity_Id) return Boolean
4015       is
4016       begin
4017          if Target_Type = Check_Type then
4018             return True;
4019
4020          else
4021             declare
4022                Tlo : constant Node_Id := Type_Low_Bound  (Target_Type);
4023                Thi : constant Node_Id := Type_High_Bound (Target_Type);
4024                Clo : constant Node_Id := Type_Low_Bound  (Check_Type);
4025                Chi : constant Node_Id := Type_High_Bound (Check_Type);
4026
4027             begin
4028                if (Tlo = Clo
4029                      or else (Compile_Time_Known_Value (Tlo)
4030                                 and then
4031                               Compile_Time_Known_Value (Clo)
4032                                 and then
4033                               Expr_Value (Clo) >= Expr_Value (Tlo)))
4034                  and then
4035                   (Thi = Chi
4036                      or else (Compile_Time_Known_Value (Thi)
4037                                 and then
4038                               Compile_Time_Known_Value (Chi)
4039                                 and then
4040                               Expr_Value (Chi) <= Expr_Value (Clo)))
4041                then
4042                   return True;
4043                else
4044                   return False;
4045                end if;
4046             end;
4047          end if;
4048       end Within_Range_Of;
4049
4050    --  Start of processing for Find_Check
4051
4052    begin
4053       --  Establish default, to avoid warnings from GCC
4054
4055       Check_Num := 0;
4056
4057       --  Case of expression is simple entity reference
4058
4059       if Is_Entity_Name (Expr) then
4060          Ent := Entity (Expr);
4061          Ofs := Uint_0;
4062
4063       --  Case of expression is entity + known constant
4064
4065       elsif Nkind (Expr) = N_Op_Add
4066         and then Compile_Time_Known_Value (Right_Opnd (Expr))
4067         and then Is_Entity_Name (Left_Opnd (Expr))
4068       then
4069          Ent := Entity (Left_Opnd (Expr));
4070          Ofs := Expr_Value (Right_Opnd (Expr));
4071
4072       --  Case of expression is entity - known constant
4073
4074       elsif Nkind (Expr) = N_Op_Subtract
4075         and then Compile_Time_Known_Value (Right_Opnd (Expr))
4076         and then Is_Entity_Name (Left_Opnd (Expr))
4077       then
4078          Ent := Entity (Left_Opnd (Expr));
4079          Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
4080
4081       --  Any other expression is not of the right form
4082
4083       else
4084          Ent := Empty;
4085          Ofs := Uint_0;
4086          Entry_OK := False;
4087          return;
4088       end if;
4089
4090       --  Come here with expression of appropriate form, check if entity is an
4091       --  appropriate one for our purposes.
4092
4093       if (Ekind (Ent) = E_Variable
4094             or else
4095           Ekind (Ent) = E_Constant
4096             or else
4097           Ekind (Ent) = E_Loop_Parameter
4098             or else
4099           Ekind (Ent) = E_In_Parameter)
4100         and then not Is_Library_Level_Entity (Ent)
4101       then
4102          Entry_OK := True;
4103       else
4104          Entry_OK := False;
4105          return;
4106       end if;
4107
4108       --  See if there is matching check already
4109
4110       for J in reverse 1 .. Num_Saved_Checks loop
4111          declare
4112             SC : Saved_Check renames Saved_Checks (J);
4113
4114          begin
4115             if SC.Killed = False
4116               and then SC.Entity = Ent
4117               and then SC.Offset = Ofs
4118               and then SC.Check_Type = Check_Type
4119               and then Within_Range_Of (Target_Type, SC.Target_Type)
4120             then
4121                Check_Num := J;
4122                return;
4123             end if;
4124          end;
4125       end loop;
4126
4127       --  If we fall through entry was not found
4128
4129       Check_Num := 0;
4130       return;
4131    end Find_Check;
4132
4133    ---------------------------------
4134    -- Generate_Discriminant_Check --
4135    ---------------------------------
4136
4137    --  Note: the code for this procedure is derived from the
4138    --  Emit_Discriminant_Check Routine in trans.c.
4139
4140    procedure Generate_Discriminant_Check (N : Node_Id) is
4141       Loc  : constant Source_Ptr := Sloc (N);
4142       Pref : constant Node_Id    := Prefix (N);
4143       Sel  : constant Node_Id    := Selector_Name (N);
4144
4145       Orig_Comp : constant Entity_Id :=
4146                     Original_Record_Component (Entity (Sel));
4147       --  The original component to be checked
4148
4149       Discr_Fct : constant Entity_Id :=
4150                     Discriminant_Checking_Func (Orig_Comp);
4151       --  The discriminant checking function
4152
4153       Discr : Entity_Id;
4154       --  One discriminant to be checked in the type
4155
4156       Real_Discr : Entity_Id;
4157       --  Actual discriminant in the call
4158
4159       Pref_Type : Entity_Id;
4160       --  Type of relevant prefix (ignoring private/access stuff)
4161
4162       Args : List_Id;
4163       --  List of arguments for function call
4164
4165       Formal : Entity_Id;
4166       --  Keep track of the formal corresponding to the actual we build for
4167       --  each discriminant, in order to be able to perform the necessary type
4168       --  conversions.
4169
4170       Scomp : Node_Id;
4171       --  Selected component reference for checking function argument
4172
4173    begin
4174       Pref_Type := Etype (Pref);
4175
4176       --  Force evaluation of the prefix, so that it does not get evaluated
4177       --  twice (once for the check, once for the actual reference). Such a
4178       --  double evaluation is always a potential source of inefficiency,
4179       --  and is functionally incorrect in the volatile case, or when the
4180       --  prefix may have side-effects. An entity or a component of an
4181       --  entity requires no evaluation.
4182
4183       if Is_Entity_Name (Pref) then
4184          if Treat_As_Volatile (Entity (Pref)) then
4185             Force_Evaluation (Pref, Name_Req => True);
4186          end if;
4187
4188       elsif Treat_As_Volatile (Etype (Pref)) then
4189             Force_Evaluation (Pref, Name_Req => True);
4190
4191       elsif Nkind (Pref) = N_Selected_Component
4192         and then Is_Entity_Name (Prefix (Pref))
4193       then
4194          null;
4195
4196       else
4197          Force_Evaluation (Pref, Name_Req => True);
4198       end if;
4199
4200       --  For a tagged type, use the scope of the original component to
4201       --  obtain the type, because ???
4202
4203       if Is_Tagged_Type (Scope (Orig_Comp)) then
4204          Pref_Type := Scope (Orig_Comp);
4205
4206       --  For an untagged derived type, use the discriminants of the parent
4207       --  which have been renamed in the derivation, possibly by a one-to-many
4208       --  discriminant constraint. For non-tagged type, initially get the Etype
4209       --  of the prefix
4210
4211       else
4212          if Is_Derived_Type (Pref_Type)
4213            and then Number_Discriminants (Pref_Type) /=
4214                     Number_Discriminants (Etype (Base_Type (Pref_Type)))
4215          then
4216             Pref_Type := Etype (Base_Type (Pref_Type));
4217          end if;
4218       end if;
4219
4220       --  We definitely should have a checking function, This routine should
4221       --  not be called if no discriminant checking function is present.
4222
4223       pragma Assert (Present (Discr_Fct));
4224
4225       --  Create the list of the actual parameters for the call. This list
4226       --  is the list of the discriminant fields of the record expression to
4227       --  be discriminant checked.
4228
4229       Args   := New_List;
4230       Formal := First_Formal (Discr_Fct);
4231       Discr  := First_Discriminant (Pref_Type);
4232       while Present (Discr) loop
4233
4234          --  If we have a corresponding discriminant field, and a parent
4235          --  subtype is present, then we want to use the corresponding
4236          --  discriminant since this is the one with the useful value.
4237
4238          if Present (Corresponding_Discriminant (Discr))
4239            and then Ekind (Pref_Type) = E_Record_Type
4240            and then Present (Parent_Subtype (Pref_Type))
4241          then
4242             Real_Discr := Corresponding_Discriminant (Discr);
4243          else
4244             Real_Discr := Discr;
4245          end if;
4246
4247          --  Construct the reference to the discriminant
4248
4249          Scomp :=
4250            Make_Selected_Component (Loc,
4251              Prefix =>
4252                Unchecked_Convert_To (Pref_Type,
4253                  Duplicate_Subexpr (Pref)),
4254              Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
4255
4256          --  Manually analyze and resolve this selected component. We really
4257          --  want it just as it appears above, and do not want the expander
4258          --  playing discriminal games etc with this reference. Then we append
4259          --  the argument to the list we are gathering.
4260
4261          Set_Etype (Scomp, Etype (Real_Discr));
4262          Set_Analyzed (Scomp, True);
4263          Append_To (Args, Convert_To (Etype (Formal), Scomp));
4264
4265          Next_Formal_With_Extras (Formal);
4266          Next_Discriminant (Discr);
4267       end loop;
4268
4269       --  Now build and insert the call
4270
4271       Insert_Action (N,
4272         Make_Raise_Constraint_Error (Loc,
4273           Condition =>
4274             Make_Function_Call (Loc,
4275               Name => New_Occurrence_Of (Discr_Fct, Loc),
4276               Parameter_Associations => Args),
4277           Reason => CE_Discriminant_Check_Failed));
4278    end Generate_Discriminant_Check;
4279
4280    ---------------------------
4281    -- Generate_Index_Checks --
4282    ---------------------------
4283
4284    procedure Generate_Index_Checks (N : Node_Id) is
4285       Loc : constant Source_Ptr := Sloc (N);
4286       A   : constant Node_Id    := Prefix (N);
4287       Sub : Node_Id;
4288       Ind : Nat;
4289       Num : List_Id;
4290
4291    begin
4292       --  Ignore call if index checks suppressed for array object or type
4293
4294       if (Is_Entity_Name (A) and then Index_Checks_Suppressed (Entity (A)))
4295         or else Index_Checks_Suppressed (Etype (A))
4296       then
4297          return;
4298       end if;
4299
4300       --  Generate the checks
4301
4302       Sub := First (Expressions (N));
4303       Ind := 1;
4304       while Present (Sub) loop
4305          if Do_Range_Check (Sub) then
4306             Set_Do_Range_Check (Sub, False);
4307
4308             --  Force evaluation except for the case of a simple name of a
4309             --  non-volatile entity.
4310
4311             if not Is_Entity_Name (Sub)
4312               or else Treat_As_Volatile (Entity (Sub))
4313             then
4314                Force_Evaluation (Sub);
4315             end if;
4316
4317             --  Generate a raise of constraint error with the appropriate
4318             --  reason and a condition of the form:
4319
4320             --    Base_Type(Sub) not in array'range (subscript)
4321
4322             --  Note that the reason we generate the conversion to the base
4323             --  type here is that we definitely want the range check to take
4324             --  place, even if it looks like the subtype is OK. Optimization
4325             --  considerations that allow us to omit the check have already
4326             --  been taken into account in the setting of the Do_Range_Check
4327             --  flag earlier on.
4328
4329             if Ind = 1 then
4330                Num := No_List;
4331             else
4332                Num :=  New_List (Make_Integer_Literal (Loc, Ind));
4333             end if;
4334
4335             Insert_Action (N,
4336               Make_Raise_Constraint_Error (Loc,
4337                 Condition =>
4338                   Make_Not_In (Loc,
4339                     Left_Opnd  =>
4340                       Convert_To (Base_Type (Etype (Sub)),
4341                         Duplicate_Subexpr_Move_Checks (Sub)),
4342                     Right_Opnd =>
4343                       Make_Attribute_Reference (Loc,
4344                         Prefix         => Duplicate_Subexpr_Move_Checks (A),
4345                         Attribute_Name => Name_Range,
4346                         Expressions    => Num)),
4347                 Reason => CE_Index_Check_Failed));
4348          end if;
4349
4350          Ind := Ind + 1;
4351          Next (Sub);
4352       end loop;
4353    end Generate_Index_Checks;
4354
4355    --------------------------
4356    -- Generate_Range_Check --
4357    --------------------------
4358
4359    procedure Generate_Range_Check
4360      (N           : Node_Id;
4361       Target_Type : Entity_Id;
4362       Reason      : RT_Exception_Code)
4363    is
4364       Loc              : constant Source_Ptr := Sloc (N);
4365       Source_Type      : constant Entity_Id  := Etype (N);
4366       Source_Base_Type : constant Entity_Id  := Base_Type (Source_Type);
4367       Target_Base_Type : constant Entity_Id  := Base_Type (Target_Type);
4368
4369    begin
4370       --  First special case, if the source type is already within the range
4371       --  of the target type, then no check is needed (probably we should have
4372       --  stopped Do_Range_Check from being set in the first place, but better
4373       --  late than later in preventing junk code!
4374
4375       --  We do NOT apply this if the source node is a literal, since in this
4376       --  case the literal has already been labeled as having the subtype of
4377       --  the target.
4378
4379       if In_Subrange_Of (Source_Type, Target_Type)
4380         and then not
4381           (Nkind (N) = N_Integer_Literal
4382              or else
4383            Nkind (N) = N_Real_Literal
4384              or else
4385            Nkind (N) = N_Character_Literal
4386              or else
4387            (Is_Entity_Name (N)
4388               and then Ekind (Entity (N)) = E_Enumeration_Literal))
4389       then
4390          return;
4391       end if;
4392
4393       --  We need a check, so force evaluation of the node, so that it does
4394       --  not get evaluated twice (once for the check, once for the actual
4395       --  reference). Such a double evaluation is always a potential source
4396       --  of inefficiency, and is functionally incorrect in the volatile case.
4397
4398       if not Is_Entity_Name (N)
4399         or else Treat_As_Volatile (Entity (N))
4400       then
4401          Force_Evaluation (N);
4402       end if;
4403
4404       --  The easiest case is when Source_Base_Type and Target_Base_Type are
4405       --  the same since in this case we can simply do a direct check of the
4406       --  value of N against the bounds of Target_Type.
4407
4408       --    [constraint_error when N not in Target_Type]
4409
4410       --  Note: this is by far the most common case, for example all cases of
4411       --  checks on the RHS of assignments are in this category, but not all
4412       --  cases are like this. Notably conversions can involve two types.
4413
4414       if Source_Base_Type = Target_Base_Type then
4415          Insert_Action (N,
4416            Make_Raise_Constraint_Error (Loc,
4417              Condition =>
4418                Make_Not_In (Loc,
4419                  Left_Opnd  => Duplicate_Subexpr (N),
4420                  Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4421              Reason => Reason));
4422
4423       --  Next test for the case where the target type is within the bounds
4424       --  of the base type of the source type, since in this case we can
4425       --  simply convert these bounds to the base type of T to do the test.
4426
4427       --    [constraint_error when N not in
4428       --       Source_Base_Type (Target_Type'First)
4429       --         ..
4430       --       Source_Base_Type(Target_Type'Last))]
4431
4432       --  The conversions will always work and need no check
4433
4434       elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
4435          Insert_Action (N,
4436            Make_Raise_Constraint_Error (Loc,
4437              Condition =>
4438                Make_Not_In (Loc,
4439                  Left_Opnd  => Duplicate_Subexpr (N),
4440
4441                  Right_Opnd =>
4442                    Make_Range (Loc,
4443                      Low_Bound =>
4444                        Convert_To (Source_Base_Type,
4445                          Make_Attribute_Reference (Loc,
4446                            Prefix =>
4447                              New_Occurrence_Of (Target_Type, Loc),
4448                            Attribute_Name => Name_First)),
4449
4450                      High_Bound =>
4451                        Convert_To (Source_Base_Type,
4452                          Make_Attribute_Reference (Loc,
4453                            Prefix =>
4454                              New_Occurrence_Of (Target_Type, Loc),
4455                            Attribute_Name => Name_Last)))),
4456              Reason => Reason));
4457
4458       --  Note that at this stage we now that the Target_Base_Type is not in
4459       --  the range of the Source_Base_Type (since even the Target_Type itself
4460       --  is not in this range). It could still be the case that Source_Type is
4461       --  in range of the target base type since we have not checked that case.
4462
4463       --  If that is the case, we can freely convert the source to the target,
4464       --  and then test the target result against the bounds.
4465
4466       elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
4467
4468          --  We make a temporary to hold the value of the converted value
4469          --  (converted to the base type), and then we will do the test against
4470          --  this temporary.
4471
4472          --     Tnn : constant Target_Base_Type := Target_Base_Type (N);
4473          --     [constraint_error when Tnn not in Target_Type]
4474
4475          --  Then the conversion itself is replaced by an occurrence of Tnn
4476
4477          declare
4478             Tnn : constant Entity_Id :=
4479                     Make_Defining_Identifier (Loc,
4480                       Chars => New_Internal_Name ('T'));
4481
4482          begin
4483             Insert_Actions (N, New_List (
4484               Make_Object_Declaration (Loc,
4485                 Defining_Identifier => Tnn,
4486                 Object_Definition   =>
4487                   New_Occurrence_Of (Target_Base_Type, Loc),
4488                 Constant_Present    => True,
4489                 Expression          =>
4490                   Make_Type_Conversion (Loc,
4491                     Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
4492                     Expression   => Duplicate_Subexpr (N))),
4493
4494               Make_Raise_Constraint_Error (Loc,
4495                 Condition =>
4496                   Make_Not_In (Loc,
4497                     Left_Opnd  => New_Occurrence_Of (Tnn, Loc),
4498                     Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4499
4500                 Reason => Reason)));
4501
4502             Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4503
4504             --  Set the type of N, because the declaration for Tnn might not
4505             --  be analyzed yet, as is the case if N appears within a record
4506             --  declaration, as a discriminant constraint or expression.
4507
4508             Set_Etype (N, Target_Base_Type);
4509          end;
4510
4511       --  At this stage, we know that we have two scalar types, which are
4512       --  directly convertible, and where neither scalar type has a base
4513       --  range that is in the range of the other scalar type.
4514
4515       --  The only way this can happen is with a signed and unsigned type.
4516       --  So test for these two cases:
4517
4518       else
4519          --  Case of the source is unsigned and the target is signed
4520
4521          if Is_Unsigned_Type (Source_Base_Type)
4522            and then not Is_Unsigned_Type (Target_Base_Type)
4523          then
4524             --  If the source is unsigned and the target is signed, then we
4525             --  know that the source is not shorter than the target (otherwise
4526             --  the source base type would be in the target base type range).
4527
4528             --  In other words, the unsigned type is either the same size as
4529             --  the target, or it is larger. It cannot be smaller.
4530
4531             pragma Assert
4532               (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
4533
4534             --  We only need to check the low bound if the low bound of the
4535             --  target type is non-negative. If the low bound of the target
4536             --  type is negative, then we know that we will fit fine.
4537
4538             --  If the high bound of the target type is negative, then we
4539             --  know we have a constraint error, since we can't possibly
4540             --  have a negative source.
4541
4542             --  With these two checks out of the way, we can do the check
4543             --  using the source type safely
4544
4545             --  This is definitely the most annoying case!
4546
4547             --    [constraint_error
4548             --       when (Target_Type'First >= 0
4549             --               and then
4550             --                 N < Source_Base_Type (Target_Type'First))
4551             --         or else Target_Type'Last < 0
4552             --         or else N > Source_Base_Type (Target_Type'Last)];
4553
4554             --  We turn off all checks since we know that the conversions
4555             --  will work fine, given the guards for negative values.
4556
4557             Insert_Action (N,
4558               Make_Raise_Constraint_Error (Loc,
4559                 Condition =>
4560                   Make_Or_Else (Loc,
4561                     Make_Or_Else (Loc,
4562                       Left_Opnd =>
4563                         Make_And_Then (Loc,
4564                           Left_Opnd => Make_Op_Ge (Loc,
4565                             Left_Opnd =>
4566                               Make_Attribute_Reference (Loc,
4567                                 Prefix =>
4568                                   New_Occurrence_Of (Target_Type, Loc),
4569                                 Attribute_Name => Name_First),
4570                             Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4571
4572                           Right_Opnd =>
4573                             Make_Op_Lt (Loc,
4574                               Left_Opnd => Duplicate_Subexpr (N),
4575                               Right_Opnd =>
4576                                 Convert_To (Source_Base_Type,
4577                                   Make_Attribute_Reference (Loc,
4578                                     Prefix =>
4579                                       New_Occurrence_Of (Target_Type, Loc),
4580                                     Attribute_Name => Name_First)))),
4581
4582                       Right_Opnd =>
4583                         Make_Op_Lt (Loc,
4584                           Left_Opnd =>
4585                             Make_Attribute_Reference (Loc,
4586                               Prefix => New_Occurrence_Of (Target_Type, Loc),
4587                               Attribute_Name => Name_Last),
4588                             Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
4589
4590                     Right_Opnd =>
4591                       Make_Op_Gt (Loc,
4592                         Left_Opnd => Duplicate_Subexpr (N),
4593                         Right_Opnd =>
4594                           Convert_To (Source_Base_Type,
4595                             Make_Attribute_Reference (Loc,
4596                               Prefix => New_Occurrence_Of (Target_Type, Loc),
4597                               Attribute_Name => Name_Last)))),
4598
4599                 Reason => Reason),
4600               Suppress  => All_Checks);
4601
4602          --  Only remaining possibility is that the source is signed and
4603          --  the target is unsigned
4604
4605          else
4606             pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
4607                              and then Is_Unsigned_Type (Target_Base_Type));
4608
4609             --  If the source is signed and the target is unsigned, then we
4610             --  know that the target is not shorter than the source (otherwise
4611             --  the target base type would be in the source base type range).
4612
4613             --  In other words, the unsigned type is either the same size as
4614             --  the target, or it is larger. It cannot be smaller.
4615
4616             --  Clearly we have an error if the source value is negative since
4617             --  no unsigned type can have negative values. If the source type
4618             --  is non-negative, then the check can be done using the target
4619             --  type.
4620
4621             --    Tnn : constant Target_Base_Type (N) := Target_Type;
4622
4623             --    [constraint_error
4624             --       when N < 0 or else Tnn not in Target_Type];
4625
4626             --  We turn off all checks for the conversion of N to the target
4627             --  base type, since we generate the explicit check to ensure that
4628             --  the value is non-negative
4629
4630             declare
4631                Tnn : constant Entity_Id :=
4632                        Make_Defining_Identifier (Loc,
4633                          Chars => New_Internal_Name ('T'));
4634
4635             begin
4636                Insert_Actions (N, New_List (
4637                  Make_Object_Declaration (Loc,
4638                    Defining_Identifier => Tnn,
4639                    Object_Definition   =>
4640                      New_Occurrence_Of (Target_Base_Type, Loc),
4641                    Constant_Present    => True,
4642                    Expression          =>
4643                      Make_Type_Conversion (Loc,
4644                        Subtype_Mark =>
4645                          New_Occurrence_Of (Target_Base_Type, Loc),
4646                        Expression   => Duplicate_Subexpr (N))),
4647
4648                  Make_Raise_Constraint_Error (Loc,
4649                    Condition =>
4650                      Make_Or_Else (Loc,
4651                        Left_Opnd =>
4652                          Make_Op_Lt (Loc,
4653                            Left_Opnd  => Duplicate_Subexpr (N),
4654                            Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4655
4656                        Right_Opnd =>
4657                          Make_Not_In (Loc,
4658                            Left_Opnd  => New_Occurrence_Of (Tnn, Loc),
4659                            Right_Opnd =>
4660                              New_Occurrence_Of (Target_Type, Loc))),
4661
4662                    Reason => Reason)),
4663                  Suppress => All_Checks);
4664
4665                --  Set the Etype explicitly, because Insert_Actions may have
4666                --  placed the declaration in the freeze list for an enclosing
4667                --  construct, and thus it is not analyzed yet.
4668
4669                Set_Etype (Tnn, Target_Base_Type);
4670                Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4671             end;
4672          end if;
4673       end if;
4674    end Generate_Range_Check;
4675
4676    ------------------
4677    -- Get_Check_Id --
4678    ------------------
4679
4680    function Get_Check_Id (N : Name_Id) return Check_Id is
4681    begin
4682       --  For standard check name, we can do a direct computation
4683
4684       if N in First_Check_Name .. Last_Check_Name then
4685          return Check_Id (N - (First_Check_Name - 1));
4686
4687       --  For non-standard names added by pragma Check_Name, search table
4688
4689       else
4690          for J in All_Checks + 1 .. Check_Names.Last loop
4691             if Check_Names.Table (J) = N then
4692                return J;
4693             end if;
4694          end loop;
4695       end if;
4696
4697       --  No matching name found
4698
4699       return No_Check_Id;
4700    end Get_Check_Id;
4701
4702    ---------------------
4703    -- Get_Discriminal --
4704    ---------------------
4705
4706    function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
4707       Loc : constant Source_Ptr := Sloc (E);
4708       D   : Entity_Id;
4709       Sc  : Entity_Id;
4710
4711    begin
4712       --  The bound can be a bona fide parameter of a protected operation,
4713       --  rather than a prival encoded as an in-parameter.
4714
4715       if No (Discriminal_Link (Entity (Bound))) then
4716          return Bound;
4717       end if;
4718
4719       --  Climb the scope stack looking for an enclosing protected type. If
4720       --  we run out of scopes, return the bound itself.
4721
4722       Sc := Scope (E);
4723       while Present (Sc) loop
4724          if Sc = Standard_Standard then
4725             return Bound;
4726
4727          elsif Ekind (Sc) = E_Protected_Type then
4728             exit;
4729          end if;
4730
4731          Sc := Scope (Sc);
4732       end loop;
4733
4734       D := First_Discriminant (Sc);
4735       while Present (D) loop
4736          if Chars (D) = Chars (Bound) then
4737             return New_Occurrence_Of (Discriminal (D), Loc);
4738          end if;
4739
4740          Next_Discriminant (D);
4741       end loop;
4742
4743       return Bound;
4744    end Get_Discriminal;
4745
4746    ----------------------
4747    -- Get_Range_Checks --
4748    ----------------------
4749
4750    function Get_Range_Checks
4751      (Ck_Node    : Node_Id;
4752       Target_Typ : Entity_Id;
4753       Source_Typ : Entity_Id := Empty;
4754       Warn_Node  : Node_Id   := Empty) return Check_Result
4755    is
4756    begin
4757       return Selected_Range_Checks
4758         (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
4759    end Get_Range_Checks;
4760
4761    ------------------
4762    -- Guard_Access --
4763    ------------------
4764
4765    function Guard_Access
4766      (Cond    : Node_Id;
4767       Loc     : Source_Ptr;
4768       Ck_Node : Node_Id) return Node_Id
4769    is
4770    begin
4771       if Nkind (Cond) = N_Or_Else then
4772          Set_Paren_Count (Cond, 1);
4773       end if;
4774
4775       if Nkind (Ck_Node) = N_Allocator then
4776          return Cond;
4777       else
4778          return
4779            Make_And_Then (Loc,
4780              Left_Opnd =>
4781                Make_Op_Ne (Loc,
4782                  Left_Opnd  => Duplicate_Subexpr_No_Checks (Ck_Node),
4783                  Right_Opnd => Make_Null (Loc)),
4784              Right_Opnd => Cond);
4785       end if;
4786    end Guard_Access;
4787
4788    -----------------------------
4789    -- Index_Checks_Suppressed --
4790    -----------------------------
4791
4792    function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
4793    begin
4794       if Present (E) and then Checks_May_Be_Suppressed (E) then
4795          return Is_Check_Suppressed (E, Index_Check);
4796       else
4797          return Scope_Suppress (Index_Check);
4798       end if;
4799    end Index_Checks_Suppressed;
4800
4801    ----------------
4802    -- Initialize --
4803    ----------------
4804
4805    procedure Initialize is
4806    begin
4807       for J in Determine_Range_Cache_N'Range loop
4808          Determine_Range_Cache_N (J) := Empty;
4809       end loop;
4810
4811       Check_Names.Init;
4812
4813       for J in Int range 1 .. All_Checks loop
4814          Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
4815       end loop;
4816    end Initialize;
4817
4818    -------------------------
4819    -- Insert_Range_Checks --
4820    -------------------------
4821
4822    procedure Insert_Range_Checks
4823      (Checks       : Check_Result;
4824       Node         : Node_Id;
4825       Suppress_Typ : Entity_Id;
4826       Static_Sloc  : Source_Ptr := No_Location;
4827       Flag_Node    : Node_Id    := Empty;
4828       Do_Before    : Boolean    := False)
4829    is
4830       Internal_Flag_Node   : Node_Id    := Flag_Node;
4831       Internal_Static_Sloc : Source_Ptr := Static_Sloc;
4832
4833       Check_Node : Node_Id;
4834       Checks_On  : constant Boolean :=
4835                      (not Index_Checks_Suppressed (Suppress_Typ))
4836                        or else
4837                      (not Range_Checks_Suppressed (Suppress_Typ));
4838
4839    begin
4840       --  For now we just return if Checks_On is false, however this should be
4841       --  enhanced to check for an always True value in the condition and to
4842       --  generate a compilation warning???
4843
4844       if not Expander_Active or else not Checks_On then
4845          return;
4846       end if;
4847
4848       if Static_Sloc = No_Location then
4849          Internal_Static_Sloc := Sloc (Node);
4850       end if;
4851
4852       if No (Flag_Node) then
4853          Internal_Flag_Node := Node;
4854       end if;
4855
4856       for J in 1 .. 2 loop
4857          exit when No (Checks (J));
4858
4859          if Nkind (Checks (J)) = N_Raise_Constraint_Error
4860            and then Present (Condition (Checks (J)))
4861          then
4862             if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
4863                Check_Node := Checks (J);
4864                Mark_Rewrite_Insertion (Check_Node);
4865
4866                if Do_Before then
4867                   Insert_Before_And_Analyze (Node, Check_Node);
4868                else
4869                   Insert_After_And_Analyze (Node, Check_Node);
4870                end if;
4871
4872                Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
4873             end if;
4874
4875          else
4876             Check_Node :=
4877               Make_Raise_Constraint_Error (Internal_Static_Sloc,
4878                 Reason => CE_Range_Check_Failed);
4879             Mark_Rewrite_Insertion (Check_Node);
4880
4881             if Do_Before then
4882                Insert_Before_And_Analyze (Node, Check_Node);
4883             else
4884                Insert_After_And_Analyze (Node, Check_Node);
4885             end if;
4886          end if;
4887       end loop;
4888    end Insert_Range_Checks;
4889
4890    ------------------------
4891    -- Insert_Valid_Check --
4892    ------------------------
4893
4894    procedure Insert_Valid_Check (Expr : Node_Id) is
4895       Loc : constant Source_Ptr := Sloc (Expr);
4896       Exp : Node_Id;
4897
4898    begin
4899       --  Do not insert if checks off, or if not checking validity
4900
4901       if not Validity_Checks_On
4902         or else Range_Or_Validity_Checks_Suppressed (Expr)
4903       then
4904          return;
4905       end if;
4906
4907       --  If we have a checked conversion, then validity check applies to
4908       --  the expression inside the conversion, not the result, since if
4909       --  the expression inside is valid, then so is the conversion result.
4910
4911       Exp := Expr;
4912       while Nkind (Exp) = N_Type_Conversion loop
4913          Exp := Expression (Exp);
4914       end loop;
4915
4916       --  We are about to insert the validity check for Exp. We save and
4917       --  reset the Do_Range_Check flag over this validity check, and then
4918       --  put it back for the final original reference (Exp may be rewritten).
4919
4920       declare
4921          DRC : constant Boolean := Do_Range_Check (Exp);
4922
4923       begin
4924          Set_Do_Range_Check (Exp, False);
4925
4926          --  Insert the validity check. Note that we do this with validity
4927          --  checks turned off, to avoid recursion, we do not want validity
4928          --  checks on the validity checking code itself!
4929
4930          Insert_Action
4931            (Expr,
4932             Make_Raise_Constraint_Error (Loc,
4933               Condition =>
4934                 Make_Op_Not (Loc,
4935                   Right_Opnd =>
4936                     Make_Attribute_Reference (Loc,
4937                       Prefix =>
4938                         Duplicate_Subexpr_No_Checks (Exp, Name_Req => True),
4939                       Attribute_Name => Name_Valid)),
4940               Reason => CE_Invalid_Data),
4941             Suppress => Validity_Check);
4942
4943          --  If the expression is a a reference to an element of a bit-packed
4944          --  array, then it is rewritten as a renaming declaration. If the
4945          --  expression is an actual in a call, it has not been expanded,
4946          --  waiting for the proper point at which to do it. The same happens
4947          --  with renamings, so that we have to force the expansion now. This
4948          --  non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
4949          --  and exp_ch6.adb.
4950
4951          if Is_Entity_Name (Exp)
4952            and then Nkind (Parent (Entity (Exp))) =
4953                       N_Object_Renaming_Declaration
4954          then
4955             declare
4956                Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
4957             begin
4958                if Nkind (Old_Exp) = N_Indexed_Component
4959                  and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
4960                then
4961                   Expand_Packed_Element_Reference (Old_Exp);
4962                end if;
4963             end;
4964          end if;
4965
4966          --  Put back the Do_Range_Check flag on the resulting (possibly
4967          --  rewritten) expression.
4968
4969          --  Note: it might be thought that a validity check is not required
4970          --  when a range check is present, but that's not the case, because
4971          --  the back end is allowed to assume for the range check that the
4972          --  operand is within its declared range (an assumption that validity
4973          --  checking is all about NOT assuming!)
4974
4975          --  Note: no need to worry about Possible_Local_Raise here, it will
4976          --  already have been called if original node has Do_Range_Check set.
4977
4978          Set_Do_Range_Check (Exp, DRC);
4979       end;
4980    end Insert_Valid_Check;
4981
4982    ----------------------------------
4983    -- Install_Null_Excluding_Check --
4984    ----------------------------------
4985
4986    procedure Install_Null_Excluding_Check (N : Node_Id) is
4987       Loc : constant Source_Ptr := Sloc (N);
4988       Typ : constant Entity_Id  := Etype (N);
4989
4990       function In_Declarative_Region_Of_Subprogram_Body return Boolean;
4991       --  Determine whether node N, a reference to an *in* parameter, is
4992       --  inside the declarative region of the current subprogram body.
4993
4994       procedure Mark_Non_Null;
4995       --  After installation of check, if the node in question is an entity
4996       --  name, then mark this entity as non-null if possible.
4997
4998       ----------------------------------------------
4999       -- In_Declarative_Region_Of_Subprogram_Body --
5000       ----------------------------------------------
5001
5002       function In_Declarative_Region_Of_Subprogram_Body return Boolean is
5003          E     : constant Entity_Id := Entity (N);
5004          S     : constant Entity_Id := Current_Scope;
5005          S_Par : Node_Id;
5006
5007       begin
5008          pragma Assert (Ekind (E) = E_In_Parameter);
5009
5010          --  Two initial context checks. We must be inside a subprogram body
5011          --  with declarations and reference must not appear in nested scopes.
5012
5013          if (Ekind (S) /= E_Function
5014              and then Ekind (S) /= E_Procedure)
5015            or else Scope (E) /= S
5016          then
5017             return False;
5018          end if;
5019
5020          S_Par := Parent (Parent (S));
5021
5022          if Nkind (S_Par) /= N_Subprogram_Body
5023            or else No (Declarations (S_Par))
5024          then
5025             return False;
5026          end if;
5027
5028          declare
5029             N_Decl : Node_Id;
5030             P      : Node_Id;
5031
5032          begin
5033             --  Retrieve the declaration node of N (if any). Note that N
5034             --  may be a part of a complex initialization expression.
5035
5036             P := Parent (N);
5037             N_Decl := Empty;
5038             while Present (P) loop
5039
5040                --  While traversing the parent chain, we find that N
5041                --  belongs to a statement, thus it may never appear in
5042                --  a declarative region.
5043
5044                if Nkind (P) in N_Statement_Other_Than_Procedure_Call
5045                  or else Nkind (P) = N_Procedure_Call_Statement
5046                then
5047                   return False;
5048                end if;
5049
5050                if Nkind (P) in N_Declaration
5051                  and then Nkind (P) not in N_Subprogram_Specification
5052                then
5053                   N_Decl := P;
5054                   exit;
5055                end if;
5056
5057                P := Parent (P);
5058             end loop;
5059
5060             if No (N_Decl) then
5061                return False;
5062             end if;
5063
5064             return List_Containing (N_Decl) = Declarations (S_Par);
5065          end;
5066       end In_Declarative_Region_Of_Subprogram_Body;
5067
5068       -------------------
5069       -- Mark_Non_Null --
5070       -------------------
5071
5072       procedure Mark_Non_Null is
5073       begin
5074          --  Only case of interest is if node N is an entity name
5075
5076          if Is_Entity_Name (N) then
5077
5078             --  For sure, we want to clear an indication that this is known to
5079             --  be null, since if we get past this check, it definitely is not!
5080
5081             Set_Is_Known_Null (Entity (N), False);
5082
5083             --  We can mark the entity as known to be non-null if either it is
5084             --  safe to capture the value, or in the case of an IN parameter,
5085             --  which is a constant, if the check we just installed is in the
5086             --  declarative region of the subprogram body. In this latter case,
5087             --  a check is decisive for the rest of the body, since we know we
5088             --  must complete all declarations before executing the body.
5089
5090             if Safe_To_Capture_Value (N, Entity (N))
5091               or else
5092                 (Ekind (Entity (N)) = E_In_Parameter
5093                    and then In_Declarative_Region_Of_Subprogram_Body)
5094             then
5095                Set_Is_Known_Non_Null (Entity (N));
5096             end if;
5097          end if;
5098       end Mark_Non_Null;
5099
5100    --  Start of processing for Install_Null_Excluding_Check
5101
5102    begin
5103       pragma Assert (Is_Access_Type (Typ));
5104
5105       --  No check inside a generic (why not???)
5106
5107       if Inside_A_Generic then
5108          return;
5109       end if;
5110
5111       --  No check needed if known to be non-null
5112
5113       if Known_Non_Null (N) then
5114          return;
5115       end if;
5116
5117       --  If known to be null, here is where we generate a compile time check
5118
5119       if Known_Null (N) then
5120          Apply_Compile_Time_Constraint_Error
5121            (N,
5122             "null value not allowed here?",
5123             CE_Access_Check_Failed);
5124          Mark_Non_Null;
5125          return;
5126       end if;
5127
5128       --  If entity is never assigned, for sure a warning is appropriate
5129
5130       if Is_Entity_Name (N) then
5131          Check_Unset_Reference (N);
5132       end if;
5133
5134       --  No check needed if checks are suppressed on the range. Note that we
5135       --  don't set Is_Known_Non_Null in this case (we could legitimately do
5136       --  so, since the program is erroneous, but we don't like to casually
5137       --  propagate such conclusions from erroneosity).
5138
5139       if Access_Checks_Suppressed (Typ) then
5140          return;
5141       end if;
5142
5143       --  No check needed for access to concurrent record types generated by
5144       --  the expander. This is not just an optimization (though it does indeed
5145       --  remove junk checks). It also avoids generation of junk warnings.
5146
5147       if Nkind (N) in N_Has_Chars
5148         and then Chars (N) = Name_uObject
5149         and then Is_Concurrent_Record_Type
5150                    (Directly_Designated_Type (Etype (N)))
5151       then
5152          return;
5153       end if;
5154
5155       --  Otherwise install access check
5156
5157       Insert_Action (N,
5158         Make_Raise_Constraint_Error (Loc,
5159           Condition =>
5160             Make_Op_Eq (Loc,
5161               Left_Opnd  => Duplicate_Subexpr_Move_Checks (N),
5162               Right_Opnd => Make_Null (Loc)),
5163           Reason => CE_Access_Check_Failed));
5164
5165       Mark_Non_Null;
5166    end Install_Null_Excluding_Check;
5167
5168    --------------------------
5169    -- Install_Static_Check --
5170    --------------------------
5171
5172    procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
5173       Stat : constant Boolean   := Is_Static_Expression (R_Cno);
5174       Typ  : constant Entity_Id := Etype (R_Cno);
5175
5176    begin
5177       Rewrite (R_Cno,
5178         Make_Raise_Constraint_Error (Loc,
5179           Reason => CE_Range_Check_Failed));
5180       Set_Analyzed (R_Cno);
5181       Set_Etype (R_Cno, Typ);
5182       Set_Raises_Constraint_Error (R_Cno);
5183       Set_Is_Static_Expression (R_Cno, Stat);
5184    end Install_Static_Check;
5185
5186    ---------------------
5187    -- Kill_All_Checks --
5188    ---------------------
5189
5190    procedure Kill_All_Checks is
5191    begin
5192       if Debug_Flag_CC then
5193          w ("Kill_All_Checks");
5194       end if;
5195
5196       --  We reset the number of saved checks to zero, and also modify all
5197       --  stack entries for statement ranges to indicate that the number of
5198       --  checks at each level is now zero.
5199
5200       Num_Saved_Checks := 0;
5201
5202       for J in 1 .. Saved_Checks_TOS loop
5203          Saved_Checks_Stack (J) := 0;
5204       end loop;
5205    end Kill_All_Checks;
5206
5207    -----------------
5208    -- Kill_Checks --
5209    -----------------
5210
5211    procedure Kill_Checks (V : Entity_Id) is
5212    begin
5213       if Debug_Flag_CC then
5214          w ("Kill_Checks for entity", Int (V));
5215       end if;
5216
5217       for J in 1 .. Num_Saved_Checks loop
5218          if Saved_Checks (J).Entity = V then
5219             if Debug_Flag_CC then
5220                w ("   Checks killed for saved check ", J);
5221             end if;
5222
5223             Saved_Checks (J).Killed := True;
5224          end if;
5225       end loop;
5226    end Kill_Checks;
5227
5228    ------------------------------
5229    -- Length_Checks_Suppressed --
5230    ------------------------------
5231
5232    function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
5233    begin
5234       if Present (E) and then Checks_May_Be_Suppressed (E) then
5235          return Is_Check_Suppressed (E, Length_Check);
5236       else
5237          return Scope_Suppress (Length_Check);
5238       end if;
5239    end Length_Checks_Suppressed;
5240
5241    --------------------------------
5242    -- Overflow_Checks_Suppressed --
5243    --------------------------------
5244
5245    function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
5246    begin
5247       if Present (E) and then Checks_May_Be_Suppressed (E) then
5248          return Is_Check_Suppressed (E, Overflow_Check);
5249       else
5250          return Scope_Suppress (Overflow_Check);
5251       end if;
5252    end Overflow_Checks_Suppressed;
5253    -----------------------------
5254    -- Range_Checks_Suppressed --
5255    -----------------------------
5256
5257    function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
5258    begin
5259       if Present (E) then
5260
5261          --  Note: for now we always suppress range checks on Vax float types,
5262          --  since Gigi does not know how to generate these checks.
5263
5264          if Vax_Float (E) then
5265             return True;
5266          elsif Kill_Range_Checks (E) then
5267             return True;
5268          elsif Checks_May_Be_Suppressed (E) then
5269             return Is_Check_Suppressed (E, Range_Check);
5270          end if;
5271       end if;
5272
5273       return Scope_Suppress (Range_Check);
5274    end Range_Checks_Suppressed;
5275
5276    -----------------------------------------
5277    -- Range_Or_Validity_Checks_Suppressed --
5278    -----------------------------------------
5279
5280    --  Note: the coding would be simpler here if we simply made appropriate
5281    --  calls to Range/Validity_Checks_Suppressed, but that would result in
5282    --  duplicated checks which we prefer to avoid.
5283
5284    function Range_Or_Validity_Checks_Suppressed
5285      (Expr : Node_Id) return Boolean
5286    is
5287    begin
5288       --  Immediate return if scope checks suppressed for either check
5289
5290       if Scope_Suppress (Range_Check) or Scope_Suppress (Validity_Check) then
5291          return True;
5292       end if;
5293
5294       --  If no expression, that's odd, decide that checks are suppressed,
5295       --  since we don't want anyone trying to do checks in this case, which
5296       --  is most likely the result of some other error.
5297
5298       if No (Expr) then
5299          return True;
5300       end if;
5301
5302       --  Expression is present, so perform suppress checks on type
5303
5304       declare
5305          Typ : constant Entity_Id := Etype (Expr);
5306       begin
5307          if Vax_Float (Typ) then
5308             return True;
5309          elsif Checks_May_Be_Suppressed (Typ)
5310            and then (Is_Check_Suppressed (Typ, Range_Check)
5311                        or else
5312                      Is_Check_Suppressed (Typ, Validity_Check))
5313          then
5314             return True;
5315          end if;
5316       end;
5317
5318       --  If expression is an entity name, perform checks on this entity
5319
5320       if Is_Entity_Name (Expr) then
5321          declare
5322             Ent : constant Entity_Id := Entity (Expr);
5323          begin
5324             if Checks_May_Be_Suppressed (Ent) then
5325                return Is_Check_Suppressed (Ent, Range_Check)
5326                  or else Is_Check_Suppressed (Ent, Validity_Check);
5327             end if;
5328          end;
5329       end if;
5330
5331       --  If we fall through, no checks suppressed
5332
5333       return False;
5334    end Range_Or_Validity_Checks_Suppressed;
5335
5336    -------------------
5337    -- Remove_Checks --
5338    -------------------
5339
5340    procedure Remove_Checks (Expr : Node_Id) is
5341       Discard : Traverse_Result;
5342       pragma Warnings (Off, Discard);
5343
5344       function Process (N : Node_Id) return Traverse_Result;
5345       --  Process a single node during the traversal
5346
5347       function Traverse is new Traverse_Func (Process);
5348       --  The traversal function itself
5349
5350       -------------
5351       -- Process --
5352       -------------
5353
5354       function Process (N : Node_Id) return Traverse_Result is
5355       begin
5356          if Nkind (N) not in N_Subexpr then
5357             return Skip;
5358          end if;
5359
5360          Set_Do_Range_Check (N, False);
5361
5362          case Nkind (N) is
5363             when N_And_Then =>
5364                Discard := Traverse (Left_Opnd (N));
5365                return Skip;
5366
5367             when N_Attribute_Reference =>
5368                Set_Do_Overflow_Check (N, False);
5369
5370             when N_Function_Call =>
5371                Set_Do_Tag_Check (N, False);
5372
5373             when N_Op =>
5374                Set_Do_Overflow_Check (N, False);
5375
5376                case Nkind (N) is
5377                   when N_Op_Divide =>
5378                      Set_Do_Division_Check (N, False);
5379
5380                   when N_Op_And =>
5381                      Set_Do_Length_Check (N, False);
5382
5383                   when N_Op_Mod =>
5384                      Set_Do_Division_Check (N, False);
5385
5386                   when N_Op_Or =>
5387                      Set_Do_Length_Check (N, False);
5388
5389                   when N_Op_Rem =>
5390                      Set_Do_Division_Check (N, False);
5391
5392                   when N_Op_Xor =>
5393                      Set_Do_Length_Check (N, False);
5394
5395                   when others =>
5396                      null;
5397                end case;
5398
5399             when N_Or_Else =>
5400                Discard := Traverse (Left_Opnd (N));
5401                return Skip;
5402
5403             when N_Selected_Component =>
5404                Set_Do_Discriminant_Check (N, False);
5405
5406             when N_Type_Conversion =>
5407                Set_Do_Length_Check   (N, False);
5408                Set_Do_Tag_Check      (N, False);
5409                Set_Do_Overflow_Check (N, False);
5410
5411             when others =>
5412                null;
5413          end case;
5414
5415          return OK;
5416       end Process;
5417
5418    --  Start of processing for Remove_Checks
5419
5420    begin
5421       Discard := Traverse (Expr);
5422    end Remove_Checks;
5423
5424    ----------------------------
5425    -- Selected_Length_Checks --
5426    ----------------------------
5427
5428    function Selected_Length_Checks
5429      (Ck_Node    : Node_Id;
5430       Target_Typ : Entity_Id;
5431       Source_Typ : Entity_Id;
5432       Warn_Node  : Node_Id) return Check_Result
5433    is
5434       Loc         : constant Source_Ptr := Sloc (Ck_Node);
5435       S_Typ       : Entity_Id;
5436       T_Typ       : Entity_Id;
5437       Expr_Actual : Node_Id;
5438       Exptyp      : Entity_Id;
5439       Cond        : Node_Id := Empty;
5440       Do_Access   : Boolean := False;
5441       Wnode       : Node_Id := Warn_Node;
5442       Ret_Result  : Check_Result := (Empty, Empty);
5443       Num_Checks  : Natural := 0;
5444
5445       procedure Add_Check (N : Node_Id);
5446       --  Adds the action given to Ret_Result if N is non-Empty
5447
5448       function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
5449       function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
5450       --  Comments required ???
5451
5452       function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
5453       --  True for equal literals and for nodes that denote the same constant
5454       --  entity, even if its value is not a static constant. This includes the
5455       --  case of a discriminal reference within an init proc. Removes some
5456       --  obviously superfluous checks.
5457
5458       function Length_E_Cond
5459         (Exptyp : Entity_Id;
5460          Typ    : Entity_Id;
5461          Indx   : Nat) return Node_Id;
5462       --  Returns expression to compute:
5463       --    Typ'Length /= Exptyp'Length
5464
5465       function Length_N_Cond
5466         (Expr : Node_Id;
5467          Typ  : Entity_Id;
5468          Indx : Nat) return Node_Id;
5469       --  Returns expression to compute:
5470       --    Typ'Length /= Expr'Length
5471
5472       ---------------
5473       -- Add_Check --
5474       ---------------
5475
5476       procedure Add_Check (N : Node_Id) is
5477       begin
5478          if Present (N) then
5479
5480             --  For now, ignore attempt to place more than 2 checks ???
5481
5482             if Num_Checks = 2 then
5483                return;
5484             end if;
5485
5486             pragma Assert (Num_Checks <= 1);
5487             Num_Checks := Num_Checks + 1;
5488             Ret_Result (Num_Checks) := N;
5489          end if;
5490       end Add_Check;
5491
5492       ------------------
5493       -- Get_E_Length --
5494       ------------------
5495
5496       function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
5497          SE : constant Entity_Id := Scope (E);
5498          N  : Node_Id;
5499          E1 : Entity_Id := E;
5500
5501       begin
5502          if Ekind (Scope (E)) = E_Record_Type
5503            and then Has_Discriminants (Scope (E))
5504          then
5505             N := Build_Discriminal_Subtype_Of_Component (E);
5506
5507             if Present (N) then
5508                Insert_Action (Ck_Node, N);
5509                E1 := Defining_Identifier (N);
5510             end if;
5511          end if;
5512
5513          if Ekind (E1) = E_String_Literal_Subtype then
5514             return
5515               Make_Integer_Literal (Loc,
5516                 Intval => String_Literal_Length (E1));
5517
5518          elsif SE /= Standard_Standard
5519            and then Ekind (Scope (SE)) = E_Protected_Type
5520            and then Has_Discriminants (Scope (SE))
5521            and then Has_Completion (Scope (SE))
5522            and then not Inside_Init_Proc
5523          then
5524             --  If the type whose length is needed is a private component
5525             --  constrained by a discriminant, we must expand the 'Length
5526             --  attribute into an explicit computation, using the discriminal
5527             --  of the current protected operation. This is because the actual
5528             --  type of the prival is constructed after the protected opera-
5529             --  tion has been fully expanded.
5530
5531             declare
5532                Indx_Type : Node_Id;
5533                Lo        : Node_Id;
5534                Hi        : Node_Id;
5535                Do_Expand : Boolean := False;
5536
5537             begin
5538                Indx_Type := First_Index (E);
5539
5540                for J in 1 .. Indx - 1 loop
5541                   Next_Index (Indx_Type);
5542                end loop;
5543
5544                Get_Index_Bounds (Indx_Type, Lo, Hi);
5545
5546                if Nkind (Lo) = N_Identifier
5547                  and then Ekind (Entity (Lo)) = E_In_Parameter
5548                then
5549                   Lo := Get_Discriminal (E, Lo);
5550                   Do_Expand := True;
5551                end if;
5552
5553                if Nkind (Hi) = N_Identifier
5554                  and then Ekind (Entity (Hi)) = E_In_Parameter
5555                then
5556                   Hi := Get_Discriminal (E, Hi);
5557                   Do_Expand := True;
5558                end if;
5559
5560                if Do_Expand then
5561                   if not Is_Entity_Name (Lo) then
5562                      Lo := Duplicate_Subexpr_No_Checks (Lo);
5563                   end if;
5564
5565                   if not Is_Entity_Name (Hi) then
5566                      Lo := Duplicate_Subexpr_No_Checks (Hi);
5567                   end if;
5568
5569                   N :=
5570                     Make_Op_Add (Loc,
5571                       Left_Opnd =>
5572                         Make_Op_Subtract (Loc,
5573                           Left_Opnd  => Hi,
5574                           Right_Opnd => Lo),
5575
5576                       Right_Opnd => Make_Integer_Literal (Loc, 1));
5577                   return N;
5578
5579                else
5580                   N :=
5581                     Make_Attribute_Reference (Loc,
5582                       Attribute_Name => Name_Length,
5583                       Prefix =>
5584                         New_Occurrence_Of (E1, Loc));
5585
5586                   if Indx > 1 then
5587                      Set_Expressions (N, New_List (
5588                        Make_Integer_Literal (Loc, Indx)));
5589                   end if;
5590
5591                   return N;
5592                end if;
5593             end;
5594
5595          else
5596             N :=
5597               Make_Attribute_Reference (Loc,
5598                 Attribute_Name => Name_Length,
5599                 Prefix =>
5600                   New_Occurrence_Of (E1, Loc));
5601
5602             if Indx > 1 then
5603                Set_Expressions (N, New_List (
5604                  Make_Integer_Literal (Loc, Indx)));
5605             end if;
5606
5607             return N;
5608          end if;
5609       end Get_E_Length;
5610
5611       ------------------
5612       -- Get_N_Length --
5613       ------------------
5614
5615       function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
5616       begin
5617          return
5618            Make_Attribute_Reference (Loc,
5619              Attribute_Name => Name_Length,
5620              Prefix =>
5621                Duplicate_Subexpr_No_Checks (N, Name_Req => True),
5622              Expressions => New_List (
5623                Make_Integer_Literal (Loc, Indx)));
5624       end Get_N_Length;
5625
5626       -------------------
5627       -- Length_E_Cond --
5628       -------------------
5629
5630       function Length_E_Cond
5631         (Exptyp : Entity_Id;
5632          Typ    : Entity_Id;
5633          Indx   : Nat) return Node_Id
5634       is
5635       begin
5636          return
5637            Make_Op_Ne (Loc,
5638              Left_Opnd  => Get_E_Length (Typ, Indx),
5639              Right_Opnd => Get_E_Length (Exptyp, Indx));
5640       end Length_E_Cond;
5641
5642       -------------------
5643       -- Length_N_Cond --
5644       -------------------
5645
5646       function Length_N_Cond
5647         (Expr : Node_Id;
5648          Typ  : Entity_Id;
5649          Indx : Nat) return Node_Id
5650       is
5651       begin
5652          return
5653            Make_Op_Ne (Loc,
5654              Left_Opnd  => Get_E_Length (Typ, Indx),
5655              Right_Opnd => Get_N_Length (Expr, Indx));
5656       end Length_N_Cond;
5657
5658       -----------------
5659       -- Same_Bounds --
5660       -----------------
5661
5662       function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
5663       begin
5664          return
5665            (Nkind (L) = N_Integer_Literal
5666              and then Nkind (R) = N_Integer_Literal
5667              and then Intval (L) = Intval (R))
5668
5669           or else
5670             (Is_Entity_Name (L)
5671               and then Ekind (Entity (L)) = E_Constant
5672               and then ((Is_Entity_Name (R)
5673                          and then Entity (L) = Entity (R))
5674                         or else
5675                        (Nkind (R) = N_Type_Conversion
5676                          and then Is_Entity_Name (Expression (R))
5677                          and then Entity (L) = Entity (Expression (R)))))
5678
5679           or else
5680             (Is_Entity_Name (R)
5681               and then Ekind (Entity (R)) = E_Constant
5682               and then Nkind (L) = N_Type_Conversion
5683               and then Is_Entity_Name (Expression (L))
5684               and then Entity (R) = Entity (Expression (L)))
5685
5686          or else
5687             (Is_Entity_Name (L)
5688               and then Is_Entity_Name (R)
5689               and then Entity (L) = Entity (R)
5690               and then Ekind (Entity (L)) = E_In_Parameter
5691               and then Inside_Init_Proc);
5692       end Same_Bounds;
5693
5694    --  Start of processing for Selected_Length_Checks
5695
5696    begin
5697       if not Expander_Active then
5698          return Ret_Result;
5699       end if;
5700
5701       if Target_Typ = Any_Type
5702         or else Target_Typ = Any_Composite
5703         or else Raises_Constraint_Error (Ck_Node)
5704       then
5705          return Ret_Result;
5706       end if;
5707
5708       if No (Wnode) then
5709          Wnode := Ck_Node;
5710       end if;
5711
5712       T_Typ := Target_Typ;
5713
5714       if No (Source_Typ) then
5715          S_Typ := Etype (Ck_Node);
5716       else
5717          S_Typ := Source_Typ;
5718       end if;
5719
5720       if S_Typ = Any_Type or else S_Typ = Any_Composite then
5721          return Ret_Result;
5722       end if;
5723
5724       if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
5725          S_Typ := Designated_Type (S_Typ);
5726          T_Typ := Designated_Type (T_Typ);
5727          Do_Access := True;
5728
5729          --  A simple optimization for the null case
5730
5731          if Known_Null (Ck_Node) then
5732             return Ret_Result;
5733          end if;
5734       end if;
5735
5736       if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
5737          if Is_Constrained (T_Typ) then
5738
5739             --  The checking code to be generated will freeze the
5740             --  corresponding array type. However, we must freeze the
5741             --  type now, so that the freeze node does not appear within
5742             --  the generated condional expression, but ahead of it.
5743
5744             Freeze_Before (Ck_Node, T_Typ);
5745
5746             Expr_Actual := Get_Referenced_Object (Ck_Node);
5747             Exptyp      := Get_Actual_Subtype (Ck_Node);
5748
5749             if Is_Access_Type (Exptyp) then
5750                Exptyp := Designated_Type (Exptyp);
5751             end if;
5752
5753             --  String_Literal case. This needs to be handled specially be-
5754             --  cause no index types are available for string literals. The
5755             --  condition is simply:
5756
5757             --    T_Typ'Length = string-literal-length
5758
5759             if Nkind (Expr_Actual) = N_String_Literal
5760               and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
5761             then
5762                Cond :=
5763                  Make_Op_Ne (Loc,
5764                    Left_Opnd  => Get_E_Length (T_Typ, 1),
5765                    Right_Opnd =>
5766                      Make_Integer_Literal (Loc,
5767                        Intval =>
5768                          String_Literal_Length (Etype (Expr_Actual))));
5769
5770             --  General array case. Here we have a usable actual subtype for
5771             --  the expression, and the condition is built from the two types
5772             --  (Do_Length):
5773
5774             --     T_Typ'Length     /= Exptyp'Length     or else
5775             --     T_Typ'Length (2) /= Exptyp'Length (2) or else
5776             --     T_Typ'Length (3) /= Exptyp'Length (3) or else
5777             --     ...
5778
5779             elsif Is_Constrained (Exptyp) then
5780                declare
5781                   Ndims : constant Nat := Number_Dimensions (T_Typ);
5782
5783                   L_Index  : Node_Id;
5784                   R_Index  : Node_Id;
5785                   L_Low    : Node_Id;
5786                   L_High   : Node_Id;
5787                   R_Low    : Node_Id;
5788                   R_High   : Node_Id;
5789                   L_Length : Uint;
5790                   R_Length : Uint;
5791                   Ref_Node : Node_Id;
5792
5793                begin
5794                   --  At the library level, we need to ensure that the type of
5795                   --  the object is elaborated before the check itself is
5796                   --  emitted. This is only done if the object is in the
5797                   --  current compilation unit, otherwise the type is frozen
5798                   --  and elaborated in its unit.
5799
5800                   if Is_Itype (Exptyp)
5801                     and then
5802                       Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
5803                     and then
5804                       not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
5805                     and then In_Open_Scopes (Scope (Exptyp))
5806                   then
5807                      Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
5808                      Set_Itype (Ref_Node, Exptyp);
5809                      Insert_Action (Ck_Node, Ref_Node);
5810                   end if;
5811
5812                   L_Index := First_Index (T_Typ);
5813                   R_Index := First_Index (Exptyp);
5814
5815                   for Indx in 1 .. Ndims loop
5816                      if not (Nkind (L_Index) = N_Raise_Constraint_Error
5817                                or else
5818                              Nkind (R_Index) = N_Raise_Constraint_Error)
5819                      then
5820                         Get_Index_Bounds (L_Index, L_Low, L_High);
5821                         Get_Index_Bounds (R_Index, R_Low, R_High);
5822
5823                         --  Deal with compile time length check. Note that we
5824                         --  skip this in the access case, because the access
5825                         --  value may be null, so we cannot know statically.
5826
5827                         if not Do_Access
5828                           and then Compile_Time_Known_Value (L_Low)
5829                           and then Compile_Time_Known_Value (L_High)
5830                           and then Compile_Time_Known_Value (R_Low)
5831                           and then Compile_Time_Known_Value (R_High)
5832                         then
5833                            if Expr_Value (L_High) >= Expr_Value (L_Low) then
5834                               L_Length := Expr_Value (L_High) -
5835                                           Expr_Value (L_Low) + 1;
5836                            else
5837                               L_Length := UI_From_Int (0);
5838                            end if;
5839
5840                            if Expr_Value (R_High) >= Expr_Value (R_Low) then
5841                               R_Length := Expr_Value (R_High) -
5842                                           Expr_Value (R_Low) + 1;
5843                            else
5844                               R_Length := UI_From_Int (0);
5845                            end if;
5846
5847                            if L_Length > R_Length then
5848                               Add_Check
5849                                 (Compile_Time_Constraint_Error
5850                                   (Wnode, "too few elements for}?", T_Typ));
5851
5852                            elsif  L_Length < R_Length then
5853                               Add_Check
5854                                 (Compile_Time_Constraint_Error
5855                                   (Wnode, "too many elements for}?", T_Typ));
5856                            end if;
5857
5858                         --  The comparison for an individual index subtype
5859                         --  is omitted if the corresponding index subtypes
5860                         --  statically match, since the result is known to
5861                         --  be true. Note that this test is worth while even
5862                         --  though we do static evaluation, because non-static
5863                         --  subtypes can statically match.
5864
5865                         elsif not
5866                           Subtypes_Statically_Match
5867                             (Etype (L_Index), Etype (R_Index))
5868
5869                           and then not
5870                             (Same_Bounds (L_Low, R_Low)
5871                               and then Same_Bounds (L_High, R_High))
5872                         then
5873                            Evolve_Or_Else
5874                              (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
5875                         end if;
5876
5877                         Next (L_Index);
5878                         Next (R_Index);
5879                      end if;
5880                   end loop;
5881                end;
5882
5883             --  Handle cases where we do not get a usable actual subtype that
5884             --  is constrained. This happens for example in the function call
5885             --  and explicit dereference cases. In these cases, we have to get
5886             --  the length or range from the expression itself, making sure we
5887             --  do not evaluate it more than once.
5888
5889             --  Here Ck_Node is the original expression, or more properly the
5890             --  result of applying Duplicate_Expr to the original tree, forcing
5891             --  the result to be a name.
5892
5893             else
5894                declare
5895                   Ndims : constant Nat := Number_Dimensions (T_Typ);
5896
5897                begin
5898                   --  Build the condition for the explicit dereference case
5899
5900                   for Indx in 1 .. Ndims loop
5901                      Evolve_Or_Else
5902                        (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
5903                   end loop;
5904                end;
5905             end if;
5906          end if;
5907       end if;
5908
5909       --  Construct the test and insert into the tree
5910
5911       if Present (Cond) then
5912          if Do_Access then
5913             Cond := Guard_Access (Cond, Loc, Ck_Node);
5914          end if;
5915
5916          Add_Check
5917            (Make_Raise_Constraint_Error (Loc,
5918               Condition => Cond,
5919               Reason => CE_Length_Check_Failed));
5920       end if;
5921
5922       return Ret_Result;
5923    end Selected_Length_Checks;
5924
5925    ---------------------------
5926    -- Selected_Range_Checks --
5927    ---------------------------
5928
5929    function Selected_Range_Checks
5930      (Ck_Node    : Node_Id;
5931       Target_Typ : Entity_Id;
5932       Source_Typ : Entity_Id;
5933       Warn_Node  : Node_Id) return Check_Result
5934    is
5935       Loc         : constant Source_Ptr := Sloc (Ck_Node);
5936       S_Typ       : Entity_Id;
5937       T_Typ       : Entity_Id;
5938       Expr_Actual : Node_Id;
5939       Exptyp      : Entity_Id;
5940       Cond        : Node_Id := Empty;
5941       Do_Access   : Boolean := False;
5942       Wnode       : Node_Id  := Warn_Node;
5943       Ret_Result  : Check_Result := (Empty, Empty);
5944       Num_Checks  : Integer := 0;
5945
5946       procedure Add_Check (N : Node_Id);
5947       --  Adds the action given to Ret_Result if N is non-Empty
5948
5949       function Discrete_Range_Cond
5950         (Expr : Node_Id;
5951          Typ  : Entity_Id) return Node_Id;
5952       --  Returns expression to compute:
5953       --    Low_Bound (Expr) < Typ'First
5954       --      or else
5955       --    High_Bound (Expr) > Typ'Last
5956
5957       function Discrete_Expr_Cond
5958         (Expr : Node_Id;
5959          Typ  : Entity_Id) return Node_Id;
5960       --  Returns expression to compute:
5961       --    Expr < Typ'First
5962       --      or else
5963       --    Expr > Typ'Last
5964
5965       function Get_E_First_Or_Last
5966         (E    : Entity_Id;
5967          Indx : Nat;
5968          Nam  : Name_Id) return Node_Id;
5969       --  Returns expression to compute:
5970       --    E'First or E'Last
5971
5972       function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
5973       function Get_N_Last  (N : Node_Id; Indx : Nat) return Node_Id;
5974       --  Returns expression to compute:
5975       --    N'First or N'Last using Duplicate_Subexpr_No_Checks
5976
5977       function Range_E_Cond
5978         (Exptyp : Entity_Id;
5979          Typ    : Entity_Id;
5980          Indx   : Nat)
5981          return   Node_Id;
5982       --  Returns expression to compute:
5983       --    Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
5984
5985       function Range_Equal_E_Cond
5986         (Exptyp : Entity_Id;
5987          Typ    : Entity_Id;
5988          Indx   : Nat) return Node_Id;
5989       --  Returns expression to compute:
5990       --    Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
5991
5992       function Range_N_Cond
5993         (Expr : Node_Id;
5994          Typ  : Entity_Id;
5995          Indx : Nat) return Node_Id;
5996       --  Return expression to compute:
5997       --    Expr'First < Typ'First or else Expr'Last > Typ'Last
5998
5999       ---------------
6000       -- Add_Check --
6001       ---------------
6002
6003       procedure Add_Check (N : Node_Id) is
6004       begin
6005          if Present (N) then
6006
6007             --  For now, ignore attempt to place more than 2 checks ???
6008
6009             if Num_Checks = 2 then
6010                return;
6011             end if;
6012
6013             pragma Assert (Num_Checks <= 1);
6014             Num_Checks := Num_Checks + 1;
6015             Ret_Result (Num_Checks) := N;
6016          end if;
6017       end Add_Check;
6018
6019       -------------------------
6020       -- Discrete_Expr_Cond --
6021       -------------------------
6022
6023       function Discrete_Expr_Cond
6024         (Expr : Node_Id;
6025          Typ  : Entity_Id) return Node_Id
6026       is
6027       begin
6028          return
6029            Make_Or_Else (Loc,
6030              Left_Opnd =>
6031                Make_Op_Lt (Loc,
6032                  Left_Opnd =>
6033                    Convert_To (Base_Type (Typ),
6034                      Duplicate_Subexpr_No_Checks (Expr)),
6035                  Right_Opnd =>
6036                    Convert_To (Base_Type (Typ),
6037                                Get_E_First_Or_Last (Typ, 0, Name_First))),
6038
6039              Right_Opnd =>
6040                Make_Op_Gt (Loc,
6041                  Left_Opnd =>
6042                    Convert_To (Base_Type (Typ),
6043                      Duplicate_Subexpr_No_Checks (Expr)),
6044                  Right_Opnd =>
6045                    Convert_To
6046                      (Base_Type (Typ),
6047                       Get_E_First_Or_Last (Typ, 0, Name_Last))));
6048       end Discrete_Expr_Cond;
6049
6050       -------------------------
6051       -- Discrete_Range_Cond --
6052       -------------------------
6053
6054       function Discrete_Range_Cond
6055         (Expr : Node_Id;
6056          Typ  : Entity_Id) return Node_Id
6057       is
6058          LB : Node_Id := Low_Bound (Expr);
6059          HB : Node_Id := High_Bound (Expr);
6060
6061          Left_Opnd  : Node_Id;
6062          Right_Opnd : Node_Id;
6063
6064       begin
6065          if Nkind (LB) = N_Identifier
6066            and then Ekind (Entity (LB)) = E_Discriminant
6067          then
6068             LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6069          end if;
6070
6071          if Nkind (HB) = N_Identifier
6072            and then Ekind (Entity (HB)) = E_Discriminant
6073          then
6074             HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6075          end if;
6076
6077          Left_Opnd :=
6078            Make_Op_Lt (Loc,
6079              Left_Opnd  =>
6080                Convert_To
6081                  (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
6082
6083              Right_Opnd =>
6084                Convert_To
6085                  (Base_Type (Typ), Get_E_First_Or_Last (Typ, 0, Name_First)));
6086
6087          if Base_Type (Typ) = Typ then
6088             return Left_Opnd;
6089
6090          elsif Compile_Time_Known_Value (High_Bound (Scalar_Range (Typ)))
6091             and then
6092                Compile_Time_Known_Value (High_Bound (Scalar_Range
6093                                                      (Base_Type (Typ))))
6094          then
6095             if Is_Floating_Point_Type (Typ) then
6096                if Expr_Value_R (High_Bound (Scalar_Range (Typ))) =
6097                   Expr_Value_R (High_Bound (Scalar_Range (Base_Type (Typ))))
6098                then
6099                   return Left_Opnd;
6100                end if;
6101
6102             else
6103                if Expr_Value (High_Bound (Scalar_Range (Typ))) =
6104                   Expr_Value (High_Bound (Scalar_Range (Base_Type (Typ))))
6105                then
6106                   return Left_Opnd;
6107                end if;
6108             end if;
6109          end if;
6110
6111          Right_Opnd :=
6112            Make_Op_Gt (Loc,
6113              Left_Opnd  =>
6114                Convert_To
6115                  (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
6116
6117              Right_Opnd =>
6118                Convert_To
6119                  (Base_Type (Typ),
6120                   Get_E_First_Or_Last (Typ, 0, Name_Last)));
6121
6122          return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
6123       end Discrete_Range_Cond;
6124
6125       -------------------------
6126       -- Get_E_First_Or_Last --
6127       -------------------------
6128
6129       function Get_E_First_Or_Last
6130         (E    : Entity_Id;
6131          Indx : Nat;
6132          Nam  : Name_Id) return Node_Id
6133       is
6134          N     : Node_Id;
6135          LB    : Node_Id;
6136          HB    : Node_Id;
6137          Bound : Node_Id;
6138
6139       begin
6140          if Is_Array_Type (E) then
6141             N := First_Index (E);
6142
6143             for J in 2 .. Indx loop
6144                Next_Index (N);
6145             end loop;
6146
6147          else
6148             N := Scalar_Range (E);
6149          end if;
6150
6151          if Nkind (N) = N_Subtype_Indication then
6152             LB := Low_Bound (Range_Expression (Constraint (N)));
6153             HB := High_Bound (Range_Expression (Constraint (N)));
6154
6155          elsif Is_Entity_Name (N) then
6156             LB := Type_Low_Bound  (Etype (N));
6157             HB := Type_High_Bound (Etype (N));
6158
6159          else
6160             LB := Low_Bound  (N);
6161             HB := High_Bound (N);
6162          end if;
6163
6164          if Nam = Name_First then
6165             Bound := LB;
6166          else
6167             Bound := HB;
6168          end if;
6169
6170          if Nkind (Bound) = N_Identifier
6171            and then Ekind (Entity (Bound)) = E_Discriminant
6172          then
6173             --  If this is a task discriminant, and we are the body, we must
6174             --  retrieve the corresponding body discriminal. This is another
6175             --  consequence of the early creation of discriminals, and the
6176             --  need to generate constraint checks before their declarations
6177             --  are made visible.
6178
6179             if Is_Concurrent_Record_Type (Scope (Entity (Bound)))  then
6180                declare
6181                   Tsk : constant Entity_Id :=
6182                           Corresponding_Concurrent_Type
6183                            (Scope (Entity (Bound)));
6184                   Disc : Entity_Id;
6185
6186                begin
6187                   if In_Open_Scopes (Tsk)
6188                     and then Has_Completion (Tsk)
6189                   then
6190                      --  Find discriminant of original task, and use its
6191                      --  current discriminal, which is the renaming within
6192                      --  the task body.
6193
6194                      Disc :=  First_Discriminant (Tsk);
6195                      while Present (Disc) loop
6196                         if Chars (Disc) = Chars (Entity (Bound)) then
6197                            Set_Scope (Discriminal (Disc), Tsk);
6198                            return New_Occurrence_Of (Discriminal (Disc), Loc);
6199                         end if;
6200
6201                         Next_Discriminant (Disc);
6202                      end loop;
6203
6204                      --  That loop should always succeed in finding a matching
6205                      --  entry and returning. Fatal error if not.
6206
6207                      raise Program_Error;
6208
6209                   else
6210                      return
6211                        New_Occurrence_Of (Discriminal (Entity (Bound)), Loc);
6212                   end if;
6213                end;
6214             else
6215                return New_Occurrence_Of (Discriminal (Entity (Bound)), Loc);
6216             end if;
6217
6218          elsif Nkind (Bound) = N_Identifier
6219            and then Ekind (Entity (Bound)) = E_In_Parameter
6220            and then not Inside_Init_Proc
6221          then
6222             return Get_Discriminal (E, Bound);
6223
6224          elsif Nkind (Bound) = N_Integer_Literal then
6225             return Make_Integer_Literal (Loc, Intval (Bound));
6226
6227          --  Case of a bound rewritten to an N_Raise_Constraint_Error node
6228          --  because it is an out-of-range value. Duplicate_Subexpr cannot be
6229          --  called on this node because an N_Raise_Constraint_Error is not
6230          --  side effect free, and we may not assume that we are in the proper
6231          --  context to remove side effects on it at the point of reference.
6232
6233          elsif Nkind (Bound) = N_Raise_Constraint_Error then
6234             return New_Copy_Tree (Bound);
6235
6236          else
6237             return Duplicate_Subexpr_No_Checks (Bound);
6238          end if;
6239       end Get_E_First_Or_Last;
6240
6241       -----------------
6242       -- Get_N_First --
6243       -----------------
6244
6245       function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
6246       begin
6247          return
6248            Make_Attribute_Reference (Loc,
6249              Attribute_Name => Name_First,
6250              Prefix =>
6251                Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6252              Expressions => New_List (
6253                Make_Integer_Literal (Loc, Indx)));
6254       end Get_N_First;
6255
6256       ----------------
6257       -- Get_N_Last --
6258       ----------------
6259
6260       function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
6261       begin
6262          return
6263            Make_Attribute_Reference (Loc,
6264              Attribute_Name => Name_Last,
6265              Prefix =>
6266                Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6267              Expressions => New_List (
6268               Make_Integer_Literal (Loc, Indx)));
6269       end Get_N_Last;
6270
6271       ------------------
6272       -- Range_E_Cond --
6273       ------------------
6274
6275       function Range_E_Cond
6276         (Exptyp : Entity_Id;
6277          Typ    : Entity_Id;
6278          Indx   : Nat) return Node_Id
6279       is
6280       begin
6281          return
6282            Make_Or_Else (Loc,
6283              Left_Opnd =>
6284                Make_Op_Lt (Loc,
6285                  Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_First),
6286                  Right_Opnd  => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6287
6288              Right_Opnd =>
6289                Make_Op_Gt (Loc,
6290                  Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_Last),
6291                  Right_Opnd  => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6292       end Range_E_Cond;
6293
6294       ------------------------
6295       -- Range_Equal_E_Cond --
6296       ------------------------
6297
6298       function Range_Equal_E_Cond
6299         (Exptyp : Entity_Id;
6300          Typ    : Entity_Id;
6301          Indx   : Nat) return Node_Id
6302       is
6303       begin
6304          return
6305            Make_Or_Else (Loc,
6306              Left_Opnd =>
6307                Make_Op_Ne (Loc,
6308                  Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_First),
6309                  Right_Opnd  => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6310              Right_Opnd =>
6311                Make_Op_Ne (Loc,
6312                  Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_Last),
6313                  Right_Opnd  => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6314       end Range_Equal_E_Cond;
6315
6316       ------------------
6317       -- Range_N_Cond --
6318       ------------------
6319
6320       function Range_N_Cond
6321         (Expr : Node_Id;
6322          Typ  : Entity_Id;
6323          Indx : Nat) return Node_Id
6324       is
6325       begin
6326          return
6327            Make_Or_Else (Loc,
6328              Left_Opnd =>
6329                Make_Op_Lt (Loc,
6330                  Left_Opnd => Get_N_First (Expr, Indx),
6331                  Right_Opnd  => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6332
6333              Right_Opnd =>
6334                Make_Op_Gt (Loc,
6335                  Left_Opnd => Get_N_Last (Expr, Indx),
6336                  Right_Opnd  => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6337       end Range_N_Cond;
6338
6339    --  Start of processing for Selected_Range_Checks
6340
6341    begin
6342       if not Expander_Active then
6343          return Ret_Result;
6344       end if;
6345
6346       if Target_Typ = Any_Type
6347         or else Target_Typ = Any_Composite
6348         or else Raises_Constraint_Error (Ck_Node)
6349       then
6350          return Ret_Result;
6351       end if;
6352
6353       if No (Wnode) then
6354          Wnode := Ck_Node;
6355       end if;
6356
6357       T_Typ := Target_Typ;
6358
6359       if No (Source_Typ) then
6360          S_Typ := Etype (Ck_Node);
6361       else
6362          S_Typ := Source_Typ;
6363       end if;
6364
6365       if S_Typ = Any_Type or else S_Typ = Any_Composite then
6366          return Ret_Result;
6367       end if;
6368
6369       --  The order of evaluating T_Typ before S_Typ seems to be critical
6370       --  because S_Typ can be derived from Etype (Ck_Node), if it's not passed
6371       --  in, and since Node can be an N_Range node, it might be invalid.
6372       --  Should there be an assert check somewhere for taking the Etype of
6373       --  an N_Range node ???
6374
6375       if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6376          S_Typ := Designated_Type (S_Typ);
6377          T_Typ := Designated_Type (T_Typ);
6378          Do_Access := True;
6379
6380          --  A simple optimization for the null case
6381
6382          if Known_Null (Ck_Node) then
6383             return Ret_Result;
6384          end if;
6385       end if;
6386
6387       --  For an N_Range Node, check for a null range and then if not
6388       --  null generate a range check action.
6389
6390       if Nkind (Ck_Node) = N_Range then
6391
6392          --  There's no point in checking a range against itself
6393
6394          if Ck_Node = Scalar_Range (T_Typ) then
6395             return Ret_Result;
6396          end if;
6397
6398          declare
6399             T_LB       : constant Node_Id := Type_Low_Bound  (T_Typ);
6400             T_HB       : constant Node_Id := Type_High_Bound (T_Typ);
6401             LB         : constant Node_Id := Low_Bound (Ck_Node);
6402             HB         : constant Node_Id := High_Bound (Ck_Node);
6403             Null_Range : Boolean;
6404
6405             Out_Of_Range_L : Boolean;
6406             Out_Of_Range_H : Boolean;
6407
6408          begin
6409             --  Check for case where everything is static and we can
6410             --  do the check at compile time. This is skipped if we
6411             --  have an access type, since the access value may be null.
6412
6413             --  ??? This code can be improved since you only need to know
6414             --  that the two respective bounds (LB & T_LB or HB & T_HB)
6415             --  are known at compile time to emit pertinent messages.
6416
6417             if Compile_Time_Known_Value (LB)
6418               and then Compile_Time_Known_Value (HB)
6419               and then Compile_Time_Known_Value (T_LB)
6420               and then Compile_Time_Known_Value (T_HB)
6421               and then not Do_Access
6422             then
6423                --  Floating-point case
6424
6425                if Is_Floating_Point_Type (S_Typ) then
6426                   Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
6427                   Out_Of_Range_L :=
6428                     (Expr_Value_R (LB) < Expr_Value_R (T_LB))
6429                        or else
6430                     (Expr_Value_R (LB) > Expr_Value_R (T_HB));
6431
6432                   Out_Of_Range_H :=
6433                     (Expr_Value_R (HB) > Expr_Value_R (T_HB))
6434                        or else
6435                     (Expr_Value_R (HB) < Expr_Value_R (T_LB));
6436
6437                --  Fixed or discrete type case
6438
6439                else
6440                   Null_Range := Expr_Value (HB) < Expr_Value (LB);
6441                   Out_Of_Range_L :=
6442                     (Expr_Value (LB) < Expr_Value (T_LB))
6443                     or else
6444                     (Expr_Value (LB) > Expr_Value (T_HB));
6445
6446                   Out_Of_Range_H :=
6447                     (Expr_Value (HB) > Expr_Value (T_HB))
6448                     or else
6449                     (Expr_Value (HB) < Expr_Value (T_LB));
6450                end if;
6451
6452                if not Null_Range then
6453                   if Out_Of_Range_L then
6454                      if No (Warn_Node) then
6455                         Add_Check
6456                           (Compile_Time_Constraint_Error
6457                              (Low_Bound (Ck_Node),
6458                               "static value out of range of}?", T_Typ));
6459
6460                      else
6461                         Add_Check
6462                           (Compile_Time_Constraint_Error
6463                             (Wnode,
6464                              "static range out of bounds of}?", T_Typ));
6465                      end if;
6466                   end if;
6467
6468                   if Out_Of_Range_H then
6469                      if No (Warn_Node) then
6470                         Add_Check
6471                           (Compile_Time_Constraint_Error
6472                              (High_Bound (Ck_Node),
6473                               "static value out of range of}?", T_Typ));
6474
6475                      else
6476                         Add_Check
6477                           (Compile_Time_Constraint_Error
6478                              (Wnode,
6479                               "static range out of bounds of}?", T_Typ));
6480                      end if;
6481                   end if;
6482
6483                end if;
6484
6485             else
6486                declare
6487                   LB : Node_Id := Low_Bound (Ck_Node);
6488                   HB : Node_Id := High_Bound (Ck_Node);
6489
6490                begin
6491                   --  If either bound is a discriminant and we are within the
6492                   --  record declaration, it is a use of the discriminant in a
6493                   --  constraint of a component, and nothing can be checked
6494                   --  here. The check will be emitted within the init proc.
6495                   --  Before then, the discriminal has no real meaning.
6496                   --  Similarly, if the entity is a discriminal, there is no
6497                   --  check to perform yet.
6498
6499                   --  The same holds within a discriminated synchronized type,
6500                   --  where the discriminant may constrain a component or an
6501                   --  entry family.
6502
6503                   if Nkind (LB) = N_Identifier
6504                     and then Denotes_Discriminant (LB, True)
6505                   then
6506                      if Current_Scope = Scope (Entity (LB))
6507                        or else Is_Concurrent_Type (Current_Scope)
6508                        or else Ekind (Entity (LB)) /= E_Discriminant
6509                      then
6510                         return Ret_Result;
6511                      else
6512                         LB :=
6513                           New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6514                      end if;
6515                   end if;
6516
6517                   if Nkind (HB) = N_Identifier
6518                     and then Denotes_Discriminant (HB, True)
6519                   then
6520                      if Current_Scope = Scope (Entity (HB))
6521                        or else Is_Concurrent_Type (Current_Scope)
6522                        or else Ekind (Entity (HB)) /= E_Discriminant
6523                      then
6524                         return Ret_Result;
6525                      else
6526                         HB :=
6527                           New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6528                      end if;
6529                   end if;
6530
6531                   Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
6532                   Set_Paren_Count (Cond, 1);
6533
6534                   Cond :=
6535                     Make_And_Then (Loc,
6536                       Left_Opnd =>
6537                         Make_Op_Ge (Loc,
6538                           Left_Opnd  => Duplicate_Subexpr_No_Checks (HB),
6539                           Right_Opnd => Duplicate_Subexpr_No_Checks (LB)),
6540                       Right_Opnd => Cond);
6541                end;
6542             end if;
6543          end;
6544
6545       elsif Is_Scalar_Type (S_Typ) then
6546
6547          --  This somewhat duplicates what Apply_Scalar_Range_Check does,
6548          --  except the above simply sets a flag in the node and lets
6549          --  gigi generate the check base on the Etype of the expression.
6550          --  Sometimes, however we want to do a dynamic check against an
6551          --  arbitrary target type, so we do that here.
6552
6553          if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
6554             Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6555
6556          --  For literals, we can tell if the constraint error will be
6557          --  raised at compile time, so we never need a dynamic check, but
6558          --  if the exception will be raised, then post the usual warning,
6559          --  and replace the literal with a raise constraint error
6560          --  expression. As usual, skip this for access types
6561
6562          elsif Compile_Time_Known_Value (Ck_Node)
6563            and then not Do_Access
6564          then
6565             declare
6566                LB : constant Node_Id := Type_Low_Bound (T_Typ);
6567                UB : constant Node_Id := Type_High_Bound (T_Typ);
6568
6569                Out_Of_Range  : Boolean;
6570                Static_Bounds : constant Boolean :=
6571                                  Compile_Time_Known_Value (LB)
6572                                    and Compile_Time_Known_Value (UB);
6573
6574             begin
6575                --  Following range tests should use Sem_Eval routine ???
6576
6577                if Static_Bounds then
6578                   if Is_Floating_Point_Type (S_Typ) then
6579                      Out_Of_Range :=
6580                        (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
6581                          or else
6582                        (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
6583
6584                   else -- fixed or discrete type
6585                      Out_Of_Range :=
6586                        Expr_Value (Ck_Node) < Expr_Value (LB)
6587                          or else
6588                        Expr_Value (Ck_Node) > Expr_Value (UB);
6589                   end if;
6590
6591                   --  Bounds of the type are static and the literal is
6592                   --  out of range so make a warning message.
6593
6594                   if Out_Of_Range then
6595                      if No (Warn_Node) then
6596                         Add_Check
6597                           (Compile_Time_Constraint_Error
6598                              (Ck_Node,
6599                               "static value out of range of}?", T_Typ));
6600
6601                      else
6602                         Add_Check
6603                           (Compile_Time_Constraint_Error
6604                              (Wnode,
6605                               "static value out of range of}?", T_Typ));
6606                      end if;
6607                   end if;
6608
6609                else
6610                   Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6611                end if;
6612             end;
6613
6614          --  Here for the case of a non-static expression, we need a runtime
6615          --  check unless the source type range is guaranteed to be in the
6616          --  range of the target type.
6617
6618          else
6619             if not In_Subrange_Of (S_Typ, T_Typ) then
6620                Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6621             end if;
6622          end if;
6623       end if;
6624
6625       if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6626          if Is_Constrained (T_Typ) then
6627
6628             Expr_Actual := Get_Referenced_Object (Ck_Node);
6629             Exptyp      := Get_Actual_Subtype (Expr_Actual);
6630
6631             if Is_Access_Type (Exptyp) then
6632                Exptyp := Designated_Type (Exptyp);
6633             end if;
6634
6635             --  String_Literal case. This needs to be handled specially be-
6636             --  cause no index types are available for string literals. The
6637             --  condition is simply:
6638
6639             --    T_Typ'Length = string-literal-length
6640
6641             if Nkind (Expr_Actual) = N_String_Literal then
6642                null;
6643
6644             --  General array case. Here we have a usable actual subtype for
6645             --  the expression, and the condition is built from the two types
6646
6647             --     T_Typ'First     < Exptyp'First     or else
6648             --     T_Typ'Last      > Exptyp'Last      or else
6649             --     T_Typ'First(1)  < Exptyp'First(1)  or else
6650             --     T_Typ'Last(1)   > Exptyp'Last(1)   or else
6651             --     ...
6652
6653             elsif Is_Constrained (Exptyp) then
6654                declare
6655                   Ndims : constant Nat := Number_Dimensions (T_Typ);
6656
6657                   L_Index : Node_Id;
6658                   R_Index : Node_Id;
6659                   L_Low   : Node_Id;
6660                   L_High  : Node_Id;
6661                   R_Low   : Node_Id;
6662                   R_High  : Node_Id;
6663
6664                begin
6665                   L_Index := First_Index (T_Typ);
6666                   R_Index := First_Index (Exptyp);
6667
6668                   for Indx in 1 .. Ndims loop
6669                      if not (Nkind (L_Index) = N_Raise_Constraint_Error
6670                                or else
6671                              Nkind (R_Index) = N_Raise_Constraint_Error)
6672                      then
6673                         Get_Index_Bounds (L_Index, L_Low, L_High);
6674                         Get_Index_Bounds (R_Index, R_Low, R_High);
6675
6676                         --  Deal with compile time length check. Note that we
6677                         --  skip this in the access case, because the access
6678                         --  value may be null, so we cannot know statically.
6679
6680                         if not
6681                           Subtypes_Statically_Match
6682                             (Etype (L_Index), Etype (R_Index))
6683                         then
6684                            --  If the target type is constrained then we
6685                            --  have to check for exact equality of bounds
6686                            --  (required for qualified expressions).
6687
6688                            if Is_Constrained (T_Typ) then
6689                               Evolve_Or_Else
6690                                 (Cond,
6691                                  Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
6692
6693                            else
6694                               Evolve_Or_Else
6695                                 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
6696                            end if;
6697                         end if;
6698
6699                         Next (L_Index);
6700                         Next (R_Index);
6701
6702                      end if;
6703                   end loop;
6704                end;
6705
6706             --  Handle cases where we do not get a usable actual subtype that
6707             --  is constrained. This happens for example in the function call
6708             --  and explicit dereference cases. In these cases, we have to get
6709             --  the length or range from the expression itself, making sure we
6710             --  do not evaluate it more than once.
6711
6712             --  Here Ck_Node is the original expression, or more properly the
6713             --  result of applying Duplicate_Expr to the original tree,
6714             --  forcing the result to be a name.
6715
6716             else
6717                declare
6718                   Ndims : constant Nat := Number_Dimensions (T_Typ);
6719
6720                begin
6721                   --  Build the condition for the explicit dereference case
6722
6723                   for Indx in 1 .. Ndims loop
6724                      Evolve_Or_Else
6725                        (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
6726                   end loop;
6727                end;
6728
6729             end if;
6730
6731          else
6732             --  For a conversion to an unconstrained array type, generate an
6733             --  Action to check that the bounds of the source value are within
6734             --  the constraints imposed by the target type (RM 4.6(38)). No
6735             --  check is needed for a conversion to an access to unconstrained
6736             --  array type, as 4.6(24.15/2) requires the designated subtypes
6737             --  of the two access types to statically match.
6738
6739             if Nkind (Parent (Ck_Node)) = N_Type_Conversion
6740               and then not Do_Access
6741             then
6742                declare
6743                   Opnd_Index : Node_Id;
6744                   Targ_Index : Node_Id;
6745                   Opnd_Range : Node_Id;
6746
6747                begin
6748                   Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
6749                   Targ_Index := First_Index (T_Typ);
6750
6751                   while Present (Opnd_Index) loop
6752
6753                      --  If the index is a range, use its bounds. If it is an
6754                      --  entity (as will be the case if it is a named subtype
6755                      --  or an itype created for a slice) retrieve its range.
6756
6757                      if Is_Entity_Name (Opnd_Index)
6758                        and then Is_Type (Entity (Opnd_Index))
6759                      then
6760                         Opnd_Range := Scalar_Range (Entity (Opnd_Index));
6761                      else
6762                         Opnd_Range := Opnd_Index;
6763                      end if;
6764
6765                      if Nkind (Opnd_Range) = N_Range then
6766                         if Is_In_Range
6767                              (Low_Bound (Opnd_Range), Etype (Targ_Index))
6768                           and then
6769                             Is_In_Range
6770                              (High_Bound (Opnd_Range), Etype (Targ_Index))
6771                         then
6772                            null;
6773
6774                         --  If null range, no check needed
6775
6776                         elsif
6777                           Compile_Time_Known_Value (High_Bound (Opnd_Range))
6778                             and then
6779                           Compile_Time_Known_Value (Low_Bound (Opnd_Range))
6780                             and then
6781                               Expr_Value (High_Bound (Opnd_Range)) <
6782                                   Expr_Value (Low_Bound (Opnd_Range))
6783                         then
6784                            null;
6785
6786                         elsif Is_Out_Of_Range
6787                                 (Low_Bound (Opnd_Range), Etype (Targ_Index))
6788                           or else
6789                               Is_Out_Of_Range
6790                                 (High_Bound (Opnd_Range), Etype (Targ_Index))
6791                         then
6792                            Add_Check
6793                              (Compile_Time_Constraint_Error
6794                                (Wnode, "value out of range of}?", T_Typ));
6795
6796                         else
6797                            Evolve_Or_Else
6798                              (Cond,
6799                               Discrete_Range_Cond
6800                                 (Opnd_Range, Etype (Targ_Index)));
6801                         end if;
6802                      end if;
6803
6804                      Next_Index (Opnd_Index);
6805                      Next_Index (Targ_Index);
6806                   end loop;
6807                end;
6808             end if;
6809          end if;
6810       end if;
6811
6812       --  Construct the test and insert into the tree
6813
6814       if Present (Cond) then
6815          if Do_Access then
6816             Cond := Guard_Access (Cond, Loc, Ck_Node);
6817          end if;
6818
6819          Add_Check
6820            (Make_Raise_Constraint_Error (Loc,
6821               Condition => Cond,
6822               Reason    => CE_Range_Check_Failed));
6823       end if;
6824
6825       return Ret_Result;
6826    end Selected_Range_Checks;
6827
6828    -------------------------------
6829    -- Storage_Checks_Suppressed --
6830    -------------------------------
6831
6832    function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
6833    begin
6834       if Present (E) and then Checks_May_Be_Suppressed (E) then
6835          return Is_Check_Suppressed (E, Storage_Check);
6836       else
6837          return Scope_Suppress (Storage_Check);
6838       end if;
6839    end Storage_Checks_Suppressed;
6840
6841    ---------------------------
6842    -- Tag_Checks_Suppressed --
6843    ---------------------------
6844
6845    function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
6846    begin
6847       if Present (E) then
6848          if Kill_Tag_Checks (E) then
6849             return True;
6850          elsif Checks_May_Be_Suppressed (E) then
6851             return Is_Check_Suppressed (E, Tag_Check);
6852          end if;
6853       end if;
6854
6855       return Scope_Suppress (Tag_Check);
6856    end Tag_Checks_Suppressed;
6857
6858    --------------------------
6859    -- Validity_Check_Range --
6860    --------------------------
6861
6862    procedure Validity_Check_Range (N : Node_Id) is
6863    begin
6864       if Validity_Checks_On and Validity_Check_Operands then
6865          if Nkind (N) = N_Range then
6866             Ensure_Valid (Low_Bound (N));
6867             Ensure_Valid (High_Bound (N));
6868          end if;
6869       end if;
6870    end Validity_Check_Range;
6871
6872    --------------------------------
6873    -- Validity_Checks_Suppressed --
6874    --------------------------------
6875
6876    function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
6877    begin
6878       if Present (E) and then Checks_May_Be_Suppressed (E) then
6879          return Is_Check_Suppressed (E, Validity_Check);
6880       else
6881          return Scope_Suppress (Validity_Check);
6882       end if;
6883    end Validity_Checks_Suppressed;
6884
6885 end Checks;