diff --git a/gcc/ChangeLog b/gcc/ChangeLog
index 80a3571bc3685407d49176111c350d03617443f1..68ee5888aedbe1c08d2b7eda950f0d146330f7fa 100644
--- a/gcc/ChangeLog
+++ b/gcc/ChangeLog
@@ -1,3 +1,9 @@
+2006-05-15  Jakub Jelinek  <jakub@redhat.com>
+
+	PR middle-end/27416
+	* omp-low.c (build_outer_var_ref): If VAR is reference in orphaned
+	construct, return *VAR.
+
 2006-05-14  Kaz Kojima  <kkojima@gcc.gnu.org>
 
 	PR rtl-optimization/27406
diff --git a/gcc/omp-low.c b/gcc/omp-low.c
index 2de13eccdec4f31fc2c968f358e756ad5e3e6b7c..c6d186bee71507cd81867541436ff9622b72320b 100644
--- a/gcc/omp-low.c
+++ b/gcc/omp-low.c
@@ -577,6 +577,10 @@ build_outer_var_ref (tree var, omp_context *ctx)
     }
   else if (ctx->outer)
     x = lookup_decl (var, ctx->outer);
+  else if (is_reference (var))
+    /* This can happen with orphaned constructs.  If var is reference, it is
+       possible it is shared and as such valid.  */
+    x = var;
   else
     gcc_unreachable ();
 
diff --git a/libgomp/ChangeLog b/libgomp/ChangeLog
index d04194cd4a65529bab3165f36b7330e634d24307..3cf357ed1b6e886423cc129451dbf6b468fc220e 100644
--- a/libgomp/ChangeLog
+++ b/libgomp/ChangeLog
@@ -1,3 +1,8 @@
+2006-05-15  Jakub Jelinek  <jakub@redhat.com>
+
+	PR middle-end/27416
+	* libgomp.fortran/pr27416-1.f90: New test.
+
 2006-05-03  Jakub Jelinek  <jakub@redhat.com>
 
 	PR fortran/27395
diff --git a/libgomp/testsuite/libgomp.fortran/pr27416-1.f90 b/libgomp/testsuite/libgomp.fortran/pr27416-1.f90
new file mode 100644
index 0000000000000000000000000000000000000000..d42e1ef19ab564c623763bf4b146925eb09ba138
--- /dev/null
+++ b/libgomp/testsuite/libgomp.fortran/pr27416-1.f90
@@ -0,0 +1,19 @@
+! PR middle-end/27416
+! { dg-do run }
+
+  integer :: j
+  j = 6
+!$omp parallel num_threads (4)
+  call foo (j)
+!$omp end parallel
+  if (j.ne.6+16) call abort
+end
+
+subroutine foo (j)
+  integer :: i, j
+
+!$omp do firstprivate (j) lastprivate (j)
+  do i = 1, 16
+    if (i.eq.16) j = j + i
+  end do
+end subroutine foo