1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                               C H E C K S                                --
6--                                                                          --
7--                                 S p e c                                  --
8--                                                                          --
9--          Copyright (C) 1992-2012, 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--  Package containing routines used to deal with runtime checks. These
27--  routines are used both by the semantics and by the expander. In some
28--  cases, checks are enabled simply by setting flags for gigi, and in
29--  other cases the code for the check is expanded.
30
31--  The approach used for range and length checks, in regards to suppressed
32--  checks, is to attempt to detect at compilation time that a constraint
33--  error will occur. If this is detected a warning or error is issued and the
34--  offending expression or statement replaced with a constraint error node.
35--  This always occurs whether checks are suppressed or not. Dynamic range
36--  checks are, of course, not inserted if checks are suppressed.
37
38with Namet;  use Namet;
39with Table;
40with Types;  use Types;
41with Uintp;  use Uintp;
42
43package Checks is
44
45   procedure Initialize;
46   --  Called for each new main source program, to initialize internal
47   --  variables used in the package body of the Checks unit.
48
49   function Access_Checks_Suppressed          (E : Entity_Id) return Boolean;
50   function Accessibility_Checks_Suppressed   (E : Entity_Id) return Boolean;
51   function Alignment_Checks_Suppressed       (E : Entity_Id) return Boolean;
52   function Atomic_Synchronization_Disabled   (E : Entity_Id) return Boolean;
53   function Discriminant_Checks_Suppressed    (E : Entity_Id) return Boolean;
54   function Division_Checks_Suppressed        (E : Entity_Id) return Boolean;
55   function Elaboration_Checks_Suppressed     (E : Entity_Id) return Boolean;
56   function Index_Checks_Suppressed           (E : Entity_Id) return Boolean;
57   function Length_Checks_Suppressed          (E : Entity_Id) return Boolean;
58   function Overflow_Checks_Suppressed        (E : Entity_Id) return Boolean;
59   function Range_Checks_Suppressed           (E : Entity_Id) return Boolean;
60   function Storage_Checks_Suppressed         (E : Entity_Id) return Boolean;
61   function Tag_Checks_Suppressed             (E : Entity_Id) return Boolean;
62   function Validity_Checks_Suppressed        (E : Entity_Id) return Boolean;
63   --  These functions check to see if the named check is suppressed, either
64   --  by an active scope suppress setting, or because the check has been
65   --  specifically suppressed for the given entity. If no entity is relevant
66   --  for the current check, then Empty is used as an argument. Note: the
67   --  reason we insist on specifying Empty is to force the caller to think
68   --  about whether there is any relevant entity that should be checked.
69
70   function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean;
71   --  This function is called if Checks_May_Be_Suppressed (E) is True to
72   --  determine whether check C is suppressed either on the entity E or
73   --  as the result of a scope suppress pragma. If Checks_May_Be_Suppressed
74   --  is False, then the status of the check can be determined simply by
75   --  examining Scope_Suppress, so this routine is not called in that case.
76
77   function Overflow_Check_Mode return Overflow_Mode_Type;
78   --  Returns current overflow checking mode, taking into account whether
79   --  we are inside an assertion expression.
80
81   -------------------------------------------
82   -- Procedures to Activate Checking Flags --
83   -------------------------------------------
84
85   procedure Activate_Division_Check (N : Node_Id);
86   pragma Inline (Activate_Division_Check);
87   --  Sets Do_Division_Check flag in node N, and handles possible local raise.
88   --  Always call this routine rather than calling Set_Do_Division_Check to
89   --  set an explicit value of True, to ensure handling the local raise case.
90
91   procedure Activate_Overflow_Check (N : Node_Id);
92   pragma Inline (Activate_Overflow_Check);
93   --  Sets Do_Overflow_Check flag in node N, and handles possible local raise.
94   --  Always call this routine rather than calling Set_Do_Overflow_Check to
95   --  set an explicit value of True, to ensure handling the local raise case.
96   --  Note that this call has no effect for MOD, REM, and unary "+" for which
97   --  overflow is never possible in any case.
98
99   procedure Activate_Range_Check (N : Node_Id);
100   pragma Inline (Activate_Range_Check);
101   --  Sets Do_Range_Check flag in node N, and handles possible local raise
102   --  Always call this routine rather than calling Set_Do_Range_Check to
103   --  set an explicit value of True, to ensure handling the local raise case.
104
105   --------------------------------
106   -- Procedures to Apply Checks --
107   --------------------------------
108
109   --  General note on following checks. These checks are always active if
110   --  Expander_Active and not Inside_A_Generic. They are inactive and have
111   --  no effect Inside_A_Generic. In the case where not Expander_Active
112   --  and not Inside_A_Generic, most of them are inactive, but some of them
113   --  operate anyway since they may generate useful compile time warnings.
114
115   procedure Apply_Access_Check (N : Node_Id);
116   --  Determines whether an expression node requires a runtime access
117   --  check and if so inserts the appropriate run-time check.
118
119   procedure Apply_Accessibility_Check
120     (N           : Node_Id;
121      Typ         : Entity_Id;
122      Insert_Node : Node_Id);
123   --  Given a name N denoting an access parameter, emits a run-time
124   --  accessibility check (if necessary), checking that the level of
125   --  the object denoted by the access parameter is not deeper than the
126   --  level of the type Typ. Program_Error is raised if the check fails.
127   --  Insert_Node indicates the node where the check should be inserted.
128
129   procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id);
130   --  E is the entity for an object which has an address clause. If checks
131   --  are enabled, then this procedure generates a check that the specified
132   --  address has an alignment consistent with the alignment of the object,
133   --  raising PE if this is not the case. The resulting check (if one is
134   --  generated) is prepended to the Actions list of N_Freeze_Entity node N.
135   --  Note that the check references E'Alignment, so it cannot be emitted
136   --  before N (its freeze node), otherwise this would cause an illegal
137   --  access before elaboration error in GIGI. For the case of a clear overlay
138   --  situation, we also check that the size of the overlaying object is not
139   --  larger than the overlaid object.
140
141   procedure Apply_Arithmetic_Overflow_Check (N : Node_Id);
142   --  Handle overflow checking for an arithmetic operator. Also handles the
143   --  cases of ELIMINATED and MINIMIZED overflow checking mode. If the mode
144   --  is one of the latter two, then this routine can also be called with
145   --  an if or case expression node to make sure that we properly handle
146   --  overflow checking for dependent expressions. This routine handles
147   --  front end vs back end overflow checks (in the front end case it expands
148   --  the necessary check). Note that divide is handled separately using
149   --  Apply_Divide_Checks. Node N may or may not have Do_Overflow_Check.
150   --  In STRICT mode, there is nothing to do if this flag is off, but in
151   --  MINIMIZED/ELIMINATED mode we still have to deal with possible use
152   --  of doing operations in Long_Long_Integer or Bignum mode.
153
154   procedure Apply_Constraint_Check
155     (N          : Node_Id;
156      Typ        : Entity_Id;
157      No_Sliding : Boolean := False);
158   --  Top-level procedure, calls all the others depending on the class of
159   --  Typ. Checks that expression N satisfies the constraint of type Typ.
160   --  No_Sliding is only relevant for constrained array types, if set to
161   --  True, it checks that indexes are in range.
162
163   procedure Apply_Discriminant_Check
164     (N   : Node_Id;
165      Typ : Entity_Id;
166      Lhs : Node_Id := Empty);
167   --  Given an expression N of a discriminated type, or of an access type
168   --  whose designated type is a discriminanted type, generates a check to
169   --  ensure that the expression can be converted to the subtype given as
170   --  the second parameter. Lhs is empty except in the case of assignments,
171   --  where the target object may be needed to determine the subtype to
172   --  check against (such as the cases of unconstrained formal parameters
173   --  and unconstrained aliased objects). For the case of unconstrained
174   --  formals, the check is performed only if the corresponding actual is
175   --  constrained, i.e., whether Lhs'Constrained is True.
176
177   procedure Apply_Divide_Checks (N : Node_Id);
178   --  The node kind is N_Op_Divide, N_Op_Mod, or N_Op_Rem if either of the
179   --  flags Do_Division_Check or Do_Overflow_Check is set, then this routine
180   --  ensures that the appropriate checks are made. Note that overflow can
181   --  occur in the signed case for the case of the largest negative number
182   --  divided by minus one.
183
184   procedure Apply_Parameter_Aliasing_Checks
185     (Call : Node_Id;
186      Subp : Entity_Id);
187   --  Given a subprogram call Call, add a check to verify that none of the
188   --  actuals overlap. Subp denotes the subprogram being called.
189
190   procedure Apply_Parameter_Validity_Checks (Subp : Entity_Id);
191   --  Given a subprogram Subp, add both a pre and post condition pragmas that
192   --  verify the proper initialization of scalars in parameters and function
193   --  results.
194
195   procedure Apply_Predicate_Check (N : Node_Id; Typ : Entity_Id);
196   --  N is an expression to which a predicate check may need to be applied
197   --  for Typ, if Typ has a predicate function. The check is applied only
198   --  if the type of N does not match Typ.
199
200   procedure Apply_Type_Conversion_Checks (N : Node_Id);
201   --  N is an N_Type_Conversion node. A type conversion actually involves
202   --  two sorts of checks. The first check is the checks that ensures that
203   --  the operand in the type conversion fits onto the base type of the
204   --  subtype it is being converted to (see RM 4.6 (28)-(50)). The second
205   --  check is there to ensure that once the operand has been converted to
206   --  a value of the target type, this converted value meets the
207   --  constraints imposed by the target subtype (see RM 4.6 (51)).
208
209   procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id);
210   --  The argument N is an attribute reference node intended for processing
211   --  by gigi. The attribute is one that returns a universal integer, but
212   --  the attribute reference node is currently typed with the expected
213   --  result type. This routine deals with range and overflow checks needed
214   --  to make sure that the universal result is in range.
215
216   function Build_Discriminant_Checks
217     (N     : Node_Id;
218      T_Typ : Entity_Id)
219      return  Node_Id;
220   --  Subsidiary routine for Apply_Discriminant_Check. Builds the expression
221   --  that compares discriminants of the expression with discriminants of the
222   --  type. Also used directly for membership tests (see Exp_Ch4.Expand_N_In).
223
224   function Convert_From_Bignum (N : Node_Id) return Node_Id;
225   --  Returns result of converting node N from Bignum. The returned value is
226   --  not analyzed, the caller takes responsibility for this. Node N must be
227   --  a subexpression node of type Bignum. The result is Long_Long_Integer.
228
229   function Convert_To_Bignum (N : Node_Id) return Node_Id;
230   --  Returns result of converting node N to Bignum. The returned value is not
231   --  analyzed, the caller takes responsibility for this. Node N must be a
232   --  subexpression node of a signed integer type or Bignum type (if it is
233   --  already a Bignum, the returned value is Relocate_Node (N)).
234
235   procedure Determine_Range
236     (N            : Node_Id;
237      OK           : out Boolean;
238      Lo           : out Uint;
239      Hi           : out Uint;
240      Assume_Valid : Boolean := False);
241   --  N is a node for a subexpression. If N is of a discrete type with no
242   --  error indications, and no other peculiarities (e.g. missing Etype),
243   --  then OK is True on return, and Lo and Hi are set to a conservative
244   --  estimate of the possible range of values of N. Thus if OK is True on
245   --  return, the value of the subexpression N is known to lie in the range
246   --  Lo .. Hi (inclusive). If the expression is not of a discrete type, or
247   --  some kind of error condition is detected, then OK is False on exit, and
248   --  Lo/Hi are set to No_Uint. Thus the significance of OK being False on
249   --  return is that no useful information is available on the range of the
250   --  expression. Assume_Valid determines whether the processing is allowed to
251   --  assume that values are in range of their subtypes. If it is set to True,
252   --  then this assumption is valid, if False, then processing is done using
253   --  base types to allow invalid values.
254
255   procedure Install_Null_Excluding_Check (N : Node_Id);
256   --  Determines whether an access node requires a runtime access check and
257   --  if so inserts the appropriate run-time check.
258
259   function Make_Bignum_Block (Loc : Source_Ptr) return Node_Id;
260   --  This function is used by top level overflow checking routines to do a
261   --  mark/release operation on the secondary stack around bignum operations.
262   --  The block created looks like:
263   --
264   --    declare
265   --       M : Mark_Id := SS_Mark;
266   --    begin
267   --       SS_Release (M);
268   --    end;
269   --
270   --  The idea is that the caller will insert any needed extra declarations
271   --  after the declaration of M, and any needed statements (in particular
272   --  the bignum operations) before the call to SS_Release, and then do an
273   --  Insert_Action of the whole block (it is returned unanalyzed). The Loc
274   --  parameter is used to supply Sloc values for the constructed tree.
275
276   procedure Minimize_Eliminate_Overflows
277     (N         : Node_Id;
278      Lo        : out Uint;
279      Hi        : out Uint;
280      Top_Level : Boolean);
281   --  This is the main routine for handling MINIMIZED and ELIMINATED overflow
282   --  processing. On entry N is a node whose result is a signed integer
283   --  subtype. The Do_Overflow_Check flag may or may not be set on N. If the
284   --  node is an arithmetic operation, then a range analysis is carried out,
285   --  and there are three possibilities:
286   --
287   --    The node is left unchanged (apart from expansion of an exponentiation
288   --    operation). This happens if the routine can determine that the result
289   --    is definitely in range. The Do_Overflow_Check flag is turned off in
290   --    this case.
291   --
292   --    The node is transformed into an arithmetic operation with a result
293   --    type of Long_Long_Integer.
294   --
295   --    The node is transformed into a function call that calls an appropriate
296   --    function in the System.Bignums package to compute a Bignum result.
297   --
298   --  In the first two cases, Lo and Hi are set to the bounds of the possible
299   --  range of results, computed as accurately as possible. In the third case
300   --  Lo and Hi are set to No_Uint (there are some cases where we could get an
301   --  advantage from keeping result ranges for Bignum values, but it could use
302   --  a lot of space and is very unlikely to be valuable).
303   --
304   --  If the node is not an arithmetic operation, then it is unchanged but
305   --  Lo and Hi are still set (to the bounds of the result subtype if nothing
306   --  better can be determined).
307   --
308   --  Note: this function is recursive, if called with an arithmetic operator,
309   --  recursive calls are made to process the operands using this procedure.
310   --  So we end up doing things top down. Nothing happens to an arithmetic
311   --  expression until this procedure is called on the top level node and
312   --  then the recursive calls process all the children. We have to do it
313   --  this way. If we try to do it bottom up in natural expansion order, then
314   --  there are two problems. First, where do we stash the bounds, and more
315   --  importantly, semantic processing will be messed up. Consider A+B+C where
316   --  A,B,C are all of type integer, if we processed A+B before doing semantic
317   --  analysis of the addition of this result to C, that addition could end up
318   --  with a Long_Long_Integer left operand and an Integer right operand, and
319   --  we would get a semantic error.
320   --
321   --  The routine is called in three situations if we are operating in either
322   --  MINIMIZED or ELIMINATED modes.
323   --
324   --    Overflow processing applied to the top node of an expression tree when
325   --    that node is an arithmetic operator. In this case the result is
326   --    converted to the appropriate result type (there is special processing
327   --    when the parent is a conversion, see body for details).
328   --
329   --    Overflow processing applied to the operands of a comparison operation.
330   --    In this case, the comparison is done on the result Long_Long_Integer
331   --    or Bignum values, without raising any exceptions.
332   --
333   --    Overflow processing applied to the left operand of a membership test.
334   --    In this case no exception is raised if a Long_Long_Integer or Bignum
335   --    result is outside the range of the type of that left operand (it is
336   --    just that the result of IN is false in that case).
337   --
338   --  Note that if Bignum values appear, the caller must take care of doing
339   --  the appropriate mark/release operations on the secondary stack.
340   --
341   --  Top_Level is used to avoid inefficient unnecessary transitions into the
342   --  Bignum domain. If Top_Level is True, it means that the caller will have
343   --  to convert any Bignum value back to Long_Long_Integer, possibly checking
344   --  that the value is in range. This is the normal case for a top level
345   --  operator in a subexpression. There is no point in going into Bignum mode
346   --  to avoid an overflow just so we can check for overflow the next moment.
347   --  For calls from comparisons and membership tests, and for all recursive
348   --  calls, we do want to transition into the Bignum domain if necessary.
349   --  Note that this setting is only relevant in ELIMINATED mode.
350
351   -------------------------------------------------------
352   -- Control and Optimization of Range/Overflow Checks --
353   -------------------------------------------------------
354
355   --  Range checks are controlled by the Do_Range_Check flag. The front end
356   --  is responsible for setting this flag in relevant nodes. Originally
357   --  the back end generated all corresponding range checks. But later on
358   --  we decided to generate many range checks in the front end. We are now
359   --  in the transitional phase where some of these checks are still done
360   --  by the back end, but many are done by the front end. It is possible
361   --  that in the future we might move all the checks to the front end. The
362   --  main remaining back end checks are for subscript checking.
363
364   --  Overflow checks are similarly controlled by the Do_Overflow_Check flag.
365   --  The difference here is that if back end overflow checks are inactive
366   --  (Backend_Overflow_Checks_On_Target set False), then the actual overflow
367   --  checks are generated by the front end, but if back end overflow checks
368   --  are active (Backend_Overflow_Checks_On_Target set True), then the back
369   --  end does generate the checks.
370
371   --  The following two routines are used to set these flags, they allow
372   --  for the possibility of eliminating checks. Checks can be eliminated
373   --  if an identical check has already been performed.
374
375   procedure Enable_Overflow_Check (N : Node_Id);
376   --  First this routine determines if an overflow check is needed by doing
377   --  an appropriate range check. If a check is not needed, then the call
378   --  has no effect. If a check is needed then this routine sets the flag
379   --  Do_Overflow_Check in node N to True, unless it can be determined that
380   --  the check is not needed. The only condition under which this is the
381   --  case is if there was an identical check earlier on.
382
383   procedure Enable_Range_Check (N : Node_Id);
384   --  Set Do_Range_Check flag in node N True, unless it can be determined
385   --  that the check is not needed. The only condition under which this is
386   --  the case is if there was an identical check earlier on. This routine
387   --  is not responsible for doing range analysis to determine whether or
388   --  not such a check is needed -- the caller is expected to do this. The
389   --  one other case in which the request to set the flag is ignored is
390   --  when Kill_Range_Check is set in an N_Unchecked_Conversion node.
391
392   --  The following routines are used to keep track of processing sequences
393   --  of statements (e.g. the THEN statements of an IF statement). A check
394   --  that appears within such a sequence can eliminate an identical check
395   --  within this sequence of statements. However, after the end of the
396   --  sequence of statements, such a check is no longer of interest, since
397   --  it may not have been executed.
398
399   procedure Conditional_Statements_Begin;
400   --  This call marks the start of processing of a sequence of statements.
401   --  Every call to this procedure must be followed by a matching call to
402   --  Conditional_Statements_End.
403
404   procedure Conditional_Statements_End;
405   --  This call removes from consideration all saved checks since the
406   --  corresponding call to Conditional_Statements_Begin. These two
407   --  procedures operate in a stack like manner.
408
409   --  The mechanism for optimizing checks works by remembering checks
410   --  that have already been made, but certain conditions, for example
411   --  an assignment to a variable involved in a check, may mean that the
412   --  remembered check is no longer valid, in the sense that if the same
413   --  expression appears again, another check is required because the
414   --  value may have changed.
415
416   --  The following routines are used to note conditions which may render
417   --  some or all of the stored and remembered checks to be invalidated.
418
419   procedure Kill_Checks (V : Entity_Id);
420   --  This procedure records an assignment or other condition that causes
421   --  the value of the variable to be changed, invalidating any stored
422   --  checks that reference the value. Note that all such checks must
423   --  be discarded, even if they are not in the current statement range.
424
425   procedure Kill_All_Checks;
426   --  This procedure kills all remembered checks
427
428   -----------------------------
429   -- Length and Range Checks --
430   -----------------------------
431
432   --  In the following procedures, there are three arguments which have
433   --  a common meaning as follows:
434
435   --    Expr        The expression to be checked. If a check is required,
436   --                the appropriate flag will be placed on this node. Whether
437   --                this node is further examined depends on the setting of
438   --                the parameter Source_Typ, as described below.
439
440   --    ??? Apply_Length_Check and Apply_Range_Check do not have an Expr
441   --        formal
442
443   --    ??? Apply_Length_Check and Apply_Range_Check have a Ck_Node formal
444   --        which is undocumented, is it the same as Expr?
445
446   --    Target_Typ  The target type on which the check is to be based. For
447   --                example, if we have a scalar range check, then the check
448   --                is that we are in range of this type.
449
450   --    Source_Typ  Normally Empty, but can be set to a type, in which case
451   --                this type is used for the check, see below.
452
453   --  The checks operate in one of two modes:
454
455   --    If Source_Typ is Empty, then the node Expr is examined, at the very
456   --    least to get the source subtype. In addition for some of the checks,
457   --    the actual form of the node may be examined. For example, a node of
458   --    type Integer whose actual form is an Integer conversion from a type
459   --    with range 0 .. 3 can be determined to have a value in range 0 .. 3.
460
461   --    If Source_Typ is given, then nothing can be assumed about the Expr,
462   --    and indeed its contents are not examined. In this case the check is
463   --    based on the assumption that Expr can be an arbitrary value of the
464   --    given Source_Typ.
465
466   --  Currently, the only case in which a Source_Typ is explicitly supplied
467   --  is for the case of Out and In_Out parameters, where, for the conversion
468   --  on return (the Out direction), the types must be reversed. This is
469   --  handled by the caller.
470
471   procedure Apply_Length_Check
472     (Ck_Node    : Node_Id;
473      Target_Typ : Entity_Id;
474      Source_Typ : Entity_Id := Empty);
475   --  This procedure builds a sequence of declarations to do a length check
476   --  that checks if the lengths of the two arrays Target_Typ and source type
477   --  are the same. The resulting actions are inserted at Node using a call
478   --  to Insert_Actions.
479   --
480   --  For access types, the Directly_Designated_Type is retrieved and
481   --  processing continues as enumerated above, with a guard against null
482   --  values.
483   --
484   --  Note: calls to Apply_Length_Check currently never supply an explicit
485   --  Source_Typ parameter, but Apply_Length_Check takes this parameter and
486   --  processes it as described above for consistency with the other routines
487   --  in this section.
488
489   procedure Apply_Range_Check
490     (Ck_Node    : Node_Id;
491      Target_Typ : Entity_Id;
492      Source_Typ : Entity_Id := Empty);
493   --  For a Node of kind N_Range, constructs a range check action that tests
494   --  first that the range is not null and then that the range is contained in
495   --  the Target_Typ range.
496   --
497   --  For scalar types, constructs a range check action that first tests that
498   --  the expression is contained in the Target_Typ range. The difference
499   --  between this and Apply_Scalar_Range_Check is that the latter generates
500   --  the actual checking code in gigi against the Etype of the expression.
501   --
502   --  For constrained array types, construct series of range check actions
503   --  to check that each Expr range is properly contained in the range of
504   --  Target_Typ.
505   --
506   --  For a type conversion to an unconstrained array type, constructs a range
507   --  check action to check that the bounds of the source type are within the
508   --  constraints imposed by the Target_Typ.
509   --
510   --  For access types, the Directly_Designated_Type is retrieved and
511   --  processing continues as enumerated above, with a guard against null
512   --  values.
513   --
514   --  The source type is used by type conversions to unconstrained array
515   --  types to retrieve the corresponding bounds.
516
517   procedure Apply_Static_Length_Check
518     (Expr       : Node_Id;
519      Target_Typ : Entity_Id;
520      Source_Typ : Entity_Id := Empty);
521   --  Tries to determine statically whether the two array types source type
522   --  and Target_Typ have the same length. If it can be determined at compile
523   --  time that they do not, then an N_Raise_Constraint_Error node replaces
524   --  Expr, and a warning message is issued.
525
526   procedure Apply_Scalar_Range_Check
527     (Expr       : Node_Id;
528      Target_Typ : Entity_Id;
529      Source_Typ : Entity_Id := Empty;
530      Fixed_Int  : Boolean   := False);
531   --  For scalar types, determines whether an expression node should be
532   --  flagged as needing a runtime range check. If the node requires such a
533   --  check, the Do_Range_Check flag is turned on. The Fixed_Int flag if set
534   --  causes any fixed-point values to be treated as though they were discrete
535   --  values (i.e. the underlying integer value is used).
536
537   type Check_Result is private;
538   --  Type used to return result of Get_Range_Checks call, for later use in
539   --  call to Insert_Range_Checks procedure.
540
541   function Get_Range_Checks
542     (Ck_Node    : Node_Id;
543      Target_Typ : Entity_Id;
544      Source_Typ : Entity_Id := Empty;
545      Warn_Node  : Node_Id   := Empty) return Check_Result;
546   --  Like Apply_Range_Check, except it does not modify anything. Instead
547   --  it returns an encapsulated result of the check operations for later
548   --  use in a call to Insert_Range_Checks. If Warn_Node is non-empty, its
549   --  Sloc is used, in the static case, for the generated warning or error.
550   --  Additionally, it is used rather than Expr (or Low/High_Bound of Expr)
551   --  in constructing the check.
552
553   procedure Append_Range_Checks
554     (Checks       : Check_Result;
555      Stmts        : List_Id;
556      Suppress_Typ : Entity_Id;
557      Static_Sloc  : Source_Ptr;
558      Flag_Node    : Node_Id);
559   --  Called to append range checks as returned by a call to Get_Range_Checks.
560   --  Stmts is a list to which either the dynamic check is appended or the
561   --  raise Constraint_Error statement is appended (for static checks).
562   --  Static_Sloc is the Sloc at which the raise CE node points, Flag_Node is
563   --  used as the node at which to set the Has_Dynamic_Check flag. Checks_On
564   --  is a boolean value that says if range and index checking is on or not.
565
566   procedure Insert_Range_Checks
567     (Checks       : Check_Result;
568      Node         : Node_Id;
569      Suppress_Typ : Entity_Id;
570      Static_Sloc  : Source_Ptr := No_Location;
571      Flag_Node    : Node_Id    := Empty;
572      Do_Before    : Boolean    := False);
573   --  Called to insert range checks as returned by a call to Get_Range_Checks.
574   --  Node is the node after which either the dynamic check is inserted or
575   --  the raise Constraint_Error statement is inserted (for static checks).
576   --  Suppress_Typ is the type to check to determine if checks are suppressed.
577   --  Static_Sloc, if passed, is the Sloc at which the raise CE node points,
578   --  otherwise Sloc (Node) is used. The Has_Dynamic_Check flag is normally
579   --  set at Node. If Flag_Node is present, then this is used instead as the
580   --  node at which to set the Has_Dynamic_Check flag. Normally the check is
581   --  inserted after, if Do_Before is True, the check is inserted before
582   --  Node.
583
584   -----------------------
585   -- Expander Routines --
586   -----------------------
587
588   --  Some of the earlier processing for checks results in temporarily setting
589   --  the Do_Range_Check flag rather than actually generating checks. Now we
590   --  are moving the generation of such checks into the front end for reasons
591   --  of efficiency and simplicity (there were difficulties in handling this
592   --  in the back end when side effects were present in the expressions being
593   --  checked).
594
595   --  Probably we could eliminate the Do_Range_Check flag entirely and
596   --  generate the checks earlier, but this is a delicate area and it
597   --  seemed safer to implement the following routines, which are called
598   --  late on in the expansion process. They check the Do_Range_Check flag
599   --  and if it is set, generate the actual checks and reset the flag.
600
601   procedure Generate_Range_Check
602     (N           : Node_Id;
603      Target_Type : Entity_Id;
604      Reason      : RT_Exception_Code);
605   --  This procedure is called to actually generate and insert a range check.
606   --  A check is generated to ensure that the value of N lies within the range
607   --  of the target type. Note that the base type of N may be different from
608   --  the base type of the target type. This happens in the conversion case.
609   --  The Reason parameter is the exception code to be used for the exception
610   --  if raised.
611   --
612   --  Note on the relation of this routine to the Do_Range_Check flag. Mostly
613   --  for historical reasons, we often set the Do_Range_Check flag and then
614   --  later we call Generate_Range_Check if this flag is set. Most probably we
615   --  could eliminate this intermediate setting of the flag (historically the
616   --  back end dealt with range checks, using this flag to indicate if a check
617   --  was required, then we moved checks into the front end).
618
619   procedure Generate_Index_Checks (N : Node_Id);
620   --  This procedure is called to generate index checks on the subscripts for
621   --  the indexed component node N. Each subscript expression is examined, and
622   --  if the Do_Range_Check flag is set, an appropriate index check is
623   --  generated and the flag is reset.
624
625   --  Similarly, we set the flag Do_Discriminant_Check in the semantic
626   --  analysis to indicate that a discriminant check is required for selected
627   --  component of a discriminated type. The following routine is called from
628   --  the expander to actually generate the call.
629
630   procedure Generate_Discriminant_Check (N : Node_Id);
631   --  N is a selected component for which a discriminant check is required to
632   --  make sure that the discriminants have appropriate values for the
633   --  selection. This is done by calling the appropriate discriminant checking
634   --  routine for the selector.
635
636   -----------------------
637   -- Validity Checking --
638   -----------------------
639
640   --  In (RM 13.9.1(9-11)) we have the following rules on invalid values
641
642   --    If the representation of a scalar object does not represent value of
643   --    the object's subtype (perhaps because the object was not initialized),
644   --    the object is said to have an invalid representation. It is a bounded
645   --    error to evaluate the value of such an object. If the error is
646   --    detected, either Constraint_Error or Program_Error is raised.
647   --    Otherwise, execution continues using the invalid representation. The
648   --    rules of the language outside this subclause assume that all objects
649   --    have valid representations. The semantics of operations on invalid
650   --    representations are as follows:
651   --
652   --       10  If the representation of the object represents a value of the
653   --           object's type, the value of the type is used.
654   --
655   --       11  If the representation of the object does not represent a value
656   --           of the object's type, the semantics of operations on such
657   --           representations is implementation-defined, but does not by
658   --           itself lead to erroneous or unpredictable execution, or to
659   --           other objects becoming abnormal.
660
661   --  We quote the rules in full here since they are quite delicate. Most
662   --  of the time, we can just compute away with wrong values, and get a
663   --  possibly wrong result, which is well within the range of allowed
664   --  implementation defined behavior. The two tricky cases are subscripted
665   --  array assignments, where we don't want to do wild stores, and case
666   --  statements where we don't want to do wild jumps.
667
668   --  In GNAT, we control validity checking with a switch -gnatV that can take
669   --  three parameters, n/d/f for None/Default/Full. These modes have the
670   --  following meanings:
671
672   --    None (no validity checking)
673
674   --      In this mode, there is no specific checking for invalid values
675   --      and the code generator assumes that all stored values are always
676   --      within the bounds of the object subtype. The consequences are as
677   --      follows:
678
679   --        For case statements, an out of range invalid value will cause
680   --        Constraint_Error to be raised, or an arbitrary one of the case
681   --        alternatives will be executed. Wild jumps cannot result even
682   --        in this mode, since we always do a range check
683
684   --        For subscripted array assignments, wild stores will result in
685   --        the expected manner when addresses are calculated using values
686   --        of subscripts that are out of range.
687
688   --      It could perhaps be argued that this mode is still conformant with
689   --      the letter of the RM, since implementation defined is a rather
690   --      broad category, but certainly it is not in the spirit of the
691   --      RM requirement, since wild stores certainly seem to be a case of
692   --      erroneous behavior.
693
694   --    Default (default standard RM-compatible validity checking)
695
696   --      In this mode, which is the default, minimal validity checking is
697   --      performed to ensure no erroneous behavior as follows:
698
699   --        For case statements, an out of range invalid value will cause
700   --        Constraint_Error to be raised.
701
702   --        For subscripted array assignments, invalid out of range
703   --        subscript values will cause Constraint_Error to be raised.
704
705   --    Full (Full validity checking)
706
707   --      In this mode, the protections guaranteed by the standard mode are
708   --      in place, and the following additional checks are made:
709
710   --        For every assignment, the right side is checked for validity
711
712   --        For every call, IN and IN OUT parameters are checked for validity
713
714   --        For every subscripted array reference, both for stores and loads,
715   --        all subscripts are checked for validity.
716
717   --      These checks are not required by the RM, but will in practice
718   --      improve the detection of uninitialized variables, particularly
719   --      if used in conjunction with pragma Normalize_Scalars.
720
721   --  In the above description, we talk about performing validity checks,
722   --  but we don't actually generate a check in a case where the compiler
723   --  can be sure that the value is valid. Note that this assurance must
724   --  be achieved without assuming that any uninitialized value lies within
725   --  the range of its type. The following are cases in which values are
726   --  known to be valid. The flag Is_Known_Valid is used to keep track of
727   --  some of these cases.
728
729   --    If all possible stored values are valid, then any uninitialized
730   --    value must be valid.
731
732   --    Literals, including enumeration literals, are clearly always valid
733
734   --    Constants are always assumed valid, with a validity check being
735   --    performed on the initializing value where necessary to ensure that
736   --    this is the case.
737
738   --    For variables, the status is set to known valid if there is an
739   --    initializing expression. Again a check is made on the initializing
740   --    value if necessary to ensure that this assumption is valid. The
741   --    status can change as a result of local assignments to a variable.
742   --    If a known valid value is unconditionally assigned, then we mark
743   --    the left side as known valid. If a value is assigned that is not
744   --    known to be valid, then we mark the left side as invalid. This
745   --    kind of processing does NOT apply to non-local variables since we
746   --    are not following the flow graph (more properly the flow of actual
747   --    processing only corresponds to the flow graph for local assignments).
748   --    For non-local variables, we preserve the current setting, i.e. a
749   --    validity check is performed when assigning to a knonwn valid global.
750
751   --  Note: no validity checking is required if range checks are suppressed
752   --  regardless of the setting of the validity checking mode.
753
754   --  The following procedures are used in handling validity checking
755
756   procedure Apply_Subscript_Validity_Checks (Expr : Node_Id);
757   --  Expr is the node for an indexed component. If validity checking and
758   --  range checking are enabled, all subscripts for this indexed component
759   --  are checked for validity.
760
761   procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id);
762   --  Expr is a lvalue, i.e. an expression representing the target of an
763   --  assignment. This procedure checks for this expression involving an
764   --  assignment to an array value. We have to be sure that all the subscripts
765   --  in such a case are valid, since according to the rules in (RM
766   --  13.9.1(9-11)) such assignments are not permitted to result in erroneous
767   --  behavior in the case of invalid subscript values.
768
769   procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False);
770   --  Ensure that Expr represents a valid value of its type. If this type
771   --  is not a scalar type, then the call has no effect, since validity
772   --  is only an issue for scalar types. The effect of this call is to
773   --  check if the value is known valid, if so, nothing needs to be done.
774   --  If this is not known, then either Expr is set to be range checked,
775   --  or specific checking code is inserted so that an exception is raised
776   --  if the value is not valid.
777   --
778   --  The optional argument Holes_OK indicates whether it is necessary to
779   --  worry about enumeration types with non-standard representations leading
780   --  to "holes" in the range of possible representations. If Holes_OK is
781   --  True, then such values are assumed valid (this is used when the caller
782   --  will make a separate check for this case anyway). If Holes_OK is False,
783   --  then this case is checked, and code is inserted to ensure that Expr is
784   --  valid, raising Constraint_Error if the value is not valid.
785
786   function Expr_Known_Valid (Expr : Node_Id) return Boolean;
787   --  This function tests it the value of Expr is known to be valid in the
788   --  sense of RM 13.9.1(9-11). In the case of GNAT, it is only discrete types
789   --  which are a concern, since for non-discrete types we simply continue
790   --  computation with invalid values, which does not lead to erroneous
791   --  behavior. Thus Expr_Known_Valid always returns True if the type of Expr
792   --  is non-discrete. For discrete types the value returned is True only if
793   --  it can be determined that the value is Valid. Otherwise False is
794   --  returned.
795
796   procedure Insert_Valid_Check (Expr : Node_Id);
797   --  Inserts code that will check for the value of Expr being valid, in
798   --  the sense of the 'Valid attribute returning True. Constraint_Error
799   --  will be raised if the value is not valid.
800
801   procedure Null_Exclusion_Static_Checks (N : Node_Id);
802   --  Ada 2005 (AI-231): Check bad usages of the null-exclusion issue
803
804   procedure Remove_Checks (Expr : Node_Id);
805   --  Remove all checks from Expr except those that are only executed
806   --  conditionally (on the right side of And Then/Or Else. This call
807   --  removes only embedded checks (Do_Range_Check, Do_Overflow_Check).
808
809   procedure Validity_Check_Range (N : Node_Id);
810   --  If N is an N_Range node, then Ensure_Valid is called on its bounds,
811   --  if validity checking of operands is enabled.
812
813   -----------------------------
814   -- Handling of Check Names --
815   -----------------------------
816
817   --  The following table contains Name_Id's for recognized checks. The first
818   --  entries (corresponding to the values of the subtype Predefined_Check_Id)
819   --  contain the Name_Id values for the checks that are predefined, including
820   --  All_Checks (see Types). Remaining entries are those that are introduced
821   --  by pragma Check_Names.
822
823   package Check_Names is new Table.Table (
824     Table_Component_Type => Name_Id,
825     Table_Index_Type     => Check_Id,
826     Table_Low_Bound      => 1,
827     Table_Initial        => 30,
828     Table_Increment      => 200,
829     Table_Name           => "Name_Check_Names");
830
831   function Get_Check_Id (N : Name_Id) return Check_Id;
832   --  Function to search above table for matching name. If found returns the
833   --  corresponding Check_Id value in the range 1 .. Check_Name.Last. If not
834   --  found returns No_Check_Id.
835
836private
837
838   type Check_Result is array (Positive range 1 .. 2) of Node_Id;
839   --  There are two cases for the result returned by Range_Check:
840   --
841   --    For the static case the result is one or two nodes that should cause
842   --    a Constraint_Error. Typically these will include Expr itself or the
843   --    direct descendents of Expr, such as Low/High_Bound (Expr)). It is the
844   --    responsibility of the caller to rewrite and substitute the nodes with
845   --    N_Raise_Constraint_Error nodes.
846   --
847   --    For the non-static case a single N_Raise_Constraint_Error node with a
848   --    non-empty Condition field is returned.
849   --
850   --  Unused entries in Check_Result, if any, are simply set to Empty For
851   --  external clients, the required processing on this result is achieved
852   --  using the Insert_Range_Checks routine.
853
854   pragma Inline (Apply_Length_Check);
855   pragma Inline (Apply_Range_Check);
856   pragma Inline (Apply_Static_Length_Check);
857end Checks;
858