OSDN Git Service

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