OSDN Git Service

* gcc-interface/utils2.c (build_unary_op) <ATTR_ADDR_EXPR>: Do not
[pf3gnuchains/gcc-fork.git] / gcc / ada / gcc-interface / utils2.c
index 8ab39ee..9b00c0d 100644 (file)
@@ -6,7 +6,7 @@
  *                                                                          *
  *                          C Implementation File                           *
  *                                                                          *
- *          Copyright (C) 1992-2009, Free Software Foundation, Inc.         *
+ *          Copyright (C) 1992-2010, Free Software Foundation, Inc.         *
  *                                                                          *
  * GNAT is free software;  you can  redistribute it  and/or modify it under *
  * terms of the  GNU General Public License as published  by the Free Soft- *
@@ -31,6 +31,8 @@
 #include "ggc.h"
 #include "flags.h"
 #include "output.h"
+#include "tree-inline.h"
+
 #include "ada.h"
 #include "types.h"
 #include "atree.h"
 #include "gigi.h"
 
 static tree find_common_type (tree, tree);
-static bool contains_save_expr_p (tree);
-static tree contains_null_expr (tree);
 static tree compare_arrays (tree, tree, tree);
 static tree nonbinary_modular_operation (enum tree_code, tree, tree, tree);
 static tree build_simple_component_ref (tree, tree, tree, bool);
 \f
-/* Prepare expr to be an argument of a TRUTH_NOT_EXPR or other logical
-   operation.
-
-   This preparation consists of taking the ordinary representation of
-   an expression expr and producing a valid tree boolean expression
-   describing whether expr is nonzero. We could simply always do
-
-      build_binary_op (NE_EXPR, expr, integer_zero_node, 1),
-
-   but we optimize comparisons, &&, ||, and !.
-
-   The resulting type should always be the same as the input type.
-   This function is simpler than the corresponding C version since
-   the only possible operands will be things of Boolean type.  */
-
-tree
-gnat_truthvalue_conversion (tree expr)
-{
-  tree type = TREE_TYPE (expr);
-
-  switch (TREE_CODE (expr))
-    {
-    case EQ_EXPR:  case NE_EXPR: case LE_EXPR: case GE_EXPR:
-    case LT_EXPR:  case GT_EXPR:
-    case TRUTH_ANDIF_EXPR:
-    case TRUTH_ORIF_EXPR:
-    case TRUTH_AND_EXPR:
-    case TRUTH_OR_EXPR:
-    case TRUTH_XOR_EXPR:
-    case ERROR_MARK:
-      return expr;
-
-    case INTEGER_CST:
-      return (integer_zerop (expr)
-             ? build_int_cst (type, 0)
-             : build_int_cst (type, 1));
-
-    case REAL_CST:
-      return (real_zerop (expr)
-             ? fold_convert (type, integer_zero_node)
-             : fold_convert (type, integer_one_node));
-
-    case COND_EXPR:
-      /* Distribute the conversion into the arms of a COND_EXPR.  */
-      {
-       tree arg1 = gnat_truthvalue_conversion (TREE_OPERAND (expr, 1));
-       tree arg2 = gnat_truthvalue_conversion (TREE_OPERAND (expr, 2));
-       return fold_build3 (COND_EXPR, type, TREE_OPERAND (expr, 0),
-                           arg1, arg2);
-      }
-
-    default:
-      return build_binary_op (NE_EXPR, type, expr,
-                             fold_convert (type, integer_zero_node));
-    }
-}
-\f
 /* Return the base type of TYPE.  */
 
 tree
@@ -214,6 +157,15 @@ known_alignment (tree exp)
       this_alignment = expr_align (TREE_OPERAND (exp, 0));
       break;
 
+    case CALL_EXPR:
+      {
+       tree t = maybe_inline_call_in_expr (exp);
+       if (t)
+         return known_alignment (t);
+      }
+
+      /* Fall through... */
+
     default:
       /* For other pointer expressions, we assume that the pointed-to object
         is at least as aligned as the pointed-to type.  Beware that we can
@@ -279,187 +231,116 @@ find_common_type (tree t1, tree t2)
   return NULL_TREE;
 }
 \f
-/* See if EXP contains a SAVE_EXPR in a position where we would
-   normally put it.
-
-   ??? This is a real kludge, but is probably the best approach short
-   of some very general solution.  */
-
-static bool
-contains_save_expr_p (tree exp)
-{
-  switch (TREE_CODE (exp))
-    {
-    case SAVE_EXPR:
-      return true;
+/* Return an expression tree representing an equality comparison of A1 and A2,
+   two objects of type ARRAY_TYPE.  The result should be of type RESULT_TYPE.
 
-    case ADDR_EXPR:  case INDIRECT_REF:
-    case COMPONENT_REF:
-    CASE_CONVERT: case VIEW_CONVERT_EXPR:
-      return contains_save_expr_p (TREE_OPERAND (exp, 0));
-
-    case CONSTRUCTOR:
-      {
-       tree value;
-       unsigned HOST_WIDE_INT ix;
-
-       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (exp), ix, value)
-         if (contains_save_expr_p (value))
-           return true;
-       return false;
-      }
-
-    default:
-      return false;
-    }
-}
-\f
-/* See if EXP contains a NULL_EXPR in an expression we use for sizes. Return
-   it if so.  This is used to detect types whose sizes involve computations
-   that are known to raise Constraint_Error.  */
-
-static tree
-contains_null_expr (tree exp)
-{
-  tree tem;
-
-  if (TREE_CODE (exp) == NULL_EXPR)
-    return exp;
-
-  switch (TREE_CODE_CLASS (TREE_CODE (exp)))
-    {
-    case tcc_unary:
-      return contains_null_expr (TREE_OPERAND (exp, 0));
-
-    case tcc_comparison:
-    case tcc_binary:
-      tem = contains_null_expr (TREE_OPERAND (exp, 0));
-      if (tem)
-       return tem;
-
-      return contains_null_expr (TREE_OPERAND (exp, 1));
-
-    case tcc_expression:
-      switch (TREE_CODE (exp))
-       {
-       case SAVE_EXPR:
-         return contains_null_expr (TREE_OPERAND (exp, 0));
-
-       case COND_EXPR:
-         tem = contains_null_expr (TREE_OPERAND (exp, 0));
-         if (tem)
-           return tem;
-
-         tem = contains_null_expr (TREE_OPERAND (exp, 1));
-         if (tem)
-           return tem;
-
-         return contains_null_expr (TREE_OPERAND (exp, 2));
-
-       default:
-         return 0;
-       }
-
-    default:
-      return 0;
-    }
-}
-\f
-/* Return an expression tree representing an equality comparison of
-   A1 and A2, two objects of ARRAY_TYPE.  The returned expression should
-   be of type RESULT_TYPE
-
-   Two arrays are equal in one of two ways: (1) if both have zero length
-   in some dimension (not necessarily the same dimension) or (2) if the
-   lengths in each dimension are equal and the data is equal.  We perform the
-   length tests in as efficient a manner as possible.  */
+   Two arrays are equal in one of two ways: (1) if both have zero length in
+   some dimension (not necessarily the same dimension) or (2) if the lengths
+   in each dimension are equal and the data is equal.  We perform the length
+   tests in as efficient a manner as possible.  */
 
 static tree
 compare_arrays (tree result_type, tree a1, tree a2)
 {
+  tree result = convert (result_type, boolean_true_node);
+  tree a1_is_null = convert (result_type, boolean_false_node);
+  tree a2_is_null = convert (result_type, boolean_false_node);
   tree t1 = TREE_TYPE (a1);
   tree t2 = TREE_TYPE (a2);
-  tree result = convert (result_type, integer_one_node);
-  tree a1_is_null = convert (result_type, integer_zero_node);
-  tree a2_is_null = convert (result_type, integer_zero_node);
+  bool a1_side_effects_p = TREE_SIDE_EFFECTS (a1);
+  bool a2_side_effects_p = TREE_SIDE_EFFECTS (a2);
   bool length_zero_p = false;
 
+  /* If either operand has side-effects, they have to be evaluated only once
+     in spite of the multiple references to the operand in the comparison.  */
+  if (a1_side_effects_p)
+    a1 = gnat_protect_expr (a1);
+
+  if (a2_side_effects_p)
+    a2 = gnat_protect_expr (a2);
+
   /* Process each dimension separately and compare the lengths.  If any
-     dimension has a size known to be zero, set SIZE_ZERO_P to 1 to
-     suppress the comparison of the data.  */
+     dimension has a length known to be zero, set LENGTH_ZERO_P to true
+     in order to suppress the comparison of the data at the end.  */
   while (TREE_CODE (t1) == ARRAY_TYPE && TREE_CODE (t2) == ARRAY_TYPE)
     {
       tree lb1 = TYPE_MIN_VALUE (TYPE_DOMAIN (t1));
       tree ub1 = TYPE_MAX_VALUE (TYPE_DOMAIN (t1));
       tree lb2 = TYPE_MIN_VALUE (TYPE_DOMAIN (t2));
       tree ub2 = TYPE_MAX_VALUE (TYPE_DOMAIN (t2));
-      tree bt = get_base_type (TREE_TYPE (lb1));
-      tree length1 = fold_build2 (MINUS_EXPR, bt, ub1, lb1);
-      tree length2 = fold_build2 (MINUS_EXPR, bt, ub2, lb2);
-      tree nbt;
-      tree tem;
+      tree length1 = size_binop (PLUS_EXPR, size_binop (MINUS_EXPR, ub1, lb1),
+                                size_one_node);
+      tree length2 = size_binop (PLUS_EXPR, size_binop (MINUS_EXPR, ub2, lb2),
+                                size_one_node);
       tree comparison, this_a1_is_null, this_a2_is_null;
 
       /* If the length of the first array is a constant, swap our operands
-        unless the length of the second array is the constant zero.
-        Note that we have set the `length' values to the length - 1.  */
-      if (TREE_CODE (length1) == INTEGER_CST
-         && !integer_zerop (fold_build2 (PLUS_EXPR, bt, length2,
-                                         convert (bt, integer_one_node))))
+        unless the length of the second array is the constant zero.  */
+      if (TREE_CODE (length1) == INTEGER_CST && !integer_zerop (length2))
        {
+         tree tem;
+         bool btem;
+
          tem = a1, a1 = a2, a2 = tem;
          tem = t1, t1 = t2, t2 = tem;
          tem = lb1, lb1 = lb2, lb2 = tem;
          tem = ub1, ub1 = ub2, ub2 = tem;
          tem = length1, length1 = length2, length2 = tem;
          tem = a1_is_null, a1_is_null = a2_is_null, a2_is_null = tem;
+         btem = a1_side_effects_p, a1_side_effects_p = a2_side_effects_p,
+         a2_side_effects_p = btem;
        }
 
-      /* If the length of this dimension in the second array is the constant
-        zero, we can just go inside the original bounds for the first
-        array and see if last < first.  */
-      if (integer_zerop (fold_build2 (PLUS_EXPR, bt, length2,
-                                     convert (bt, integer_one_node))))
+      /* If the length of the second array is the constant zero, we can just
+        use the original stored bounds for the first array and see whether
+        last < first holds.  */
+      if (integer_zerop (length2))
        {
-         tree ub = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (t1)));
-         tree lb = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (t1)));
+         length_zero_p = true;
+
+         ub1 = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (t1)));
+         lb1 = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (t1)));
 
-         comparison = build_binary_op (LT_EXPR, result_type, ub, lb);
+         comparison = build_binary_op (LT_EXPR, result_type, ub1, lb1);
          comparison = SUBSTITUTE_PLACEHOLDER_IN_EXPR (comparison, a1);
-         length1 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (length1, a1);
+         if (EXPR_P (comparison))
+           SET_EXPR_LOCATION (comparison, input_location);
 
-         length_zero_p = true;
          this_a1_is_null = comparison;
-         this_a2_is_null = convert (result_type, integer_one_node);
+         this_a2_is_null = convert (result_type, boolean_true_node);
        }
 
-      /* If the length is some other constant value, we know that the
-        this dimension in the first array cannot be superflat, so we
-        can just use its length from the actual stored bounds.  */
+      /* Otherwise, if the length is some other constant value, we know that
+        this dimension in the second array cannot be superflat, so we can
+        just use its length computed from the actual stored bounds.  */
       else if (TREE_CODE (length2) == INTEGER_CST)
        {
+         tree bt;
+
          ub1 = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (t1)));
          lb1 = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (t1)));
+         /* Note that we know that UB2 and LB2 are constant and hence
+            cannot contain a PLACEHOLDER_EXPR.  */
          ub2 = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (t2)));
          lb2 = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (t2)));
-         nbt = get_base_type (TREE_TYPE (ub1));
+         bt = get_base_type (TREE_TYPE (ub1));
 
          comparison
            = build_binary_op (EQ_EXPR, result_type,
-                              build_binary_op (MINUS_EXPR, nbt, ub1, lb1),
-                              build_binary_op (MINUS_EXPR, nbt, ub2, lb2));
-
-         /* Note that we know that UB2 and LB2 are constant and hence
-            cannot contain a PLACEHOLDER_EXPR.  */
-
+                              build_binary_op (MINUS_EXPR, bt, ub1, lb1),
+                              build_binary_op (MINUS_EXPR, bt, ub2, lb2));
          comparison = SUBSTITUTE_PLACEHOLDER_IN_EXPR (comparison, a1);
-         length1 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (length1, a1);
+         if (EXPR_P (comparison))
+           SET_EXPR_LOCATION (comparison, input_location);
 
          this_a1_is_null = build_binary_op (LT_EXPR, result_type, ub1, lb1);
-         this_a2_is_null = convert (result_type, integer_zero_node);
+         if (EXPR_P (this_a1_is_null))
+           SET_EXPR_LOCATION (this_a1_is_null, input_location);
+
+         this_a2_is_null = convert (result_type, boolean_false_node);
        }
 
-      /* Otherwise compare the computed lengths.  */
+      /* Otherwise, compare the computed lengths.  */
       else
        {
          length1 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (length1, a1);
@@ -467,20 +348,39 @@ compare_arrays (tree result_type, tree a1, tree a2)
 
          comparison
            = build_binary_op (EQ_EXPR, result_type, length1, length2);
-
-         this_a1_is_null
-           = build_binary_op (LT_EXPR, result_type, length1,
-                              convert (bt, integer_zero_node));
-         this_a2_is_null
-           = build_binary_op (LT_EXPR, result_type, length2,
-                              convert (bt, integer_zero_node));
+         if (EXPR_P (comparison))
+           SET_EXPR_LOCATION (comparison, input_location);
+
+         /* If the length expression is of the form (cond ? val : 0), assume
+            that cond is equivalent to (length != 0).  That's guaranteed by
+            construction of the array types in gnat_to_gnu_entity.  */
+         if (TREE_CODE (length1) == COND_EXPR
+             && integer_zerop (TREE_OPERAND (length1, 2)))
+           this_a1_is_null = invert_truthvalue (TREE_OPERAND (length1, 0));
+         else
+           this_a1_is_null = build_binary_op (EQ_EXPR, result_type, length1,
+                                              size_zero_node);
+          if (EXPR_P (this_a1_is_null))
+           SET_EXPR_LOCATION (this_a1_is_null, input_location);
+
+         /* Likewise for the second array.  */
+         if (TREE_CODE (length2) == COND_EXPR
+             && integer_zerop (TREE_OPERAND (length2, 2)))
+           this_a2_is_null = invert_truthvalue (TREE_OPERAND (length2, 0));
+         else
+           this_a2_is_null = build_binary_op (EQ_EXPR, result_type, length2,
+                                              size_zero_node);
+          if (EXPR_P (this_a2_is_null))
+           SET_EXPR_LOCATION (this_a2_is_null, input_location);
        }
 
+      /* Append expressions for this dimension to the final expressions.  */
       result = build_binary_op (TRUTH_ANDIF_EXPR, result_type,
                                result, comparison);
 
       a1_is_null = build_binary_op (TRUTH_ORIF_EXPR, result_type,
                                    this_a1_is_null, a1_is_null);
+
       a2_is_null = build_binary_op (TRUTH_ORIF_EXPR, result_type,
                                    this_a2_is_null, a2_is_null);
 
@@ -488,18 +388,25 @@ compare_arrays (tree result_type, tree a1, tree a2)
       t2 = TREE_TYPE (t2);
     }
 
-  /* Unless the size of some bound is known to be zero, compare the
+  /* Unless the length of some dimension is known to be zero, compare the
      data in the array.  */
   if (!length_zero_p)
     {
       tree type = find_common_type (TREE_TYPE (a1), TREE_TYPE (a2));
+      tree comparison;
 
       if (type)
-       a1 = convert (type, a1), a2 = convert (type, a2);
+       {
+         a1 = convert (type, a1),
+         a2 = convert (type, a2);
+       }
 
-      result = build_binary_op (TRUTH_ANDIF_EXPR, result_type, result,
-                               fold_build2 (EQ_EXPR, result_type, a1, a2));
+      comparison = fold_build2 (EQ_EXPR, result_type, a1, a2);
+      if (EXPR_P (comparison))
+       SET_EXPR_LOCATION (comparison, input_location);
 
+      result
+       = build_binary_op (TRUTH_ANDIF_EXPR, result_type, result, comparison);
     }
 
   /* The result is also true if both sizes are zero.  */
@@ -508,14 +415,13 @@ compare_arrays (tree result_type, tree a1, tree a2)
                                             a1_is_null, a2_is_null),
                            result);
 
-  /* If either operand contains SAVE_EXPRs, they have to be evaluated before
-     starting the comparison above since the place it would be otherwise
-     evaluated would be wrong.  */
-
-  if (contains_save_expr_p (a1))
+  /* If either operand has side-effects, they have to be evaluated before
+     starting the comparison above since the place they would be otherwise
+     evaluated could be wrong.  */
+  if (a1_side_effects_p)
     result = build2 (COMPOUND_EXPR, result_type, a1, result);
 
-  if (contains_save_expr_p (a2))
+  if (a2_side_effects_p)
     result = build2 (COMPOUND_EXPR, result_type, a2, result);
 
   return result;
@@ -593,9 +499,9 @@ nonbinary_modular_operation (enum tree_code op_code, tree type, tree lhs,
   /* For subtraction, add the modulus back if we are negative.  */
   else if (op_code == MINUS_EXPR)
     {
-      result = save_expr (result);
+      result = gnat_protect_expr (result);
       result = fold_build3 (COND_EXPR, op_type,
-                           fold_build2 (LT_EXPR, integer_type_node, result,
+                           fold_build2 (LT_EXPR, boolean_type_node, result,
                                         convert (op_type, integer_zero_node)),
                            fold_build2 (PLUS_EXPR, op_type, result, modulus),
                            result);
@@ -604,9 +510,9 @@ nonbinary_modular_operation (enum tree_code op_code, tree type, tree lhs,
   /* For the other operations, subtract the modulus if we are >= it.  */
   else
     {
-      result = save_expr (result);
+      result = gnat_protect_expr (result);
       result = fold_build3 (COND_EXPR, op_type,
-                           fold_build2 (GE_EXPR, integer_type_node,
+                           fold_build2 (GE_EXPR, boolean_type_node,
                                         result, modulus),
                            fold_build2 (MINUS_EXPR, op_type,
                                         result, modulus),
@@ -655,6 +561,7 @@ build_binary_op (enum tree_code op_code, tree result_type,
 
   switch (op_code)
     {
+    case INIT_EXPR:
     case MODIFY_EXPR:
       /* If there were integral or pointer conversions on the LHS, remove
         them; we'll be putting them back below if needed.  Likewise for
@@ -696,21 +603,21 @@ build_binary_op (enum tree_code op_code, tree result_type,
 
       /* If we are copying between padded objects with compatible types, use
         the padded view of the objects, this is very likely more efficient.
-        Likewise for a padded that is assigned a constructor, in order to
-        avoid putting a VIEW_CONVERT_EXPR on the LHS.  But don't do this if
-        we wouldn't have actually copied anything.  */
-      else if (TREE_CODE (left_type) == RECORD_TYPE
-              && TYPE_IS_PADDING_P (left_type)
+        Likewise for a padded object that is assigned a constructor, if we
+        can convert the constructor to the inner type, to avoid putting a
+        VIEW_CONVERT_EXPR on the LHS.  But don't do so if we wouldn't have
+        actually copied anything.  */
+      else if (TYPE_IS_PADDING_P (left_type)
               && TREE_CONSTANT (TYPE_SIZE (left_type))
               && ((TREE_CODE (right_operand) == COMPONENT_REF
-                   && TREE_CODE (TREE_TYPE (TREE_OPERAND (right_operand, 0)))
-                      == RECORD_TYPE
                    && TYPE_IS_PADDING_P
                       (TREE_TYPE (TREE_OPERAND (right_operand, 0)))
                    && gnat_types_compatible_p
-                       (left_type,
-                        TREE_TYPE (TREE_OPERAND (right_operand, 0))))
-                  || TREE_CODE (right_operand) == CONSTRUCTOR)
+                      (left_type,
+                       TREE_TYPE (TREE_OPERAND (right_operand, 0))))
+                  || (TREE_CODE (right_operand) == CONSTRUCTOR
+                      && !CONTAINS_PLACEHOLDER_P
+                          (DECL_SIZE (TYPE_FIELDS (left_type)))))
               && !integer_zerop (TYPE_SIZE (right_type)))
        operation_type = left_type;
 
@@ -801,11 +708,16 @@ build_binary_op (enum tree_code op_code, tree result_type,
          left_type = TREE_TYPE (left_operand);
        }
 
-      /* Then convert the right operand to its base type.  This will
-        prevent unneeded signedness conversions when sizetype is wider than
-        integer.  */
+      /* For a range, make sure the element type is consistent.  */
+      if (op_code == ARRAY_RANGE_REF
+         && TREE_TYPE (operation_type) != TREE_TYPE (left_type))
+       operation_type = build_array_type (TREE_TYPE (left_type),
+                                          TYPE_DOMAIN (operation_type));
+
+      /* Then convert the right operand to its base type.  This will prevent
+        unneeded sign conversions when sizetype is wider than integer.  */
       right_operand = convert (right_base_type, right_operand);
-      right_operand = convert (TYPE_DOMAIN (left_type), right_operand);
+      right_operand = convert (sizetype, right_operand);
 
       if (!TREE_CONSTANT (right_operand)
          || !TREE_CONSTANT (TYPE_MIN_VALUE (right_type)))
@@ -814,16 +726,28 @@ build_binary_op (enum tree_code op_code, tree result_type,
       modulus = NULL_TREE;
       break;
 
+    case TRUTH_ANDIF_EXPR:
+    case TRUTH_ORIF_EXPR:
+    case TRUTH_AND_EXPR:
+    case TRUTH_OR_EXPR:
+    case TRUTH_XOR_EXPR:
+#ifdef ENABLE_CHECKING
+      gcc_assert (TREE_CODE (get_base_type (result_type)) == BOOLEAN_TYPE);
+#endif
+      operation_type = left_base_type;
+      left_operand = convert (operation_type, left_operand);
+      right_operand = convert (operation_type, right_operand);
+      break;
+
     case GE_EXPR:
     case LE_EXPR:
     case GT_EXPR:
     case LT_EXPR:
-      gcc_assert (!POINTER_TYPE_P (left_type));
-
-      /* ... fall through ... */
-
     case EQ_EXPR:
     case NE_EXPR:
+#ifdef ENABLE_CHECKING
+      gcc_assert (TREE_CODE (get_base_type (result_type)) == BOOLEAN_TYPE);
+#endif
       /* If either operand is a NULL_EXPR, just return a new one.  */
       if (TREE_CODE (left_operand) == NULL_EXPR)
        return build2 (op_code, result_type,
@@ -875,26 +799,28 @@ build_binary_op (enum tree_code op_code, tree result_type,
          return result;
        }
 
-      /* Otherwise, the base types must be the same unless the objects are
-        fat pointers or records.  If we have records, use the best type and
-        convert both operands to that type.  */
+      /* Otherwise, the base types must be the same, unless they are both fat
+        pointer types or record types.  In the latter case, use the best type
+        and convert both operands to that type.  */
       if (left_base_type != right_base_type)
        {
-         if (TYPE_FAT_POINTER_P (left_base_type)
-             && TYPE_FAT_POINTER_P (right_base_type)
-             && TYPE_MAIN_VARIANT (left_base_type)
-                == TYPE_MAIN_VARIANT (right_base_type))
-           best_type = left_base_type;
+         if (TYPE_IS_FAT_POINTER_P (left_base_type)
+             && TYPE_IS_FAT_POINTER_P (right_base_type))
+           {
+             gcc_assert (TYPE_MAIN_VARIANT (left_base_type)
+                         == TYPE_MAIN_VARIANT (right_base_type));
+             best_type = left_base_type;
+           }
+
          else if (TREE_CODE (left_base_type) == RECORD_TYPE
                   && TREE_CODE (right_base_type) == RECORD_TYPE)
            {
-             /* The only way these are permitted to be the same is if both
-                types have the same name.  In that case, one of them must
-                not be self-referential.  Use that one as the best type.
-                Even better is if one is of fixed size.  */
+             /* The only way this is permitted is if both types have the same
+                name.  In that case, one of them must not be self-referential.
+                Use it as the best type.  Even better with a fixed size.  */
              gcc_assert (TYPE_NAME (left_base_type)
-                         && (TYPE_NAME (left_base_type)
-                             == TYPE_NAME (right_base_type)));
+                         && TYPE_NAME (left_base_type)
+                            == TYPE_NAME (right_base_type));
 
              if (TREE_CONSTANT (TYPE_SIZE (left_base_type)))
                best_type = left_base_type;
@@ -907,44 +833,37 @@ build_binary_op (enum tree_code op_code, tree result_type,
              else
                gcc_unreachable ();
            }
+
          else
            gcc_unreachable ();
 
          left_operand = convert (best_type, left_operand);
          right_operand = convert (best_type, right_operand);
        }
-
-      /* If we are comparing a fat pointer against zero, we need to
-        just compare the data pointer.  */
-      else if (TYPE_FAT_POINTER_P (left_base_type)
-              && TREE_CODE (right_operand) == CONSTRUCTOR
-              && integer_zerop (VEC_index (constructor_elt,
-                                           CONSTRUCTOR_ELTS (right_operand),
-                                           0)
-                                ->value))
-       {
-         right_operand = build_component_ref (left_operand, NULL_TREE,
-                                              TYPE_FIELDS (left_base_type),
-                                              false);
-         left_operand = convert (TREE_TYPE (right_operand),
-                                 integer_zero_node);
-       }
       else
        {
          left_operand = convert (left_base_type, left_operand);
          right_operand = convert (right_base_type, right_operand);
        }
 
+      /* If we are comparing a fat pointer against zero, we just need to
+        compare the data pointer.  */
+      if (TYPE_IS_FAT_POINTER_P (left_base_type)
+         && TREE_CODE (right_operand) == CONSTRUCTOR
+         && integer_zerop (VEC_index (constructor_elt,
+                                      CONSTRUCTOR_ELTS (right_operand),
+                                      0)->value))
+       {
+         left_operand
+           = build_component_ref (left_operand, NULL_TREE,
+                                  TYPE_FIELDS (left_base_type), false);
+         right_operand
+           = convert (TREE_TYPE (left_operand), integer_zero_node);
+       }
+
       modulus = NULL_TREE;
       break;
 
-    case PREINCREMENT_EXPR:
-    case PREDECREMENT_EXPR:
-    case POSTINCREMENT_EXPR:
-    case POSTDECREMENT_EXPR:
-      /* These operations are not used anymore.  */
-      gcc_unreachable ();
-
     case LSHIFT_EXPR:
     case RSHIFT_EXPR:
     case LROTATE_EXPR:
@@ -957,15 +876,6 @@ build_binary_op (enum tree_code op_code, tree result_type,
       left_operand = convert (operation_type, left_operand);
       break;
 
-    case TRUTH_ANDIF_EXPR:
-    case TRUTH_ORIF_EXPR:
-    case TRUTH_AND_EXPR:
-    case TRUTH_OR_EXPR:
-    case TRUTH_XOR_EXPR:
-      left_operand = gnat_truthvalue_conversion (left_operand);
-      right_operand = gnat_truthvalue_conversion (right_operand);
-      goto common;
-
     case BIT_AND_EXPR:
     case BIT_IOR_EXPR:
     case BIT_XOR_EXPR:
@@ -1106,8 +1016,10 @@ build_unary_op (enum tree_code op_code, tree result_type, tree operand)
       break;
 
     case TRUTH_NOT_EXPR:
-      gcc_assert (result_type == base_type);
-      result = invert_truthvalue (gnat_truthvalue_conversion (operand));
+#ifdef ENABLE_CHECKING
+      gcc_assert (TREE_CODE (get_base_type (result_type)) == BOOLEAN_TYPE);
+#endif
+      result = invert_truthvalue (operand);
       break;
 
     case ATTR_ADDR_EXPR:
@@ -1148,13 +1060,28 @@ build_unary_op (enum tree_code op_code, tree result_type, tree operand)
          TREE_TYPE (result) = type = build_pointer_type (type);
          break;
 
+       case COMPOUND_EXPR:
+         /* Fold a compound expression if it has unconstrained array type
+            since the middle-end cannot handle it.  But we don't it in the
+            general case because it may introduce aliasing issues if the
+            first operand is an indirect assignment and the second operand
+            the corresponding address, e.g. for an allocator.  */
+         if (TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
+           {
+             result = build_unary_op (ADDR_EXPR, result_type,
+                                      TREE_OPERAND (operand, 1));
+             result = build2 (COMPOUND_EXPR, TREE_TYPE (result),
+                              TREE_OPERAND (operand, 0), result);
+             break;
+           }
+         goto common;
+
        case ARRAY_REF:
        case ARRAY_RANGE_REF:
        case COMPONENT_REF:
        case BIT_FIELD_REF:
-           /* If this is for 'Address, find the address of the prefix and
-              add the offset to the field.  Otherwise, do this the normal
-              way.  */
+           /* If this is for 'Address, find the address of the prefix and add
+              the offset to the field.  Otherwise, do this the normal way.  */
          if (op_code == ATTR_ADDR_EXPR)
            {
              HOST_WIDE_INT bitsize;
@@ -1170,11 +1097,10 @@ build_unary_op (enum tree_code op_code, tree result_type, tree operand)
              /* If INNER is a padding type whose field has a self-referential
                 size, convert to that inner type.  We know the offset is zero
                 and we need to have that type visible.  */
-             if (TREE_CODE (TREE_TYPE (inner)) == RECORD_TYPE
-                 && TYPE_IS_PADDING_P (TREE_TYPE (inner))
-                 && (CONTAINS_PLACEHOLDER_P
-                     (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS
-                                            (TREE_TYPE (inner)))))))
+             if (TYPE_IS_PADDING_P (TREE_TYPE (inner))
+                 && CONTAINS_PLACEHOLDER_P
+                    (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS
+                                           (TREE_TYPE (inner))))))
                inner = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (inner))),
                                 inner);
 
@@ -1182,11 +1108,6 @@ build_unary_op (enum tree_code op_code, tree result_type, tree operand)
              if (!offset)
                offset = size_zero_node;
 
-             if (bitpos % BITS_PER_UNIT != 0)
-               post_error
-                 ("taking address of object not aligned on storage unit?",
-                  error_gnat_node);
-
              offset = size_binop (PLUS_EXPR, offset,
                                   size_int (bitpos / BITS_PER_UNIT));
 
@@ -1207,13 +1128,11 @@ build_unary_op (enum tree_code op_code, tree result_type, tree operand)
          /* If this is just a constructor for a padded record, we can
             just take the address of the single field and convert it to
             a pointer to our type.  */
-         if (TREE_CODE (type) == RECORD_TYPE && TYPE_IS_PADDING_P (type))
+         if (TYPE_IS_PADDING_P (type))
            {
-             result = (VEC_index (constructor_elt,
-                                  CONSTRUCTOR_ELTS (operand),
-                                  0)
-                       ->value);
-
+             result = VEC_index (constructor_elt,
+                                 CONSTRUCTOR_ELTS (operand),
+                                 0)->value;
              result = convert (build_pointer_type (TREE_TYPE (operand)),
                                build_unary_op (ADDR_EXPR, NULL_TREE, result));
              break;
@@ -1255,8 +1174,7 @@ build_unary_op (enum tree_code op_code, tree result_type, tree operand)
 
          /* If we are taking the address of a padded record whose field is
             contains a template, take the address of the template.  */
-         if (TREE_CODE (type) == RECORD_TYPE
-             && TYPE_IS_PADDING_P (type)
+         if (TYPE_IS_PADDING_P (type)
              && TREE_CODE (TREE_TYPE (TYPE_FIELDS (type))) == RECORD_TYPE
              && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (TYPE_FIELDS (type))))
            {
@@ -1264,22 +1182,18 @@ build_unary_op (enum tree_code op_code, tree result_type, tree operand)
              operand = convert (type, operand);
            }
 
-         if (type != error_mark_node)
-           operation_type = build_pointer_type (type);
-
          gnat_mark_addressable (operand);
-         result = fold_build1 (ADDR_EXPR, operation_type, operand);
+         result = build_fold_addr_expr (operand);
        }
 
       TREE_CONSTANT (result) = staticp (operand) || TREE_CONSTANT (operand);
       break;
 
     case INDIRECT_REF:
-      /* If we want to refer to an entire unconstrained array,
-        make up an expression to do so.  This will never survive to
-        the backend.  If TYPE is a thin pointer, first convert the
-        operand to a fat pointer.  */
-      if (TYPE_THIN_POINTER_P (type)
+      /* If we want to refer to an unconstrained array, use the appropriate
+        expression to do so.  This will never survive down to the back-end.
+        But if TYPE is a thin pointer, first convert to a fat pointer.  */
+      if (TYPE_IS_THIN_POINTER_P (type)
          && TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type)))
        {
          operand
@@ -1288,24 +1202,27 @@ build_unary_op (enum tree_code op_code, tree result_type, tree operand)
          type = TREE_TYPE (operand);
        }
 
-      if (TYPE_FAT_POINTER_P (type))
+      if (TYPE_IS_FAT_POINTER_P (type))
        {
          result = build1 (UNCONSTRAINED_ARRAY_REF,
                           TYPE_UNCONSTRAINED_ARRAY (type), operand);
-         TREE_READONLY (result) = TREE_STATIC (result)
+         TREE_READONLY (result)
            = TYPE_READONLY (TYPE_UNCONSTRAINED_ARRAY (type));
        }
+
+      /* If we are dereferencing an ADDR_EXPR, return its operand.  */
       else if (TREE_CODE (operand) == ADDR_EXPR)
        result = TREE_OPERAND (operand, 0);
 
+      /* Otherwise, build and fold the indirect reference.  */
       else
        {
-         result = fold_build1 (op_code, TREE_TYPE (type), operand);
+         result = build_fold_indirect_ref (operand);
          TREE_READONLY (result) = TYPE_READONLY (TREE_TYPE (type));
        }
 
       side_effects
-       =  (!TYPE_FAT_POINTER_P (type) && TYPE_VOLATILE (TREE_TYPE (type)));
+       = (!TYPE_IS_FAT_POINTER_P (type) && TYPE_VOLATILE (TREE_TYPE (type)));
       break;
 
     case NEGATE_EXPR:
@@ -1353,7 +1270,7 @@ build_unary_op (enum tree_code op_code, tree result_type, tree operand)
 
                result = fold_build3 (COND_EXPR, operation_type,
                                      fold_build2 (NE_EXPR,
-                                                  integer_type_node,
+                                                  boolean_type_node,
                                                   operand,
                                                   convert
                                                     (operation_type,
@@ -1410,88 +1327,80 @@ tree
 build_cond_expr (tree result_type, tree condition_operand,
                  tree true_operand, tree false_operand)
 {
-  tree result;
   bool addr_p = false;
+  tree result;
 
-  /* The front-end verifies that result, true and false operands have same base
-     type.  Convert everything to the result type.  */
-
-  true_operand  = convert (result_type, true_operand);
+  /* The front-end verified that result, true and false operands have
+     same base type.  Convert everything to the result type.  */
+  true_operand = convert (result_type, true_operand);
   false_operand = convert (result_type, false_operand);
 
-  /* If the result type is unconstrained, take the address of
-     the operands and then dereference our result.  */
+  /* If the result type is unconstrained, take the address of the operands and
+     then dereference the result.  Likewise if the result type is passed by
+     reference, but this is natively handled in the gimplifier.  */
   if (TREE_CODE (result_type) == UNCONSTRAINED_ARRAY_TYPE
       || CONTAINS_PLACEHOLDER_P (TYPE_SIZE (result_type)))
     {
-      addr_p = true;
       result_type = build_pointer_type (result_type);
       true_operand = build_unary_op (ADDR_EXPR, result_type, true_operand);
       false_operand = build_unary_op (ADDR_EXPR, result_type, false_operand);
+      addr_p = true;
     }
 
   result = fold_build3 (COND_EXPR, result_type, condition_operand,
                        true_operand, false_operand);
 
-  /* If either operand is a SAVE_EXPR (possibly surrounded by
-     arithmetic, make sure it gets done.  */
-  true_operand  = skip_simple_arithmetic (true_operand);
+  /* If we have a common SAVE_EXPR (possibly surrounded by arithmetics)
+     in both arms, make sure it gets evaluated by moving it ahead of the
+     conditional expression.  This is necessary because it is evaluated
+     in only one place at run time and would otherwise be uninitialized
+     in one of the arms.  */
+  true_operand = skip_simple_arithmetic (true_operand);
   false_operand = skip_simple_arithmetic (false_operand);
 
-  if (TREE_CODE (true_operand) == SAVE_EXPR)
+  if (true_operand == false_operand && TREE_CODE (true_operand) == SAVE_EXPR)
     result = build2 (COMPOUND_EXPR, result_type, true_operand, result);
 
-  if (TREE_CODE (false_operand) == SAVE_EXPR)
-    result = build2 (COMPOUND_EXPR, result_type, false_operand, result);
-
-  /* ??? Seems the code above is wrong, as it may move ahead of the COND
-     SAVE_EXPRs with side effects and not shared by both arms.  */
-
- if (addr_p)
+  if (addr_p)
     result = build_unary_op (INDIRECT_REF, NULL_TREE, result);
 
   return result;
 }
 
-/* Similar, but for RETURN_EXPR.  If RESULT_DECL is non-zero, build
-   a RETURN_EXPR around the assignment of RET_VAL to RESULT_DECL.
-   If RESULT_DECL is zero, build a bare RETURN_EXPR.  */
+/* Similar, but for RETURN_EXPR.  If RET_VAL is non-null, build a RETURN_EXPR
+   around the assignment of RET_VAL to RET_OBJ.  Otherwise just build a bare
+   RETURN_EXPR around RESULT_OBJ, which may be null in this case.  */
 
 tree
-build_return_expr (tree result_decl, tree ret_val)
+build_return_expr (tree ret_obj, tree ret_val)
 {
   tree result_expr;
 
-  if (result_decl)
+  if (ret_val)
     {
       /* The gimplifier explicitly enforces the following invariant:
 
-           RETURN_EXPR
-               |
-           MODIFY_EXPR
-           /        \
-          /          \
-      RESULT_DECL    ...
-
-      As a consequence, type-homogeneity dictates that we use the type
-      of the RESULT_DECL as the operation type.  */
-
-      tree operation_type = TREE_TYPE (result_decl);
+             RETURN_EXPR
+                 |
+             MODIFY_EXPR
+             /        \
+            /          \
+        RET_OBJ        ...
 
-      /* Convert the right operand to the operation type.  Note that
-         it's the same transformation as in the MODIFY_EXPR case of
-         build_binary_op with the additional guarantee that the type
-         cannot involve a placeholder, since otherwise the function
-         would use the "target pointer" return mechanism.  */
+        As a consequence, type consistency dictates that we use the type
+        of the RET_OBJ as the operation type.  */
+      tree operation_type = TREE_TYPE (ret_obj);
 
+      /* Convert the right operand to the operation type.  Note that it's the
+        same transformation as in the MODIFY_EXPR case of build_binary_op,
+        with the assumption that the type cannot involve a placeholder.  */
       if (operation_type != TREE_TYPE (ret_val))
        ret_val = convert (operation_type, ret_val);
 
-      result_expr
-       = build2 (MODIFY_EXPR, operation_type, result_decl, ret_val);
+      result_expr = build2 (MODIFY_EXPR, operation_type, ret_obj, ret_val);
     }
   else
-    result_expr = NULL_TREE;
+    result_expr = ret_obj;
 
   return build1 (RETURN_EXPR, void_type_node, result_expr);
 }
@@ -1596,12 +1505,13 @@ build_call_raise (int msg, Node_Id gnat_node, char kind)
     = (gnat_node != Empty && Sloc (gnat_node) != No_Location)
       ? Get_Logical_Line_Number (Sloc(gnat_node)) : input_line;
 
-  TREE_TYPE (filename)
-    = build_array_type (char_type_node, build_index_type (size_int (len)));
+  TREE_TYPE (filename) = build_array_type (unsigned_char_type_node,
+                                          build_index_type (size_int (len)));
 
   return
     build_call_2_expr (fndecl,
-                      build1 (ADDR_EXPR, build_pointer_type (char_type_node),
+                      build1 (ADDR_EXPR,
+                              build_pointer_type (unsigned_char_type_node),
                               filename),
                       build_int_cst (NULL_TREE, line_number));
 }
@@ -1627,35 +1537,29 @@ compare_elmt_bitpos (const PTR rt1, const PTR rt2)
 tree
 gnat_build_constructor (tree type, tree list)
 {
-  tree elmt;
-  int n_elmts;
   bool allconstant = (TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST);
   bool side_effects = false;
-  tree result;
+  tree elmt, result;
+  int n_elmts;
 
   /* Scan the elements to see if they are all constant or if any has side
      effects, to let us set global flags on the resulting constructor.  Count
      the elements along the way for possible sorting purposes below.  */
   for (n_elmts = 0, elmt = list; elmt; elmt = TREE_CHAIN (elmt), n_elmts ++)
     {
-      if (!TREE_CONSTANT (TREE_VALUE (elmt))
+      tree obj = TREE_PURPOSE (elmt);
+      tree val = TREE_VALUE (elmt);
+
+      /* The predicate must be in keeping with output_constructor.  */
+      if (!TREE_CONSTANT (val)
          || (TREE_CODE (type) == RECORD_TYPE
-             && DECL_BIT_FIELD (TREE_PURPOSE (elmt))
-             && TREE_CODE (TREE_VALUE (elmt)) != INTEGER_CST)
-         || !initializer_constant_valid_p (TREE_VALUE (elmt),
-                                           TREE_TYPE (TREE_VALUE (elmt))))
+             && CONSTRUCTOR_BITFIELD_P (obj)
+             && !initializer_constant_valid_for_bitfield_p (val))
+         || !initializer_constant_valid_p (val, TREE_TYPE (val)))
        allconstant = false;
 
-      if (TREE_SIDE_EFFECTS (TREE_VALUE (elmt)))
+      if (TREE_SIDE_EFFECTS (val))
        side_effects = true;
-
-      /* Propagate an NULL_EXPR from the size of the type.  We won't ever
-        be executing the code we generate here in that case, but handle it
-        specially to avoid the compiler blowing up.  */
-      if (TREE_CODE (type) == RECORD_TYPE
-         && (0 != (result
-                   = contains_null_expr (DECL_SIZE (TREE_PURPOSE (elmt))))))
-       return build1 (NULL_EXPR, type, TREE_OPERAND (result, 0));
     }
 
   /* For record types with constant components only, sort field list
@@ -1728,22 +1632,15 @@ build_simple_component_ref (tree record_variable, tree component,
       tree new_field;
 
       /* First loop thru normal components.  */
-
       for (new_field = TYPE_FIELDS (record_type); new_field;
           new_field = TREE_CHAIN (new_field))
-       if (field == new_field
-           || DECL_ORIGINAL_FIELD (new_field) == field
-           || new_field == DECL_ORIGINAL_FIELD (field)
-           || (DECL_ORIGINAL_FIELD (field)
-               && (DECL_ORIGINAL_FIELD (field)
-                   == DECL_ORIGINAL_FIELD (new_field))))
+       if (SAME_FIELD_P (field, new_field))
          break;
 
       /* Next, loop thru DECL_INTERNAL_P components if we haven't found
          the component in the first search. Doing this search in 2 steps
          is required to avoiding hidden homonymous fields in the
          _Parent field.  */
-
       if (!new_field)
        for (new_field = TYPE_FIELDS (record_type); new_field;
             new_field = TREE_CHAIN (new_field))
@@ -1825,146 +1722,246 @@ build_component_ref (tree record_variable, tree component,
   if (ref)
     return ref;
 
-  /* If FIELD was specified, assume this is an invalid user field so
-     raise constraint error.  Otherwise, we can't find the type to return, so
-     abort.  */
+  /* If FIELD was specified, assume this is an invalid user field so raise
+     Constraint_Error.  Otherwise, we have no type to return so abort.  */
   gcc_assert (field);
   return build1 (NULL_EXPR, TREE_TYPE (field),
                 build_call_raise (CE_Discriminant_Check_Failed, Empty,
                                   N_Raise_Constraint_Error));
 }
 \f
+/* Helper for build_call_alloc_dealloc, with arguments to be interpreted
+   identically.  Process the case where a GNAT_PROC to call is provided.  */
+
+static inline tree
+build_call_alloc_dealloc_proc (tree gnu_obj, tree gnu_size, tree gnu_type,
+                              Entity_Id gnat_proc, Entity_Id gnat_pool)
+{
+  tree gnu_proc = gnat_to_gnu (gnat_proc);
+  tree gnu_proc_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_proc);
+  tree gnu_call;
+
+  /* The storage pools are obviously always tagged types, but the
+     secondary stack uses the same mechanism and is not tagged.  */
+  if (Is_Tagged_Type (Etype (gnat_pool)))
+    {
+      /* The size is the third parameter; the alignment is the
+        same type.  */
+      Entity_Id gnat_size_type
+       = Etype (Next_Formal (Next_Formal (First_Formal (gnat_proc))));
+      tree gnu_size_type = gnat_to_gnu_type (gnat_size_type);
+
+      tree gnu_pool = gnat_to_gnu (gnat_pool);
+      tree gnu_pool_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_pool);
+      tree gnu_align = size_int (TYPE_ALIGN (gnu_type) / BITS_PER_UNIT);
+
+      gnu_size = convert (gnu_size_type, gnu_size);
+      gnu_align = convert (gnu_size_type, gnu_align);
+
+      /* The first arg is always the address of the storage pool; next
+        comes the address of the object, for a deallocator, then the
+        size and alignment.  */
+      if (gnu_obj)
+       gnu_call = build_call_nary (TREE_TYPE (TREE_TYPE (gnu_proc)),
+                                   gnu_proc_addr, 4, gnu_pool_addr,
+                                   gnu_obj, gnu_size, gnu_align);
+      else
+       gnu_call = build_call_nary (TREE_TYPE (TREE_TYPE (gnu_proc)),
+                                   gnu_proc_addr, 3, gnu_pool_addr,
+                                   gnu_size, gnu_align);
+    }
+
+  /* Secondary stack case.  */
+  else
+    {
+      /* The size is the second parameter.  */
+      Entity_Id gnat_size_type
+       = Etype (Next_Formal (First_Formal (gnat_proc)));
+      tree gnu_size_type = gnat_to_gnu_type (gnat_size_type);
+
+      gnu_size = convert (gnu_size_type, gnu_size);
+
+      /* The first arg is the address of the object, for a deallocator,
+        then the size.  */
+      if (gnu_obj)
+       gnu_call = build_call_nary (TREE_TYPE (TREE_TYPE (gnu_proc)),
+                                   gnu_proc_addr, 2, gnu_obj, gnu_size);
+      else
+       gnu_call = build_call_nary (TREE_TYPE (TREE_TYPE (gnu_proc)),
+                                   gnu_proc_addr, 1, gnu_size);
+    }
+
+  TREE_SIDE_EFFECTS (gnu_call) = 1;
+  return gnu_call;
+}
+
+/* Helper for build_call_alloc_dealloc, to build and return an allocator for
+   DATA_SIZE bytes aimed at containing a DATA_TYPE object, using the default
+   __gnat_malloc allocator.  Honor DATA_TYPE alignments greater than what the
+   latter offers.  */
+
+static inline tree
+maybe_wrap_malloc (tree data_size, tree data_type, Node_Id gnat_node)
+{
+  /* When the DATA_TYPE alignment is stricter than what malloc offers
+     (super-aligned case), we allocate an "aligning" wrapper type and return
+     the address of its single data field with the malloc's return value
+     stored just in front.  */
+
+  unsigned int data_align = TYPE_ALIGN (data_type);
+  unsigned int default_allocator_alignment
+      = get_target_default_allocator_alignment () * BITS_PER_UNIT;
+
+  tree aligning_type
+    = ((data_align > default_allocator_alignment)
+       ? make_aligning_type (data_type, data_align, data_size,
+                            default_allocator_alignment,
+                            POINTER_SIZE / BITS_PER_UNIT)
+       : NULL_TREE);
+
+  tree size_to_malloc
+    = aligning_type ? TYPE_SIZE_UNIT (aligning_type) : data_size;
+
+  tree malloc_ptr;
+
+  /* On VMS, if 64-bit memory is disabled or pointers are 64-bit and the
+     allocator size is 32-bit or Convention C, allocate 32-bit memory.  */
+  if (TARGET_ABI_OPEN_VMS
+      && (!TARGET_MALLOC64
+         || (POINTER_SIZE == 64
+             && (UI_To_Int (Esize (Etype (gnat_node))) == 32
+                 || Convention (Etype (gnat_node)) == Convention_C))))
+    malloc_ptr = build_call_1_expr (malloc32_decl, size_to_malloc);
+  else
+    malloc_ptr = build_call_1_expr (malloc_decl, size_to_malloc);
+
+  if (aligning_type)
+    {
+      /* Latch malloc's return value and get a pointer to the aligning field
+        first.  */
+      tree storage_ptr = gnat_protect_expr (malloc_ptr);
+
+      tree aligning_record_addr
+       = convert (build_pointer_type (aligning_type), storage_ptr);
+
+      tree aligning_record
+       = build_unary_op (INDIRECT_REF, NULL_TREE, aligning_record_addr);
+
+      tree aligning_field
+       = build_component_ref (aligning_record, NULL_TREE,
+                              TYPE_FIELDS (aligning_type), false);
+
+      tree aligning_field_addr
+        = build_unary_op (ADDR_EXPR, NULL_TREE, aligning_field);
+
+      /* Then arrange to store the allocator's return value ahead
+        and return.  */
+      tree storage_ptr_slot_addr
+       = build_binary_op (POINTER_PLUS_EXPR, ptr_void_type_node,
+                          convert (ptr_void_type_node, aligning_field_addr),
+                          size_int (-(HOST_WIDE_INT) POINTER_SIZE
+                                    / BITS_PER_UNIT));
+
+      tree storage_ptr_slot
+       = build_unary_op (INDIRECT_REF, NULL_TREE,
+                         convert (build_pointer_type (ptr_void_type_node),
+                                  storage_ptr_slot_addr));
+
+      return
+       build2 (COMPOUND_EXPR, TREE_TYPE (aligning_field_addr),
+               build_binary_op (MODIFY_EXPR, NULL_TREE,
+                                storage_ptr_slot, storage_ptr),
+               aligning_field_addr);
+    }
+  else
+    return malloc_ptr;
+}
+
+/* Helper for build_call_alloc_dealloc, to release a DATA_TYPE object
+   designated by DATA_PTR using the __gnat_free entry point.  */
+
+static inline tree
+maybe_wrap_free (tree data_ptr, tree data_type)
+{
+  /* In the regular alignment case, we pass the data pointer straight to free.
+     In the superaligned case, we need to retrieve the initial allocator
+     return value, stored in front of the data block at allocation time.  */
+
+  unsigned int data_align = TYPE_ALIGN (data_type);
+  unsigned int default_allocator_alignment
+      = get_target_default_allocator_alignment () * BITS_PER_UNIT;
+
+  tree free_ptr;
+
+  if (data_align > default_allocator_alignment)
+    {
+      /* DATA_FRONT_PTR (void *)
+        = (void *)DATA_PTR - (void *)sizeof (void *))  */
+      tree data_front_ptr
+       = build_binary_op
+         (POINTER_PLUS_EXPR, ptr_void_type_node,
+          convert (ptr_void_type_node, data_ptr),
+          size_int (-(HOST_WIDE_INT) POINTER_SIZE / BITS_PER_UNIT));
+
+      /* FREE_PTR (void *) = *(void **)DATA_FRONT_PTR  */
+      free_ptr
+       = build_unary_op
+         (INDIRECT_REF, NULL_TREE,
+          convert (build_pointer_type (ptr_void_type_node), data_front_ptr));
+    }
+  else
+    free_ptr = data_ptr;
+
+  return build_call_1_expr (free_decl, free_ptr);
+}
+
 /* Build a GCC tree to call an allocation or deallocation function.
    If GNU_OBJ is nonzero, it is an object to deallocate.  Otherwise,
    generate an allocator.
 
-   GNU_SIZE is the size of the object in bytes and ALIGN is the alignment in
-   bits.  GNAT_PROC, if present, is a procedure to call and GNAT_POOL is the
-   storage pool to use.  If not preset, malloc and free will be used except
-   if GNAT_PROC is the "fake" value of -1, in which case we allocate the
-   object dynamically on the stack frame.  */
+   GNU_SIZE is the number of bytes to allocate and GNU_TYPE is the contained
+   object type, used to determine the to-be-honored address alignment.
+   GNAT_PROC, if present, is a procedure to call and GNAT_POOL is the storage
+   pool to use.  If not present, malloc and free are used.  GNAT_NODE is used
+   to provide an error location for restriction violation messages.  */
 
 tree
-build_call_alloc_dealloc (tree gnu_obj, tree gnu_size, unsigned align,
+build_call_alloc_dealloc (tree gnu_obj, tree gnu_size, tree gnu_type,
                           Entity_Id gnat_proc, Entity_Id gnat_pool,
                           Node_Id gnat_node)
 {
-  tree gnu_align = size_int (align / BITS_PER_UNIT);
-
   gnu_size = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_size, gnu_obj);
 
+  /* Explicit proc to call ?  This one is assumed to deal with the type
+     alignment constraints.  */
   if (Present (gnat_proc))
-    {
-      /* The storage pools are obviously always tagged types, but the
-        secondary stack uses the same mechanism and is not tagged */
-      if (Is_Tagged_Type (Etype (gnat_pool)))
-       {
-         /* The size is the third parameter; the alignment is the
-             same type.  */
-         Entity_Id gnat_size_type
-           = Etype (Next_Formal (Next_Formal (First_Formal (gnat_proc))));
-         tree gnu_size_type = gnat_to_gnu_type (gnat_size_type);
-         tree gnu_proc = gnat_to_gnu (gnat_proc);
-         tree gnu_proc_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_proc);
-         tree gnu_pool = gnat_to_gnu (gnat_pool);
-         tree gnu_pool_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_pool);
-         tree gnu_call;
-
-         gnu_size = convert (gnu_size_type, gnu_size);
-         gnu_align = convert (gnu_size_type, gnu_align);
-
-         /* The first arg is always the address of the storage pool; next
-            comes the address of the object, for a deallocator, then the
-            size and alignment.  */
-         if (gnu_obj)
-           gnu_call = build_call_nary (TREE_TYPE (TREE_TYPE (gnu_proc)),
-                                       gnu_proc_addr, 4, gnu_pool_addr,
-                                       gnu_obj, gnu_size, gnu_align);
-         else
-           gnu_call = build_call_nary (TREE_TYPE (TREE_TYPE (gnu_proc)),
-                                       gnu_proc_addr, 3, gnu_pool_addr,
-                                       gnu_size, gnu_align);
-         TREE_SIDE_EFFECTS (gnu_call) = 1;
-         return gnu_call;
-       }
-
-      /* Secondary stack case.  */
-      else
-       {
-         /* The size is the second parameter */
-         Entity_Id gnat_size_type
-           = Etype (Next_Formal (First_Formal (gnat_proc)));
-         tree gnu_size_type = gnat_to_gnu_type (gnat_size_type);
-         tree gnu_proc = gnat_to_gnu (gnat_proc);
-         tree gnu_proc_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_proc);
-         tree gnu_call;
-
-         gnu_size = convert (gnu_size_type, gnu_size);
-
-         /* The first arg is the address of the object, for a
-            deallocator, then the size */
-         if (gnu_obj)
-           gnu_call = build_call_nary (TREE_TYPE (TREE_TYPE (gnu_proc)),
-                                       gnu_proc_addr, 2, gnu_obj, gnu_size);
-         else
-           gnu_call = build_call_nary (TREE_TYPE (TREE_TYPE (gnu_proc)),
-                                       gnu_proc_addr, 1, gnu_size);
-         TREE_SIDE_EFFECTS (gnu_call) = 1;
-         return gnu_call;
-       }
-    }
+    return build_call_alloc_dealloc_proc (gnu_obj, gnu_size, gnu_type,
+                                         gnat_proc, gnat_pool);
 
+  /* Otherwise, object to "free" or "malloc" with possible special processing
+     for alignments stricter than what the default allocator honors.  */
   else if (gnu_obj)
-    return build_call_1_expr (free_decl, gnu_obj);
-
-  /* ??? For now, disable variable-sized allocators in the stack since
-     we can't yet gimplify an ALLOCATE_EXPR.  */
-  else if (gnat_pool == -1
-          && TREE_CODE (gnu_size) == INTEGER_CST
-          && flag_stack_check != GENERIC_STACK_CHECK)
-    {
-      /* If the size is a constant, we can put it in the fixed portion of
-        the stack frame to avoid the need to adjust the stack pointer.  */
-       {
-         tree gnu_index = build_index_2_type (size_one_node, gnu_size);
-         tree gnu_array_type = build_array_type (char_type_node, gnu_index);
-         tree gnu_decl
-           = create_var_decl (get_identifier ("RETVAL"), NULL_TREE,
-                              gnu_array_type, NULL_TREE, false, false, false,
-                              false, NULL, gnat_node);
-         return convert (ptr_void_type_node,
-                         build_unary_op (ADDR_EXPR, NULL_TREE, gnu_decl));
-       }
-#if 0
-      else
-       return build2 (ALLOCATE_EXPR, ptr_void_type_node, gnu_size, gnu_align);
-#endif
-    }
+    return maybe_wrap_free (gnu_obj, gnu_type);
   else
     {
-      if (Nkind (gnat_node) != N_Allocator || !Comes_From_Source (gnat_node))
-        Check_No_Implicit_Heap_Alloc (gnat_node);
-
-      /* If the allocator size is 32bits but the pointer size is 64bits then
-        allocate 32bit memory (sometimes necessary on 64bit VMS). Otherwise
-        default to standard malloc. */
-      if (TARGET_ABI_OPEN_VMS &&
-          (!TARGET_MALLOC64 ||
-           (POINTER_SIZE == 64
-           && (UI_To_Int (Esize (Etype (gnat_node))) == 32
-               || Convention (Etype (gnat_node)) == Convention_C))))
-        return build_call_1_expr (malloc32_decl, gnu_size);
-      else
-        return build_call_1_expr (malloc_decl, gnu_size);
+      /* Assert that we no longer can be called with this special pool.  */
+      gcc_assert (gnat_pool != -1);
+
+      /* Check that we aren't violating the associated restriction.  */
+      if (!(Nkind (gnat_node) == N_Allocator && Comes_From_Source (gnat_node)))
+       Check_No_Implicit_Heap_Alloc (gnat_node);
+
+      return maybe_wrap_malloc (gnu_size, gnu_type, gnat_node);
     }
 }
 \f
 /* Build a GCC tree to correspond to allocating an object of TYPE whose
    initial value is INIT, if INIT is nonzero.  Convert the expression to
    RESULT_TYPE, which must be some type of pointer.  Return the tree.
+
    GNAT_PROC and GNAT_POOL optionally give the procedure to call and
    the storage pool to use.  GNAT_NODE is used to provide an error
-   location for restriction violations messages.  If IGNORE_INIT_TYPE is
+   location for restriction violation messages.  If IGNORE_INIT_TYPE is
    true, ignore the type of INIT for the purpose of determining the size;
    this will cause the maximum size to be allocated if TYPE is of
    self-referential size.  */
@@ -1975,8 +1972,6 @@ build_allocator (tree type, tree init, tree result_type, Entity_Id gnat_proc,
 {
   tree size = TYPE_SIZE_UNIT (type);
   tree result;
-  unsigned int default_allocator_alignment
-    = get_target_default_allocator_alignment () * BITS_PER_UNIT;
 
   /* If the initializer, if present, is a NULL_EXPR, just return a new one.  */
   if (init && TREE_CODE (init) == NULL_EXPR)
@@ -1985,7 +1980,7 @@ build_allocator (tree type, tree init, tree result_type, Entity_Id gnat_proc,
   /* If RESULT_TYPE is a fat or thin pointer, set SIZE to be the sum of the
      sizes of the object and its template.  Allocate the whole thing and
      fill in the parts that are known.  */
-  else if (TYPE_FAT_OR_THIN_POINTER_P (result_type))
+  else if (TYPE_IS_FAT_OR_THIN_POINTER_P (result_type))
     {
       tree storage_type
        = build_unc_object_type_from_ptr (result_type, type,
@@ -2003,15 +1998,13 @@ build_allocator (tree type, tree init, tree result_type, Entity_Id gnat_proc,
       if (TREE_CODE (size) == INTEGER_CST && TREE_OVERFLOW (size))
        size = ssize_int (-1);
 
-      storage = build_call_alloc_dealloc (NULL_TREE, size,
-                                         TYPE_ALIGN (storage_type),
+      storage = build_call_alloc_dealloc (NULL_TREE, size, storage_type,
                                          gnat_proc, gnat_pool, gnat_node);
-      storage = convert (storage_ptr_type, protect_multiple_eval (storage));
+      storage = convert (storage_ptr_type, gnat_protect_expr (storage));
 
-      if (TREE_CODE (type) == RECORD_TYPE && TYPE_IS_PADDING_P (type))
+      if (TYPE_IS_PADDING_P (type))
        {
          type = TREE_TYPE (TYPE_FIELDS (type));
-
          if (init)
            init = convert (type, init);
        }
@@ -2047,7 +2040,7 @@ build_allocator (tree type, tree init, tree result_type, Entity_Id gnat_proc,
            build_component_ref
            (build_unary_op (INDIRECT_REF, NULL_TREE,
                             convert (storage_ptr_type, storage)),
-            NULL_TREE, TYPE_FIELDS (storage_type), 0),
+            NULL_TREE, TYPE_FIELDS (storage_type), false),
            build_template (template_type, type, NULL_TREE)),
           convert (result_type, convert (storage_ptr_type, storage)));
     }
@@ -2076,77 +2069,16 @@ build_allocator (tree type, tree init, tree result_type, Entity_Id gnat_proc,
   if (TREE_CODE (size) == INTEGER_CST && TREE_OVERFLOW (size))
     size = ssize_int (-1);
 
-  /* If this is in the default storage pool and the type alignment is larger
-     than what the default allocator supports, make an "aligning" record type
-     with room to store a pointer before the field, allocate an object of that
-     type, store the system's allocator return value just in front of the
-     field and return the field's address.  */
-
-  if (No (gnat_proc) && TYPE_ALIGN (type) > default_allocator_alignment)
-    {
-      /* Construct the aligning type with enough room for a pointer ahead
-        of the field, then allocate.  */
-      tree record_type
-       = make_aligning_type (type, TYPE_ALIGN (type), size,
-                             default_allocator_alignment,
-                             POINTER_SIZE / BITS_PER_UNIT);
-
-      tree record, record_addr;
-
-      record_addr
-       = build_call_alloc_dealloc (NULL_TREE, TYPE_SIZE_UNIT (record_type),
-                                   default_allocator_alignment, Empty, Empty,
-                                   gnat_node);
-
-      record_addr
-       = convert (build_pointer_type (record_type),
-                  save_expr (record_addr));
-
-      record = build_unary_op (INDIRECT_REF, NULL_TREE, record_addr);
-
-      /* Our RESULT (the Ada allocator's value) is the super-aligned address
-        of the internal record field ... */
-      result
-       = build_unary_op (ADDR_EXPR, NULL_TREE,
-                         build_component_ref
-                         (record, NULL_TREE, TYPE_FIELDS (record_type), 0));
-      result = convert (result_type, result);
-
-      /* ... with the system allocator's return value stored just in
-        front.  */
-      {
-       tree ptr_addr
-         = build_binary_op (POINTER_PLUS_EXPR, ptr_void_type_node,
-                            convert (ptr_void_type_node, result),
-                            size_int (-POINTER_SIZE/BITS_PER_UNIT));
-
-       tree ptr_ref
-         = convert (build_pointer_type (ptr_void_type_node), ptr_addr);
-
-       result
-         = build2 (COMPOUND_EXPR, TREE_TYPE (result),
-                   build_binary_op (MODIFY_EXPR, NULL_TREE,
-                                    build_unary_op (INDIRECT_REF, NULL_TREE,
-                                                    ptr_ref),
-                                    convert (ptr_void_type_node,
-                                             record_addr)),
-                   result);
-      }
-    }
-  else
-    result = convert (result_type,
-                     build_call_alloc_dealloc (NULL_TREE, size,
-                                               TYPE_ALIGN (type),
-                                               gnat_proc,
-                                               gnat_pool,
-                                               gnat_node));
-
-  /* If we have an initial value, put the new address into a SAVE_EXPR, assign
-     the value, and return the address.  Do this with a COMPOUND_EXPR.  */
+  result = convert (result_type,
+                   build_call_alloc_dealloc (NULL_TREE, size, type,
+                                             gnat_proc, gnat_pool,
+                                             gnat_node));
 
+  /* If we have an initial value, protect the new address, assign the value
+     and return the address with a COMPOUND_EXPR.  */
   if (init)
     {
-      result = save_expr (result);
+      result = gnat_protect_expr (result);
       result
        = build2 (COMPOUND_EXPR, TREE_TYPE (result),
                  build_binary_op
@@ -2168,12 +2100,11 @@ build_allocator (tree type, tree init, tree result_type, Entity_Id gnat_proc,
 tree
 fill_vms_descriptor (tree expr, Entity_Id gnat_formal, Node_Id gnat_actual)
 {
-  tree field;
   tree parm_decl = get_gnu_tree (gnat_formal);
-  tree const_list = NULL_TREE;
   tree record_type = TREE_TYPE (TREE_TYPE (parm_decl));
-  int do_range_check =
-      strcmp ("MBO",
+  tree const_list = NULL_TREE, field;
+  const bool do_range_check
+    = strcmp ("MBO",
              IDENTIFIER_POINTER (DECL_NAME (TYPE_FIELDS (record_type))));
 
   expr = maybe_unconstrained_array (expr);
@@ -2185,23 +2116,24 @@ fill_vms_descriptor (tree expr, Entity_Id gnat_formal, Node_Id gnat_actual)
                              SUBSTITUTE_PLACEHOLDER_IN_EXPR
                              (DECL_INITIAL (field), expr));
 
-      /* Check to ensure that only 32bit pointers are passed in
-        32bit descriptors */
-      if (do_range_check &&
-          strcmp (IDENTIFIER_POINTER (DECL_NAME (field)), "POINTER") == 0)
+      /* Check to ensure that only 32-bit pointers are passed in
+        32-bit descriptors */
+      if (do_range_check
+          && strcmp (IDENTIFIER_POINTER (DECL_NAME (field)), "POINTER") == 0)
         {
-         tree pointer64type =
-            build_pointer_type_for_mode (void_type_node, DImode, false);
+         tree pointer64type
+           = build_pointer_type_for_mode (void_type_node, DImode, false);
          tree addr64expr = build_unary_op (ADDR_EXPR, pointer64type, expr);
-         tree malloc64low =
-            build_int_cstu (long_integer_type_node, 0x80000000);
+         tree malloc64low
+           = build_int_cstu (long_integer_type_node, 0x80000000);
 
          add_stmt (build3 (COND_EXPR, void_type_node,
-                           build_binary_op (GE_EXPR, long_integer_type_node,
+                           build_binary_op (GE_EXPR, boolean_type_node,
                                             convert (long_integer_type_node,
                                                      addr64expr),
                                             malloc64low),
-                           build_call_raise (CE_Range_Check_Failed, gnat_actual,
+                           build_call_raise (CE_Range_Check_Failed,
+                                             gnat_actual,
                                              N_Raise_Constraint_Error),
                            NULL_TREE));
         }
@@ -2211,14 +2143,14 @@ fill_vms_descriptor (tree expr, Entity_Id gnat_formal, Node_Id gnat_actual)
   return gnat_build_constructor (record_type, nreverse (const_list));
 }
 
-/* Indicate that we need to make the address of EXPR_NODE and it therefore
+/* Indicate that we need to take the address of T and that it therefore
    should not be allocated in a register.  Returns true if successful.  */
 
 bool
-gnat_mark_addressable (tree expr_node)
+gnat_mark_addressable (tree t)
 {
-  while (1)
-    switch (TREE_CODE (expr_node))
+  while (true)
+    switch (TREE_CODE (t))
       {
       case ADDR_EXPR:
       case COMPONENT_REF:
@@ -2229,28 +2161,332 @@ gnat_mark_addressable (tree expr_node)
       case VIEW_CONVERT_EXPR:
       case NON_LVALUE_EXPR:
       CASE_CONVERT:
-       expr_node = TREE_OPERAND (expr_node, 0);
+       t = TREE_OPERAND (t, 0);
+       break;
+
+      case COMPOUND_EXPR:
+       t = TREE_OPERAND (t, 1);
        break;
 
       case CONSTRUCTOR:
-       TREE_ADDRESSABLE (expr_node) = 1;
+       TREE_ADDRESSABLE (t) = 1;
        return true;
 
       case VAR_DECL:
       case PARM_DECL:
       case RESULT_DECL:
-       TREE_ADDRESSABLE (expr_node) = 1;
+       TREE_ADDRESSABLE (t) = 1;
        return true;
 
       case FUNCTION_DECL:
-       TREE_ADDRESSABLE (expr_node) = 1;
+       TREE_ADDRESSABLE (t) = 1;
        return true;
 
       case CONST_DECL:
-       return (DECL_CONST_CORRESPONDING_VAR (expr_node)
-               && (gnat_mark_addressable
-                   (DECL_CONST_CORRESPONDING_VAR (expr_node))));
+       return DECL_CONST_CORRESPONDING_VAR (t)
+              && gnat_mark_addressable (DECL_CONST_CORRESPONDING_VAR (t));
+
       default:
        return true;
     }
 }
+\f
+/* Save EXP for later use or reuse.  This is equivalent to save_expr in tree.c
+   but we know how to handle our own nodes.  */
+
+tree
+gnat_save_expr (tree exp)
+{
+  tree type = TREE_TYPE (exp);
+  enum tree_code code = TREE_CODE (exp);
+
+  if (TREE_CONSTANT (exp) || code == SAVE_EXPR || code == NULL_EXPR)
+    return exp;
+
+  if (code == UNCONSTRAINED_ARRAY_REF)
+    {
+      tree t = build1 (code, type, gnat_save_expr (TREE_OPERAND (exp, 0)));
+      TREE_READONLY (t) = TYPE_READONLY (type);
+      return t;
+    }
+
+  /* If this is a COMPONENT_REF of a fat pointer, save the entire fat pointer.
+     This may be more efficient, but will also allow us to more easily find
+     the match for the PLACEHOLDER_EXPR.  */
+  if (code == COMPONENT_REF
+      && TYPE_IS_FAT_POINTER_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
+    return build3 (code, type, gnat_save_expr (TREE_OPERAND (exp, 0)),
+                  TREE_OPERAND (exp, 1), TREE_OPERAND (exp, 2));
+
+  return save_expr (exp);
+}
+
+/* Protect EXP for immediate reuse.  This is a variant of gnat_save_expr that
+   is optimized under the assumption that EXP's value doesn't change before
+   its subsequent reuse(s) except through its potential reevaluation.  */
+
+tree
+gnat_protect_expr (tree exp)
+{
+  tree type = TREE_TYPE (exp);
+  enum tree_code code = TREE_CODE (exp);
+
+  if (TREE_CONSTANT (exp) || code == SAVE_EXPR || code == NULL_EXPR)
+    return exp;
+
+  /* If EXP has no side effects, we theoritically don't need to do anything.
+     However, we may be recursively passed more and more complex expressions
+     involving checks which will be reused multiple times and eventually be
+     unshared for gimplification; in order to avoid a complexity explosion
+     at that point, we protect any expressions more complex than a simple
+     arithmetic expression.  */
+  if (!TREE_SIDE_EFFECTS (exp))
+    {
+      tree inner = skip_simple_arithmetic (exp);
+      if (!EXPR_P (inner) || REFERENCE_CLASS_P (inner))
+       return exp;
+    }
+
+  /* If this is a conversion, protect what's inside the conversion.  */
+  if (code == NON_LVALUE_EXPR
+      || CONVERT_EXPR_CODE_P (code)
+      || code == VIEW_CONVERT_EXPR)
+  return build1 (code, type, gnat_protect_expr (TREE_OPERAND (exp, 0)));
+
+  /* If we're indirectly referencing something, we only need to protect the
+     address since the data itself can't change in these situations.  */
+  if (code == INDIRECT_REF || code == UNCONSTRAINED_ARRAY_REF)
+    {
+      tree t = build1 (code, type, gnat_protect_expr (TREE_OPERAND (exp, 0)));
+      TREE_READONLY (t) = TYPE_READONLY (type);
+      return t;
+    }
+
+  /* If this is a COMPONENT_REF of a fat pointer, save the entire fat pointer.
+     This may be more efficient, but will also allow us to more easily find
+     the match for the PLACEHOLDER_EXPR.  */
+  if (code == COMPONENT_REF
+      && TYPE_IS_FAT_POINTER_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
+    return build3 (code, type, gnat_protect_expr (TREE_OPERAND (exp, 0)),
+                  TREE_OPERAND (exp, 1), TREE_OPERAND (exp, 2));
+
+  /* If this is a fat pointer or something that can be placed in a register,
+     just make a SAVE_EXPR.  Likewise for a CALL_EXPR as large objects are
+     returned via invisible reference in most ABIs so the temporary will
+     directly be filled by the callee.  */
+  if (TYPE_IS_FAT_POINTER_P (type)
+      || TYPE_MODE (type) != BLKmode
+      || code == CALL_EXPR)
+    return save_expr (exp);
+
+  /* Otherwise reference, protect the address and dereference.  */
+  return
+    build_unary_op (INDIRECT_REF, type,
+                   save_expr (build_unary_op (ADDR_EXPR,
+                                              build_reference_type (type),
+                                              exp)));
+}
+
+/* This is equivalent to stabilize_reference_1 in tree.c but we take an extra
+   argument to force evaluation of everything.  */
+
+static tree
+gnat_stabilize_reference_1 (tree e, bool force)
+{
+  enum tree_code code = TREE_CODE (e);
+  tree type = TREE_TYPE (e);
+  tree result;
+
+  /* We cannot ignore const expressions because it might be a reference
+     to a const array but whose index contains side-effects.  But we can
+     ignore things that are actual constant or that already have been
+     handled by this function.  */
+  if (TREE_CONSTANT (e) || code == SAVE_EXPR)
+    return e;
+
+  switch (TREE_CODE_CLASS (code))
+    {
+    case tcc_exceptional:
+    case tcc_declaration:
+    case tcc_comparison:
+    case tcc_expression:
+    case tcc_reference:
+    case tcc_vl_exp:
+      /* If this is a COMPONENT_REF of a fat pointer, save the entire
+        fat pointer.  This may be more efficient, but will also allow
+        us to more easily find the match for the PLACEHOLDER_EXPR.  */
+      if (code == COMPONENT_REF
+         && TYPE_IS_FAT_POINTER_P (TREE_TYPE (TREE_OPERAND (e, 0))))
+       result
+         = build3 (code, type,
+                   gnat_stabilize_reference_1 (TREE_OPERAND (e, 0), force),
+                   TREE_OPERAND (e, 1), TREE_OPERAND (e, 2));
+      /* If the expression has side-effects, then encase it in a SAVE_EXPR
+        so that it will only be evaluated once.  */
+      /* The tcc_reference and tcc_comparison classes could be handled as
+        below, but it is generally faster to only evaluate them once.  */
+      else if (TREE_SIDE_EFFECTS (e) || force)
+       return save_expr (e);
+      else
+       return e;
+      break;
+
+    case tcc_binary:
+      /* Recursively stabilize each operand.  */
+      result
+       = build2 (code, type,
+                 gnat_stabilize_reference_1 (TREE_OPERAND (e, 0), force),
+                 gnat_stabilize_reference_1 (TREE_OPERAND (e, 1), force));
+      break;
+
+    case tcc_unary:
+      /* Recursively stabilize each operand.  */
+      result
+       = build1 (code, type,
+                 gnat_stabilize_reference_1 (TREE_OPERAND (e, 0), force));
+      break;
+
+    default:
+      gcc_unreachable ();
+    }
+
+  /* See similar handling in gnat_stabilize_reference.  */
+  TREE_READONLY (result) = TREE_READONLY (e);
+  TREE_SIDE_EFFECTS (result) |= TREE_SIDE_EFFECTS (e);
+  TREE_THIS_VOLATILE (result) = TREE_THIS_VOLATILE (e);
+
+  return result;
+}
+
+/* This is equivalent to stabilize_reference in tree.c but we know how to
+   handle our own nodes and we take extra arguments.  FORCE says whether to
+   force evaluation of everything.  We set SUCCESS to true unless we walk
+   through something we don't know how to stabilize.  */
+
+tree
+gnat_stabilize_reference (tree ref, bool force, bool *success)
+{
+  tree type = TREE_TYPE (ref);
+  enum tree_code code = TREE_CODE (ref);
+  tree result;
+
+  /* Assume we'll success unless proven otherwise.  */
+  if (success)
+    *success = true;
+
+  switch (code)
+    {
+    case CONST_DECL:
+    case VAR_DECL:
+    case PARM_DECL:
+    case RESULT_DECL:
+      /* No action is needed in this case.  */
+      return ref;
+
+    case ADDR_EXPR:
+    CASE_CONVERT:
+    case FLOAT_EXPR:
+    case FIX_TRUNC_EXPR:
+    case VIEW_CONVERT_EXPR:
+      result
+       = build1 (code, type,
+                 gnat_stabilize_reference (TREE_OPERAND (ref, 0), force,
+                                           success));
+      break;
+
+    case INDIRECT_REF:
+    case UNCONSTRAINED_ARRAY_REF:
+      result = build1 (code, type,
+                      gnat_stabilize_reference_1 (TREE_OPERAND (ref, 0),
+                                                  force));
+      break;
+
+    case COMPONENT_REF:
+     result = build3 (COMPONENT_REF, type,
+                     gnat_stabilize_reference (TREE_OPERAND (ref, 0), force,
+                                               success),
+                     TREE_OPERAND (ref, 1), NULL_TREE);
+      break;
+
+    case BIT_FIELD_REF:
+      result = build3 (BIT_FIELD_REF, type,
+                      gnat_stabilize_reference (TREE_OPERAND (ref, 0), force,
+                                                success),
+                      gnat_stabilize_reference_1 (TREE_OPERAND (ref, 1),
+                                                  force),
+                      gnat_stabilize_reference_1 (TREE_OPERAND (ref, 2),
+                                                  force));
+      break;
+
+    case ARRAY_REF:
+    case ARRAY_RANGE_REF:
+      result = build4 (code, type,
+                      gnat_stabilize_reference (TREE_OPERAND (ref, 0), force,
+                                                success),
+                      gnat_stabilize_reference_1 (TREE_OPERAND (ref, 1),
+                                                  force),
+                      NULL_TREE, NULL_TREE);
+      break;
+
+    case CALL_EXPR:
+      result = gnat_stabilize_reference_1 (ref, force);
+      break;
+
+    case COMPOUND_EXPR:
+      result = build2 (COMPOUND_EXPR, type,
+                      gnat_stabilize_reference (TREE_OPERAND (ref, 0), force,
+                                                success),
+                      gnat_stabilize_reference_1 (TREE_OPERAND (ref, 1),
+                                                  force));
+      break;
+
+    case CONSTRUCTOR:
+      /* Constructors with 1 element are used extensively to formally
+        convert objects to special wrapping types.  */
+      if (TREE_CODE (type) == RECORD_TYPE
+         && VEC_length (constructor_elt, CONSTRUCTOR_ELTS (ref)) == 1)
+       {
+         tree index
+           = VEC_index (constructor_elt, CONSTRUCTOR_ELTS (ref), 0)->index;
+         tree value
+           = VEC_index (constructor_elt, CONSTRUCTOR_ELTS (ref), 0)->value;
+         result
+           = build_constructor_single (type, index,
+                                       gnat_stabilize_reference_1 (value,
+                                                                   force));
+       }
+      else
+       {
+         if (success)
+           *success = false;
+         return ref;
+       }
+      break;
+
+    case ERROR_MARK:
+      ref = error_mark_node;
+
+      /* ...  fall through to failure ... */
+
+      /* If arg isn't a kind of lvalue we recognize, make no change.
+        Caller should recognize the error for an invalid lvalue.  */
+    default:
+      if (success)
+       *success = false;
+      return ref;
+    }
+
+  /* TREE_THIS_VOLATILE and TREE_SIDE_EFFECTS set on the initial expression
+     may not be sustained across some paths, such as the way via build1 for
+     INDIRECT_REF.  We reset those flags here in the general case, which is
+     consistent with the GCC version of this routine.
+
+     Special care should be taken regarding TREE_SIDE_EFFECTS, because some
+     paths introduce side-effects where there was none initially (e.g. if a
+     SAVE_EXPR is built) and we also want to keep track of that.  */
+  TREE_READONLY (result) = TREE_READONLY (ref);
+  TREE_SIDE_EFFECTS (result) |= TREE_SIDE_EFFECTS (ref);
+  TREE_THIS_VOLATILE (result) = TREE_THIS_VOLATILE (ref);
+
+  return result;
+}