Index: lib/Transforms/Scalar/SROA.cpp
===================================================================
--- lib/Transforms/Scalar/SROA.cpp	(revision 182880)
+++ lib/Transforms/Scalar/SROA.cpp	(working copy)
@@ -1869,6 +1869,18 @@
                                   Indices);
 }
 
+// Check that we're not adding a bit-cast between address spaces.
+static Value *makeBitCast(IRBuilderTy &IRB, Value *V, Type *Ty, const Twine &Name = "")
+{
+  if( V->getType()->isPointerTy() && Ty->isPointerTy() ) {
+    unsigned VAS = V->getType()->getPointerAddressSpace();
+    unsigned TyAS = Ty->getPointerAddressSpace();
+    assert( VAS == TyAS && "Pointer address spaces do not match!");
+  }
+  return IRB.CreateBitCast(V, Ty, Name);
+}
+
+
 /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
 /// resulting pointer has PointerTy.
 ///
@@ -1953,8 +1965,9 @@
 
   if (!OffsetPtr) {
     if (!Int8Ptr) {
-      Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
-                                  "raw_cast");
+      unsigned PtrAS = Ptr->getType()->getPointerAddressSpace();
+      Int8Ptr = makeBitCast(IRB, Ptr, IRB.getInt8PtrTy(PtrAS),
+                                 "raw_cast");
       Int8PtrOffset = Offset;
     }
 
@@ -1966,7 +1979,7 @@
 
   // On the off chance we were targeting i8*, guard the bitcast here.
   if (Ptr->getType() != PointerTy)
-    Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
+    Ptr = makeBitCast(IRB, Ptr, PointerTy, "cast");
 
   return Ptr;
 }
@@ -2021,7 +2034,7 @@
   if (V->getType()->isPointerTy() && Ty->isIntegerTy())
     return IRB.CreatePtrToInt(V, Ty);
 
-  return IRB.CreateBitCast(V, Ty);
+  return makeBitCast(IRB, V, Ty);
 }
 
 /// \brief Test whether the given alloca partition can be promoted to a vector.
@@ -2907,6 +2920,7 @@
     // Strip all inbounds GEPs and pointer casts to try to dig out any root
     // alloca that should be re-examined after rewriting this instruction.
     Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
+    unsigned OtherAS = OtherPtr->getType()->getPointerAddressSpace();
     if (AllocaInst *AI
           = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
       Pass.Worklist.insert(AI);
@@ -2960,6 +2974,9 @@
       OtherPtrTy = SubIntTy->getPointerTo();
     }
 
+    // Fix OtherPtrTy to be in OtherAS address space.
+    OtherPtrTy = OtherPtrTy->getPointerElementType()->getPointerTo(OtherAS);
+
     Value *SrcPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy);
     Value *DstPtr = &NewAI;
     if (!IsDest)
