Remove deferred clear from SkGpuDevice

Add combining to GrClearBatch

Fix issue with state tracking in GrGLGpu::createTestingOnlyBackendTexture

Add tests for clearing GPU SkSurfaces and add tests for GrDrawContext::clear().

Add comment that SkCanvas::flush will resolve the RT in the GPU case.

BUG=skia:
GOLD_TRYBOT_URL= https://gold.skia.org/search2?unt=true&query=source_type%3Dgm&master=false&issue=1658823002

Review URL: https://codereview.chromium.org/1658823002
diff --git a/gm/imagefromyuvtextures.cpp b/gm/imagefromyuvtextures.cpp
index 28d2cf8..c53df29 100644
--- a/gm/imagefromyuvtextures.cpp
+++ b/gm/imagefromyuvtextures.cpp
@@ -94,7 +94,7 @@
     }
 
     void createYUVTextures(GrContext* context, GrBackendObject yuvHandles[3]) {
-        const GrGpu* gpu = context->getGpu();
+        GrGpu* gpu = context->getGpu();
         if (!gpu) {
             return;
         }
@@ -111,7 +111,7 @@
 
     void deleteYUVTextures(GrContext* context, const GrBackendObject yuvHandles[3]) {
 
-        const GrGpu* gpu = context->getGpu();
+        GrGpu* gpu = context->getGpu();
         if (!gpu) {
             return;
         }
diff --git a/include/core/SkCanvas.h b/include/core/SkCanvas.h
index 4ad915c..0df5d0b 100644
--- a/include/core/SkCanvas.h
+++ b/include/core/SkCanvas.h
@@ -124,7 +124,9 @@
     ///////////////////////////////////////////////////////////////////////////
 
     /**
-     *  Trigger the immediate execution of all pending draw operations.
+     *  Trigger the immediate execution of all pending draw operations. For the GPU
+     *  backend this will resolve all rendering to the GPU surface backing the
+     *  SkSurface that owns this canvas.
      */
     void flush();
 
diff --git a/src/gpu/GrGpu.h b/src/gpu/GrGpu.h
index 2140349..27a97e3 100644
--- a/src/gpu/GrGpu.h
+++ b/src/gpu/GrGpu.h
@@ -412,14 +412,14 @@
         only to be used for testing (particularly for testing the methods that import an externally
         created texture into Skia. Must be matched with a call to deleteTestingOnlyTexture(). */
     virtual GrBackendObject createTestingOnlyBackendTexture(void* pixels, int w, int h,
-                                                            GrPixelConfig config) const = 0;
+                                                            GrPixelConfig config) = 0;
     /** Check a handle represents an actual texture in the backend API that has not been freed. */
     virtual bool isTestingOnlyBackendTexture(GrBackendObject) const = 0;
     /** If ownership of the backend texture has been transferred pass true for abandonTexture. This
         will do any necessary cleanup of the handle without freeing the texture in the backend
         API. */
     virtual void deleteTestingOnlyBackendTexture(GrBackendObject,
-                                                 bool abandonTexture = false) const = 0;
+                                                 bool abandonTexture = false) = 0;
 
     // width and height may be larger than rt (if underlying API allows it).
     // Returns nullptr if compatible sb could not be created, otherwise the caller owns the ref on
diff --git a/src/gpu/GrTest.cpp b/src/gpu/GrTest.cpp
index 88e154c..257eefd 100644
--- a/src/gpu/GrTest.cpp
+++ b/src/gpu/GrTest.cpp
@@ -384,11 +384,11 @@
     void clearStencil(GrRenderTarget* target) override  {}
 
     GrBackendObject createTestingOnlyBackendTexture(void* pixels, int w, int h,
-                                                    GrPixelConfig config) const override {
+                                                    GrPixelConfig config) override {
         return 0;
     }
     bool isTestingOnlyBackendTexture(GrBackendObject ) const override { return false; }
-    void deleteTestingOnlyBackendTexture(GrBackendObject, bool abandonTexture) const override {}
+    void deleteTestingOnlyBackendTexture(GrBackendObject, bool abandonTexture) override {}
 
     typedef GrGpu INHERITED;
 };
diff --git a/src/gpu/SkGpuDevice.cpp b/src/gpu/SkGpuDevice.cpp
index 4fdd4ae..10c41d8 100644
--- a/src/gpu/SkGpuDevice.cpp
+++ b/src/gpu/SkGpuDevice.cpp
@@ -66,13 +66,6 @@
     #define CHECK_SHOULD_DRAW(draw) this->prepareDraw(draw)
 #endif
 
-#define DO_DEFERRED_CLEAR()             \
-    do {                                \
-        if (fNeedClear) {               \
-            this->clearAll();           \
-        }                               \
-    } while (false)                     \
-
 ///////////////////////////////////////////////////////////////////////////////
 
 #define CHECK_FOR_ANNOTATION(paint) \
@@ -175,7 +168,6 @@
     : INHERITED(SkSurfacePropsCopyOrDefault(props))
     , fContext(SkRef(rt->getContext()))
     , fRenderTarget(SkRef(rt)) {
-    fNeedClear = SkToBool(flags & kNeedClear_Flag);
     fOpaque = SkToBool(flags & kIsOpaque_Flag);
 
     SkAlphaType at = fOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType;
@@ -185,6 +177,9 @@
     fLegacyBitmap.setPixelRef(pr)->unref();
 
     fDrawContext.reset(this->context()->drawContext(rt, &this->surfaceProps()));
+    if (flags & kNeedClear_Flag) {
+        this->clearAll();
+    }
 }
 
 GrRenderTarget* SkGpuDevice::CreateRenderTarget(GrContext* context, SkSurface::Budgeted budgeted,
@@ -231,7 +226,6 @@
 bool SkGpuDevice::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
                                int x, int y) {
     ASSERT_SINGLE_OWNER
-    DO_DEFERRED_CLEAR();
 
     // TODO: teach fRenderTarget to take ImageInfo directly to specify the src pixels
     GrPixelConfig config = SkImageInfo2GrPixelConfig(dstInfo);
@@ -269,13 +263,11 @@
 
 const SkBitmap& SkGpuDevice::onAccessBitmap() {
     ASSERT_SINGLE_OWNER
-    DO_DEFERRED_CLEAR();
     return fLegacyBitmap;
 }
 
 bool SkGpuDevice::onAccessPixels(SkPixmap* pmap) {
     ASSERT_SINGLE_OWNER
-    DO_DEFERRED_CLEAR();
     // For compatibility with clients the know we're backed w/ a bitmap, and want to inspect its
     // genID. When we can hide/remove that fact, we can eliminate this call to notify.
     // ... ugh.
@@ -307,13 +299,10 @@
     SkASSERT(draw.fClipStack && draw.fClipStack == fClipStack);
 
     fClip.setClipStack(fClipStack, &this->getOrigin());
-
-    DO_DEFERRED_CLEAR();
 }
 
 GrRenderTarget* SkGpuDevice::accessRenderTarget() {
     ASSERT_SINGLE_OWNER
-    DO_DEFERRED_CLEAR();
     return fRenderTarget;
 }
 
@@ -323,13 +312,10 @@
     GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "clearAll", fContext);
     SkIRect rect = SkIRect::MakeWH(this->width(), this->height());
     fDrawContext->clear(&rect, color, true);
-    fNeedClear = false;
 }
 
 void SkGpuDevice::replaceRenderTarget(bool shouldRetainContent) {
     ASSERT_SINGLE_OWNER
-    // Caller must have accessed the render target, because it knows the rt must be replaced.
-    SkASSERT(!fNeedClear);
 
     SkSurface::Budgeted budgeted =
             fRenderTarget->resourcePriv().isBudgeted() ? SkSurface::kYes_Budgeted
@@ -1310,10 +1296,6 @@
     GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawDevice", fContext);
     SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
 
-    // TODO: If the source device covers the whole of this device, we could
-    // omit fNeedsClear -related flushing.
-    // TODO: if source needs clear, we could maybe omit the draw fully.
-
     // drawDevice is defined to be in device coords.
     CHECK_SHOULD_DRAW(draw);
 
@@ -1769,7 +1751,6 @@
 
 void SkGpuDevice::flush() {
     ASSERT_SINGLE_OWNER
-    DO_DEFERRED_CLEAR();
 
     // Clear batch debugging output
     // TODO not exactly sure where this should live
diff --git a/src/gpu/SkGpuDevice.h b/src/gpu/SkGpuDevice.h
index 19bef21..8bf04b1 100644
--- a/src/gpu/SkGpuDevice.h
+++ b/src/gpu/SkGpuDevice.h
@@ -164,7 +164,6 @@
     GrClip                          fClip;;
     // remove when our clients don't rely on accessBitmap()
     SkBitmap                        fLegacyBitmap;
-    bool                            fNeedClear;
     bool                            fOpaque;
 
     enum Flags {
diff --git a/src/gpu/batches/GrClearBatch.h b/src/gpu/batches/GrClearBatch.h
index c38372c..ba4b6d6 100644
--- a/src/gpu/batches/GrClearBatch.h
+++ b/src/gpu/batches/GrClearBatch.h
@@ -40,7 +40,19 @@
 
 private:
     bool onCombineIfPossible(GrBatch* t, const GrCaps& caps) override {
-        // We could combine clears. TBD how much complexity to put here.
+        // This could be much more complicated. Currently we look at cases where the new clear
+        // contains the old clear, or when the new clear is a subset of the old clear and is the
+        // same color.
+        GrClearBatch* cb = t->cast<GrClearBatch>();
+        SkASSERT(cb->fRenderTarget == fRenderTarget);
+        if (cb->fRect.contains(fRect)) {
+            fRect = cb->fRect;
+            fBounds = cb->fBounds;
+            fColor = cb->fColor;
+            return true;
+        } else if (cb->fColor == fColor && fRect.contains(cb->fRect)) {
+            return true;
+        }
         return false;
     }
 
diff --git a/src/gpu/gl/GrGLGpu.cpp b/src/gpu/gl/GrGLGpu.cpp
index 001cd48..317ddbb 100644
--- a/src/gpu/gl/GrGLGpu.cpp
+++ b/src/gpu/gl/GrGLGpu.cpp
@@ -2153,7 +2153,6 @@
         // RT. We may add additional transformations below.
         ElevateDrawPreference(drawPreference, kRequireDraw_DrawPreference);
     }
-
     if (this->glCaps().rgba8888PixelsOpsAreSlow() && kRGBA_8888_GrPixelConfig == readConfig &&
         this->readPixelsSupported(kBGRA_8888_GrPixelConfig, kBGRA_8888_GrPixelConfig)) {
         tempDrawInfo->fTempSurfaceDesc.fConfig = kBGRA_8888_GrPixelConfig;
@@ -2773,8 +2772,7 @@
         return;
     }
 
-    if (fHWBlendState.fSrcCoeff != srcCoeff ||
-        fHWBlendState.fDstCoeff != dstCoeff) {
+    if (fHWBlendState.fSrcCoeff != srcCoeff || fHWBlendState.fDstCoeff != dstCoeff) {
         GL_CALL(BlendFunc(gXfermodeCoeff2Blend[srcCoeff],
                           gXfermodeCoeff2Blend[dstCoeff]));
         fHWBlendState.fSrcCoeff = srcCoeff;
@@ -3675,7 +3673,7 @@
 }
 
 GrBackendObject GrGLGpu::createTestingOnlyBackendTexture(void* pixels, int w, int h,
-                                                         GrPixelConfig config) const {
+                                                         GrPixelConfig config) {
     if (!this->caps()->isConfigTexturable(config)) {
         return false;
     }
@@ -3686,6 +3684,7 @@
     GL_CALL(ActiveTexture(GR_GL_TEXTURE0));
     GL_CALL(PixelStorei(GR_GL_UNPACK_ALIGNMENT, 1));
     GL_CALL(BindTexture(info->fTarget, info->fID));
+    fHWBoundTextureUniqueIDs[0] = 0;
     GL_CALL(TexParameteri(info->fTarget, GR_GL_TEXTURE_MAG_FILTER, GR_GL_NEAREST));
     GL_CALL(TexParameteri(info->fTarget, GR_GL_TEXTURE_MIN_FILTER, GR_GL_NEAREST));
     GL_CALL(TexParameteri(info->fTarget, GR_GL_TEXTURE_WRAP_S, GR_GL_CLAMP_TO_EDGE));
@@ -3730,7 +3729,7 @@
     return (GR_GL_TRUE == result);
 }
 
-void GrGLGpu::deleteTestingOnlyBackendTexture(GrBackendObject id, bool abandonTexture) const {
+void GrGLGpu::deleteTestingOnlyBackendTexture(GrBackendObject id, bool abandonTexture) {
 #ifdef SK_IGNORE_GL_TEXTURE_TARGET
     GrGLuint texID = (GrGLuint)id;
 #else
diff --git a/src/gpu/gl/GrGLGpu.h b/src/gpu/gl/GrGLGpu.h
index 6f194dc..6233048 100644
--- a/src/gpu/gl/GrGLGpu.h
+++ b/src/gpu/gl/GrGLGpu.h
@@ -126,9 +126,9 @@
                                                                 int height) override;
 
     GrBackendObject createTestingOnlyBackendTexture(void* pixels, int w, int h,
-                                                    GrPixelConfig config) const override;
+                                                    GrPixelConfig config) override;
     bool isTestingOnlyBackendTexture(GrBackendObject) const override;
-    void deleteTestingOnlyBackendTexture(GrBackendObject, bool abandonTexture) const override;
+    void deleteTestingOnlyBackendTexture(GrBackendObject, bool abandonTexture) override;
 
     void resetShaderCacheForTesting() const override;
 
diff --git a/tests/ClearTest.cpp b/tests/ClearTest.cpp
new file mode 100644
index 0000000..a36c439
--- /dev/null
+++ b/tests/ClearTest.cpp
@@ -0,0 +1,236 @@
+/*
+ * Copyright 2016 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "Test.h"
+
+#if SK_SUPPORT_GPU
+#include "GrContext.h"
+#include "GrDrawContext.h"
+#include "GrGpu.h"
+#include "GrRenderTarget.h"
+#include "GrTexture.h"
+#include "GrTextureProvider.h"
+
+static bool check_rect(GrDrawContext* dc, const SkIRect& rect, uint32_t expectedValue,
+                       uint32_t* actualValue, int* failX, int* failY) {
+    GrRenderTarget* rt = dc->accessRenderTarget();
+    int w = rect.width();
+    int h = rect.height();
+    SkAutoTDeleteArray<uint32_t> pixels(new uint32_t[w * h]);
+    memset(pixels.get(), ~expectedValue, sizeof(uint32_t) * w * h);
+    rt->readPixels(rect.fLeft, rect.fTop, w, h, kRGBA_8888_GrPixelConfig, pixels.get());
+    for (int y = 0; y < h; ++y) {
+        for (int x = 0; x < w; ++x) {
+            uint32_t pixel = pixels.get()[y * w + x];
+            if (pixel != expectedValue) {
+                *actualValue = pixel;
+                *failX = x + rect.fLeft;
+                *failY = y + rect.fTop;
+                return false;
+            }
+        }
+    }
+    return true;
+}
+
+// We only really need the DC, but currently the DC doesn't own the RT so we also ref it, but that
+// could be dropped when DC is a proper owner of its RT.
+static bool reset_dc(SkAutoTUnref<GrDrawContext>* dc, SkAutoTUnref<GrSurface>* rtKeepAlive,
+                     GrContext* context, int w, int h) {
+    SkDEBUGCODE(uint32_t oldID = 0;)
+    if (*dc) {
+        SkDEBUGCODE(oldID = (*dc)->accessRenderTarget()->getUniqueID();)
+        rtKeepAlive->reset(nullptr);
+        dc->reset(nullptr);
+    }
+    context->freeGpuResources();
+
+    GrTextureDesc desc;
+    desc.fWidth = w;
+    desc.fHeight = h;
+    desc.fConfig = kRGBA_8888_GrPixelConfig;
+    desc.fFlags = kRenderTarget_GrSurfaceFlag;
+
+    rtKeepAlive->reset(context->textureProvider()->createTexture(desc, true));
+    if (!(*rtKeepAlive)) {
+        return false;
+    }
+    GrRenderTarget* rt = (*rtKeepAlive)->asRenderTarget();
+    SkASSERT(rt->getUniqueID() != oldID);
+    dc->reset(context->drawContext(rt));
+    return SkToBool(*dc);
+}
+
+DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ClearBatch, reporter, context) {
+    static const int kW = 10;
+    static const int kH = 10;
+
+    SkIRect fullRect = SkIRect::MakeWH(kW, kH);
+    SkAutoTUnref<GrDrawContext> drawContext;
+    SkAutoTUnref<GrSurface> rtKeepAlive;
+
+    // A rectangle that is inset by one on all sides and the 1-pixel wide rectangles that surround
+    // it.
+    SkIRect mid1Rect = SkIRect::MakeXYWH(1, 1, kW-2, kH-2);
+    SkIRect outerLeftEdge = SkIRect::MakeXYWH(0, 0, 1, kH);
+    SkIRect outerTopEdge = SkIRect::MakeXYWH(0, 0, kW, 1);
+    SkIRect outerRightEdge = SkIRect::MakeXYWH(kW-1, 0, 1, kH);
+    SkIRect outerBottomEdge = SkIRect::MakeXYWH(0, kH-1, kW, 1);
+
+    // A rectangle that is inset by two on all sides and the 1-pixel wide rectangles that surround
+    // it.
+    SkIRect mid2Rect = SkIRect::MakeXYWH(2, 2, kW-4, kH-4);
+    SkIRect innerLeftEdge = SkIRect::MakeXYWH(1, 1, 1, kH-2);
+    SkIRect innerTopEdge = SkIRect::MakeXYWH(1, 1, kW-2, 1);
+    SkIRect innerRightEdge = SkIRect::MakeXYWH(kW-2, 1, 1, kH-2);
+    SkIRect innerBottomEdge = SkIRect::MakeXYWH(1, kH-2, kW-2, 1);
+
+    uint32_t actualValue;
+    int failX, failY;
+
+    static const GrColor kColor1 = 0xABCDEF01;
+    static const GrColor kColor2 = ~kColor1;
+
+    if (!reset_dc(&drawContext, &rtKeepAlive, context, kW, kH)) {
+        ERRORF(reporter, "Could not create draw context.");
+        return;
+    }
+    // Check a full clear
+    drawContext->clear(&fullRect, kColor1, false);
+    if (!check_rect(drawContext, fullRect, kColor1, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue,
+               failX, failY);
+    }
+
+    if (!reset_dc(&drawContext, &rtKeepAlive, context, kW, kH)) {
+        ERRORF(reporter, "Could not create draw context.");
+        return;
+    }
+    // Check two full clears, same color
+    drawContext->clear(&fullRect, kColor1, false);
+    drawContext->clear(&fullRect, kColor1, false);
+    if (!check_rect(drawContext, fullRect, kColor1, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue,
+               failX, failY);
+    }
+
+    if (!reset_dc(&drawContext, &rtKeepAlive, context, kW, kH)) {
+        ERRORF(reporter, "Could not create draw context.");
+        return;
+    }
+    // Check two full clears, different colors
+    drawContext->clear(&fullRect, kColor1, false);
+    drawContext->clear(&fullRect, kColor2, false);
+    if (!check_rect(drawContext, fullRect, kColor2, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue,
+               failX, failY);
+    }
+
+    if (!reset_dc(&drawContext, &rtKeepAlive, context, kW, kH)) {
+        ERRORF(reporter, "Could not create draw context.");
+        return;
+    }
+    // Test a full clear followed by a same color inset clear
+    drawContext->clear(&fullRect, kColor1, false);
+    drawContext->clear(&mid1Rect, kColor1, false);
+    if (!check_rect(drawContext, fullRect, kColor1, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue,
+               failX, failY);
+    }
+
+    if (!reset_dc(&drawContext, &rtKeepAlive, context, kW, kH)) {
+        ERRORF(reporter, "Could not create draw context.");
+        return;
+    }
+    // Test a inset clear followed by same color full clear
+    drawContext->clear(&mid1Rect, kColor1, false);
+    drawContext->clear(&fullRect, kColor1, false);
+    if (!check_rect(drawContext, fullRect, kColor1, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue,
+               failX, failY);
+    }
+
+    if (!reset_dc(&drawContext, &rtKeepAlive, context, kW, kH)) {
+        ERRORF(reporter, "Could not create draw context.");
+        return;
+    }
+    // Test a full clear followed by a different color inset clear
+    drawContext->clear(&fullRect, kColor1, false);
+    drawContext->clear(&mid1Rect, kColor2, false);
+    if (!check_rect(drawContext, mid1Rect, kColor2, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue,
+               failX, failY);
+    }
+    if (!check_rect(drawContext, outerLeftEdge, kColor1, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, outerTopEdge, kColor1, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, outerRightEdge, kColor1, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, outerBottomEdge, kColor1, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue,
+               failX, failY);
+    }
+
+    if (!reset_dc(&drawContext, &rtKeepAlive, context, kW, kH)) {
+        ERRORF(reporter, "Could not create draw context.");
+        return;
+    }
+    // Test a inset clear followed by a different full clear
+    drawContext->clear(&mid1Rect, kColor2, false);
+    drawContext->clear(&fullRect, kColor1, false);
+    if (!check_rect(drawContext, fullRect, kColor1, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue,
+               failX, failY);
+    }
+
+    if (!reset_dc(&drawContext, &rtKeepAlive, context, kW, kH)) {
+        ERRORF(reporter, "Could not create draw context.");
+        return;
+    }
+    // Check three nested clears from largest to smallest where outermost and innermost are same
+    // color.
+    drawContext->clear(&fullRect, kColor1, false);
+    drawContext->clear(&mid1Rect, kColor2, false);
+    drawContext->clear(&mid2Rect, kColor1, false);
+    if (!check_rect(drawContext, mid2Rect, kColor1, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue,
+               failX, failY);
+    }
+    if (!check_rect(drawContext, innerLeftEdge, kColor2, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, innerTopEdge, kColor2, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, innerRightEdge, kColor2, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, innerBottomEdge, kColor2, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue,
+               failX, failY);
+    }
+    if (!check_rect(drawContext, outerLeftEdge, kColor1, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, outerTopEdge, kColor1, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, outerRightEdge, kColor1, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, outerBottomEdge, kColor1, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue,
+               failX, failY);
+    }
+
+    if (!reset_dc(&drawContext, &rtKeepAlive, context, kW, kH)) {
+        ERRORF(reporter, "Could not create draw context.");
+        return;
+    }
+    // Swap the order of the second two clears in the above test.
+    drawContext->clear(&fullRect, kColor1, false);
+    drawContext->clear(&mid2Rect, kColor1, false);
+    drawContext->clear(&mid1Rect, kColor2, false);
+    if (!check_rect(drawContext, mid1Rect, kColor2, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue,
+               failX, failY);
+    }
+    if (!check_rect(drawContext, outerLeftEdge, kColor1, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, outerTopEdge, kColor1, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, outerRightEdge, kColor1, &actualValue, &failX, &failY) ||
+        !check_rect(drawContext, outerBottomEdge, kColor1, &actualValue, &failX, &failY)) {
+        ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue,
+               failX, failY);
+    }
+}
+#endif
diff --git a/tests/ResourceCacheTest.cpp b/tests/ResourceCacheTest.cpp
index ee8d7c7..c8613ad 100644
--- a/tests/ResourceCacheTest.cpp
+++ b/tests/ResourceCacheTest.cpp
@@ -187,7 +187,7 @@
 }
 
 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ResourceCacheWrappedResources, reporter, context) {
-    const GrGpu* gpu = context->getGpu();
+    GrGpu* gpu = context->getGpu();
     // this test is only valid for GL
     if (!gpu || !gpu->glContextForTesting()) {
         return;
diff --git a/tests/SurfaceTest.cpp b/tests/SurfaceTest.cpp
index 5b7325e..50d443d 100644
--- a/tests/SurfaceTest.cpp
+++ b/tests/SurfaceTest.cpp
@@ -5,6 +5,7 @@
  * found in the LICENSE file.
  */
 
+#include <functional>
 #include "SkCanvas.h"
 #include "SkData.h"
 #include "SkDevice.h"
@@ -82,7 +83,7 @@
 
 #if SK_SUPPORT_GPU
 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceWrappedTexture, reporter, context) {
-    const GrGpu* gpu = context->getGpu();
+    GrGpu* gpu = context->getGpu();
     if (!gpu) {
         return;
     }
@@ -702,3 +703,85 @@
     s = SkSurface::NewRaster(info, 1 << 30, nullptr); // allocation to large
     REPORTER_ASSERT(reporter, nullptr == s);
 }
+
+#if SK_SUPPORT_GPU
+
+void test_surface_clear(skiatest::Reporter* reporter, SkSurface* surface,
+                        std::function<GrSurface*(SkSurface*)> grSurfaceGetter,
+                        uint32_t expectedValue) {
+    if (!surface) {
+        ERRORF(reporter, "Could not create GPU SkSurface.");
+        return;
+    }
+    int w = surface->width();
+    int h = surface->height();
+    SkAutoTDeleteArray<uint32_t> pixels(new uint32_t[w * h]);
+    memset(pixels.get(), ~expectedValue, sizeof(uint32_t) * w * h);
+
+    SkAutoTUnref<GrSurface> grSurface(SkSafeRef(grSurfaceGetter(surface)));
+    if (!grSurface) {
+        ERRORF(reporter, "Could access render target of GPU SkSurface.");
+        return;
+    }
+    SkASSERT(surface->unique());
+    surface->unref();
+    grSurface->readPixels(0, 0, w, h, kRGBA_8888_GrPixelConfig, pixels.get());
+    for (int y = 0; y < h; ++y) {
+        for (int x = 0; x < w; ++x) {
+            uint32_t pixel = pixels.get()[y * w + x];
+            if (pixel != expectedValue) {
+                SkString msg;
+                if (expectedValue) {
+                    msg = "SkSurface should have left render target unmodified";
+                } else {
+                    msg = "SkSurface should have cleared the render target";
+                }
+                ERRORF(reporter,
+                       "%s but read 0x%08x (instead of 0x%08x) at %x,%d", msg.c_str(), pixel,
+                       expectedValue, x, y);
+                return;
+            }
+        }
+    }
+}
+
+DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceClear_Gpu, reporter, context) {
+    std::function<GrSurface*(SkSurface*)> grSurfaceGetters[] = {
+        [] (SkSurface* s){ return s->getCanvas()->internal_private_accessTopLayerRenderTarget();},
+        [] (SkSurface* s){
+            SkBaseDevice* d =
+                s->getCanvas()->getDevice_just_for_deprecated_compatibility_testing();
+            return d->accessRenderTarget(); },
+        [] (SkSurface* s){ SkImage* i = s->newImageSnapshot();
+                           return i->getTexture(); },
+        [] (SkSurface* s){ SkImage* i = s->newImageSnapshot();
+                           return as_IB(i)->peekTexture(); },
+    };
+    for (auto grSurfaceGetter : grSurfaceGetters) {
+        for (auto& surface_func : {&create_gpu_surface, &create_gpu_scratch_surface}) {
+            SkSurface* surface(surface_func(context, kPremul_SkAlphaType, nullptr));
+            test_surface_clear(reporter, surface, grSurfaceGetter, 0x0);
+        }
+        // Wrapped RTs are *not* supposed to clear (to allow client to partially update a surface).
+        static const int kWidth = 10;
+        static const int kHeight = 10;
+        SkAutoTDeleteArray<uint32_t> pixels(new uint32_t[kWidth * kHeight]);
+        memset(pixels.get(), 0xAB, sizeof(uint32_t) * kWidth * kHeight);
+
+        GrBackendObject textureObject =
+                context->getGpu()->createTestingOnlyBackendTexture(pixels.get(), kWidth, kHeight,
+                                                                   kRGBA_8888_GrPixelConfig);
+
+        GrBackendTextureDesc desc;
+        desc.fConfig = kRGBA_8888_GrPixelConfig;
+        desc.fWidth = kWidth;
+        desc.fHeight = kHeight;
+        desc.fFlags = kRenderTarget_GrBackendTextureFlag;
+        desc.fTextureHandle = textureObject;
+
+        SkSurface* surface = SkSurface::NewFromBackendTexture(context, desc, nullptr);
+        test_surface_clear(reporter, surface, grSurfaceGetter, 0xABABABAB);
+        context->getGpu()->deleteTestingOnlyBackendTexture(textureObject);
+    }
+}
+#endif