[PATCH] C++ fix for char/wchar array initialized with string

Jakub Jelinek jakub@redhat.com
Mon Jun 5 08:10:00 GMT 2000


Hi!

Here is a repost of a 2 days old testsuite with a fix.
Basically, C++ calls indirectly complete_array_type if the size of the array
is not explicitely given, but this computation did not take into account the
special case where a char/uchar/wchar array is initialized with an
initializer like { "bar" };
Ok to commit (provided bootstrap succeeds)?

2000-06-05  Jakub Jelinek  <jakub@redhat.com>

	* decl.c (complete_array_type): Compute array size correctly
	if initializing with string a char/wchar array.

	* g++.old-deja/g++.other/initstring.C: New test.

--- gcc/testsuite/g++.old-deja/g++.other/initstring.C.jj	Sat Jun  3 09:13:37 2000
+++ gcc/testsuite/g++.old-deja/g++.other/initstring.C	Sat Jun  3 09:14:39 2000
@@ -0,0 +1,3 @@
+// Build don't link:
+
+static const char foo[] = { "bar" };
--- gcc/cp/decl.c.jj	Thu Jun  1 11:56:54 2000
+++ gcc/cp/decl.c	Mon Jun  5 16:50:58 2000
@@ -8669,16 +8669,45 @@ complete_array_type (type, initial_value
       else if (TREE_CODE (initial_value) == CONSTRUCTOR)
 	{
 	  tree elts = CONSTRUCTOR_ELTS (initial_value);
+	  tree element = NULL_TREE;
 
-	  maxindex = ssize_int (-1);
-	  for (; elts; elts = TREE_CHAIN (elts))
+	  if (elts && ! TREE_CHAIN (elts))
 	    {
-	      if (TREE_PURPOSE (elts))
-		maxindex = TREE_PURPOSE (elts);
-	      else
-		maxindex = size_binop (PLUS_EXPR, maxindex, ssize_int (1));
+	      element = TREE_VALUE (elts);
+	      /* Strip NON_LVALUE_EXPRs since we aren't using as an lvalue.  */
+	      if (element && TREE_CODE (element) == NON_LVALUE_EXPR)
+		element = TREE_OPERAND (element, 0);
+	      if (element == error_mark_node)
+		element = NULL_TREE;
+	    }
+	  if (element && TREE_CODE (element) == STRING_CST)
+	    {
+	      tree typ1 = TYPE_MAIN_VARIANT (TREE_TYPE (type));
+	      if (typ1 == char_type_node
+		  || typ1 == signed_char_type_node
+		  || typ1 == unsigned_char_type_node
+		  || typ1 == unsigned_wchar_type_node
+		  || typ1 == signed_wchar_type_node)
+		{
+		  int eltsize =
+		    int_size_in_bytes (TREE_TYPE (TREE_TYPE (element)));
+		  maxindex = build_int_2 ((TREE_STRING_LENGTH (element)
+					   / eltsize) - 1, 0);
+		}
+	    }
+	  if (maxindex == NULL_TREE)
+	    {
+	      maxindex = ssize_int (-1);
+	      for (; elts; elts = TREE_CHAIN (elts))
+		{
+		  if (TREE_PURPOSE (elts))
+		    maxindex = TREE_PURPOSE (elts);
+		  else
+		    maxindex = size_binop (PLUS_EXPR, maxindex,
+					   ssize_int (1));
+		}
+	      maxindex = copy_node (maxindex);
 	    }
-	  maxindex = copy_node (maxindex);
 	}
       else
 	{

	Jakub


More information about the Gcc-patches mailing list