diff --git a/gcc/ChangeLog b/gcc/ChangeLog
index 1a3b594ee42b..9e2e4b92609e 100644
--- a/gcc/ChangeLog
+++ b/gcc/ChangeLog
@@ -1,3 +1,9 @@
+2009-05-13  Jakub Jelinek  <jakub@redhat.com>
+	    Ben Elliston <bje@au.ibm.com>
+
+	PR middle-end/40035
+	* dse.c (check_mem_read_rtx): Guard against width == -1.
+
 2009-05-13  Michael Matz  <matz@suse.de>
 
 	PR middle-end/39976
diff --git a/gcc/dse.c b/gcc/dse.c
index 5ac898ca84a7..534324d0f5b1 100644
--- a/gcc/dse.c
+++ b/gcc/dse.c
@@ -2245,6 +2245,7 @@ check_mem_read_rtx (rtx *loc, void *data)
 	  if (store_info->rhs
 	      && store_info->group_id == -1
 	      && store_info->cse_base == base
+	      && width != -1
 	      && offset >= store_info->begin
 	      && offset + width <= store_info->end
 	      && all_positions_needed_p (store_info,
diff --git a/gcc/testsuite/ChangeLog b/gcc/testsuite/ChangeLog
index acf6ca7ebf41..928c7f63a823 100644
--- a/gcc/testsuite/ChangeLog
+++ b/gcc/testsuite/ChangeLog
@@ -1,3 +1,8 @@
+2009-05-14  Ben Elliston  <bje@au.ibm.com>
+	 
+	PR middle-end/40035
+	* gcc.c-torture/compile/pr40035.c: New test.
+
 2009-05-13  Kaveh R. Ghazi  <ghazi@caip.rutgers.edu>
 
 	* gcc.target/i386/pr39543-2.c: Skip if ilp32 && pic.
@@ -9,7 +14,6 @@
 	* gfortran.dg/c_kind_tests_2.f03: Ditto.
 	* gfortran.dg/interop_params.f03: Ditto.
 
-
 2009-05-12  Jan Hubicka  <jh@suse.cz>
 
 	* gcc.dg/tree-ssa/loop-36.c: Reduce amount of iterations to 2 so unrolling
diff --git a/gcc/testsuite/gcc.c-torture/compile/pr40035.c b/gcc/testsuite/gcc.c-torture/compile/pr40035.c
new file mode 100644
index 000000000000..1bf1a7c4c418
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/pr40035.c
@@ -0,0 +1,20 @@
+typedef __SIZE_TYPE__ size_t;
+void *memmove (void *dest, const void *src, size_t count);
+size_t strlen (const char *s);
+
+int
+foo (char *param, char *val)
+{
+  if (val)
+    {
+      if (val == param + strlen (param) + 1)
+        val[-1] = '=';
+      else if (val == param + strlen (param) + 2)
+        {
+          val[-2] = '=';
+          memmove (val - 1, val, strlen (val) + 1);
+          val--;
+        }
+    }
+  return 0;
+}