merge mozilla-inbound to mozilla-central a=merge
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Tue, 27 Sep 2016 11:21:25 +0200
changeset 315341 66a77b9bfe5dcacd50eccf85de7c0e7e15ce0ffd
parent 315340 b0b736fe600a41879e4a72934d9404a231462dcc (current diff)
parent 315285 280175619413b3ed74752933604fcb58477c07e0 (diff)
child 315342 efca0d71b0c5a99662d154884148b4445703eceb
child 315466 93bc88233717f6bc59806810664c5c1256e7e367
child 315538 cb212903f7036117ddbb29b3bdbc390b161b1bb2
push id82125
push usercbook@mozilla.com
push dateTue, 27 Sep 2016 09:26:31 +0000
treeherdermozilla-inbound@efca0d71b0c5 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone52.0a1
first release with
nightly linux32
66a77b9bfe5d / 52.0a1 / 20160927030200 / files
nightly linux64
66a77b9bfe5d / 52.0a1 / 20160927030200 / files
nightly mac
66a77b9bfe5d / 52.0a1 / 20160927030200 / files
nightly win32
66a77b9bfe5d / 52.0a1 / 20160927030200 / files
nightly win64
66a77b9bfe5d / 52.0a1 / 20160927030200 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
merge mozilla-inbound to mozilla-central a=merge
layout/style/StyleSheetHandle.h
layout/style/StyleSheetHandleInlines.h
security/nss/lib/ssl/derive.c
toolkit/components/search/tests/xpcshell/data/search-metadata.json
--- a/accessible/atk/UtilInterface.cpp
+++ b/accessible/atk/UtilInterface.cpp
@@ -260,17 +260,18 @@ mai_util_add_key_event_listener(AtkKeySn
   static guint key = 0;
 
   if (!sKey_listener_list) {
     sKey_listener_list = g_hash_table_new(nullptr, nullptr);
     sKey_snooper_id = gtk_key_snooper_install(mai_key_snooper, data);
   }
   AtkKeySnoopFuncPointer atkKeySnoop;
   atkKeySnoop.func_ptr = listener;
-  g_hash_table_insert(sKey_listener_list, GUINT_TO_POINTER(key++),
+  key++;
+  g_hash_table_insert(sKey_listener_list, GUINT_TO_POINTER(key),
                       atkKeySnoop.data);
   return key;
 }
 
 static void
 mai_util_remove_key_event_listener (guint remove_listener)
 {
     if (!sKey_listener_list) {
--- a/chrome/nsChromeRegistry.cpp
+++ b/chrome/nsChromeRegistry.cpp
@@ -24,24 +24,24 @@
 #include "nsIDOMLocation.h"
 #include "nsIDOMWindowCollection.h"
 #include "nsIDOMWindow.h"
 #include "nsIObserverService.h"
 #include "nsIPresShell.h"
 #include "nsIScriptError.h"
 #include "nsIWindowMediator.h"
 #include "nsIPrefService.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 nsChromeRegistry* nsChromeRegistry::gChromeRegistry;
 
 // DO NOT use namespace mozilla; it'll break due to a naming conflict between
 // mozilla::TextRange and a TextRange in OSX headers.
-using mozilla::StyleSheetHandle;
+using mozilla::StyleSheet;
 using mozilla::dom::IsChromeURI;
 
 ////////////////////////////////////////////////////////////////////////////////
 
 void
 nsChromeRegistry::LogMessage(const char* aMsg, ...)
 {
   nsCOMPtr<nsIConsoleService> console 
@@ -397,27 +397,27 @@ nsresult nsChromeRegistry::RefreshWindow
   nsCOMPtr<nsIDocument> document = aWindow->GetDoc();
   if (!document)
     return NS_OK;
 
   // Deal with the agent sheets first.  Have to do all the style sets by hand.
   nsCOMPtr<nsIPresShell> shell = document->GetShell();
   if (shell) {
     // Reload only the chrome URL agent style sheets.
-    nsTArray<StyleSheetHandle::RefPtr> agentSheets;
+    nsTArray<RefPtr<StyleSheet>> agentSheets;
     rv = shell->GetAgentStyleSheets(agentSheets);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    nsTArray<StyleSheetHandle::RefPtr> newAgentSheets;
-    for (StyleSheetHandle sheet : agentSheets) {
+    nsTArray<RefPtr<StyleSheet>> newAgentSheets;
+    for (StyleSheet* sheet : agentSheets) {
       nsIURI* uri = sheet->GetSheetURI();
 
       if (IsChromeURI(uri)) {
         // Reload the sheet.
-        StyleSheetHandle::RefPtr newSheet;
+        RefPtr<StyleSheet> newSheet;
         rv = document->LoadChromeSheetSync(uri, true, &newSheet);
         if (NS_FAILED(rv)) return rv;
         if (newSheet) {
           rv = newAgentSheets.AppendElement(newSheet) ? NS_OK : NS_ERROR_FAILURE;
           if (NS_FAILED(rv)) return rv;
         }
       }
       else {  // Just use the same sheet.
@@ -428,36 +428,36 @@ nsresult nsChromeRegistry::RefreshWindow
 
     rv = shell->SetAgentStyleSheets(newAgentSheets);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   int32_t count = document->GetNumberOfStyleSheets();
 
   // Build an array of style sheets we need to reload.
-  nsTArray<StyleSheetHandle::RefPtr> oldSheets(count);
-  nsTArray<StyleSheetHandle::RefPtr> newSheets(count);
+  nsTArray<RefPtr<StyleSheet>> oldSheets(count);
+  nsTArray<RefPtr<StyleSheet>> newSheets(count);
 
   // Iterate over the style sheets.
   for (int32_t i = 0; i < count; i++) {
     // Get the style sheet
-    StyleSheetHandle styleSheet = document->GetStyleSheetAt(i);
+    StyleSheet* styleSheet = document->GetStyleSheetAt(i);
     oldSheets.AppendElement(styleSheet);
   }
 
   // Iterate over our old sheets and kick off a sync load of the new
   // sheet if and only if it's a non-inline sheet with a chrome URL.
-  for (StyleSheetHandle sheet : oldSheets) {
+  for (StyleSheet* sheet : oldSheets) {
     MOZ_ASSERT(sheet, "GetStyleSheetAt shouldn't return nullptr for "
                       "in-range sheet indexes");
     nsIURI* uri = sheet->GetSheetURI();
 
     if (!sheet->IsInline() && IsChromeURI(uri)) {
       // Reload the sheet.
-      StyleSheetHandle::RefPtr newSheet;
+      RefPtr<StyleSheet> newSheet;
       // XXX what about chrome sheets that have a title or are disabled?  This
       // only works by sheer dumb luck.
       document->LoadChromeSheetSync(uri, false, &newSheet);
       // Even if it's null, we put in in there.
       newSheets.AppendElement(newSheet);
     } else {
       // Just use the same sheet.
       newSheets.AppendElement(sheet);
--- a/config/external/nss/nss.symbols
+++ b/config/external/nss/nss.symbols
@@ -668,23 +668,25 @@ SSL_GetClientAuthDataHook
 SSL_GetImplementedCiphers
 SSL_GetNextProto
 SSL_GetNumImplementedCiphers
 SSL_GetSRTPCipher
 SSL_HandshakeCallback
 SSL_HandshakeNegotiatedExtension
 SSL_ImplementedCiphers @DATA@
 SSL_ImportFD
+SSL_NamedGroupConfig
 SSL_NumImplementedCiphers @DATA@
 SSL_OptionSet
 SSL_OptionSetDefault
 SSL_PeerCertificate
 SSL_PeerCertificateChain
 SSL_PeerStapledOCSPResponses
 SSL_ResetHandshake
+SSL_SendAdditionalKeyShares
 SSL_SetCanFalseStartCallback
 SSL_SetDowngradeCheckVersion
 SSL_SetNextProtoNego
 SSL_SetPKCS11PinArg
 SSL_SetSockPeerID
 SSL_SetSRTPCiphers
 SSL_SetStapledOCSPResponses
 SSL_SetURL
--- a/dom/base/ShadowRoot.cpp
+++ b/dom/base/ShadowRoot.cpp
@@ -12,18 +12,18 @@
 #include "nsContentUtils.h"
 #include "nsDOMClassInfoID.h"
 #include "nsIDOMHTMLElement.h"
 #include "nsIStyleSheetLinkingElement.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/HTMLContentElement.h"
 #include "mozilla/dom/HTMLShadowElement.h"
 #include "nsXBLPrototypeBinding.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(ShadowRoot)
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(ShadowRoot,
                                                   DocumentFragment)
@@ -127,17 +127,17 @@ ShadowRoot::StyleSheetChanged()
   if (shell) {
     OwnerDoc()->BeginUpdate(UPDATE_STYLE);
     shell->RecordShadowStyleChange(this);
     OwnerDoc()->EndUpdate(UPDATE_STYLE);
   }
 }
 
 void
-ShadowRoot::InsertSheet(StyleSheetHandle aSheet,
+ShadowRoot::InsertSheet(StyleSheet* aSheet,
                         nsIContent* aLinkingContent)
 {
   nsCOMPtr<nsIStyleSheetLinkingElement>
     linkingElement = do_QueryInterface(aLinkingContent);
   MOZ_ASSERT(linkingElement, "The only styles in a ShadowRoot should come "
                              "from <style>.");
 
   linkingElement->SetStyleSheet(aSheet); // This sets the ownerNode on the sheet
@@ -158,17 +158,17 @@ ShadowRoot::InsertSheet(StyleSheetHandle
   }
 
   if (aSheet->IsApplicable()) {
     StyleSheetChanged();
   }
 }
 
 void
-ShadowRoot::RemoveSheet(StyleSheetHandle aSheet)
+ShadowRoot::RemoveSheet(StyleSheet* aSheet)
 {
   mProtoBinding->RemoveStyleSheet(aSheet);
 
   if (aSheet->IsApplicable()) {
     StyleSheetChanged();
   }
 }
 
@@ -751,17 +751,17 @@ ShadowRootStyleSheetList::IndexedGetter(
   aFound = aIndex < mShadowRoot->mProtoBinding->SheetCount();
 
   if (!aFound) {
     return nullptr;
   }
 
   // XXXheycam Return null until ServoStyleSheet implements the right
   // DOM interfaces.
-  StyleSheetHandle sheet = mShadowRoot->mProtoBinding->StyleSheetAt(aIndex);
+  StyleSheet* sheet = mShadowRoot->mProtoBinding->StyleSheetAt(aIndex);
   if (sheet->IsServo()) {
     NS_ERROR("stylo: can't return ServoStyleSheets to script yet");
     return nullptr;
   }
   return sheet->AsGecko();
 }
 
 uint32_t
--- a/dom/base/ShadowRoot.h
+++ b/dom/base/ShadowRoot.h
@@ -4,17 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_shadowroot_h__
 #define mozilla_dom_shadowroot_h__
 
 #include "mozilla/dom/DocumentFragment.h"
 #include "mozilla/dom/StyleSheetList.h"
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 #include "nsCOMPtr.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIContentInlines.h"
 #include "nsTHashtable.h"
 #include "nsDocument.h"
 
 class nsIAtom;
 class nsIContent;
@@ -42,18 +42,18 @@ public:
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTREMOVED
 
   ShadowRoot(nsIContent* aContent, already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
              nsXBLPrototypeBinding* aProtoBinding);
 
   void AddToIdTable(Element* aElement, nsIAtom* aId);
   void RemoveFromIdTable(Element* aElement, nsIAtom* aId);
-  void InsertSheet(StyleSheetHandle aSheet, nsIContent* aLinkingContent);
-  void RemoveSheet(StyleSheetHandle aSheet);
+  void InsertSheet(StyleSheet* aSheet, nsIContent* aLinkingContent);
+  void RemoveSheet(StyleSheet* aSheet);
   bool ApplyAuthorStyles();
   void SetApplyAuthorStyles(bool aApplyAuthorStyles);
   StyleSheetList* StyleSheets();
   HTMLShadowElement* GetShadowElement() { return mShadowElement; }
 
   /**
    * Sets the current shadow insertion point where the older
    * ShadowRoot will be projected.
--- a/dom/base/nsContentSink.cpp
+++ b/dom/base/nsContentSink.cpp
@@ -202,17 +202,17 @@ nsContentSink::Init(nsIDocument* aDoc,
     mDynamicLowerValue = sEnablePerfMode == 1;
     FavorPerformanceHint(!mDynamicLowerValue, 0);
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsContentSink::StyleSheetLoaded(StyleSheetHandle aSheet,
+nsContentSink::StyleSheetLoaded(StyleSheet* aSheet,
                                 bool aWasAlternate,
                                 nsresult aStatus)
 {
   NS_ASSERTION(!mRunsToCompletion, "How come a fragment parser observed sheets?");
   if (!aWasAlternate) {
     NS_ASSERTION(mPendingSheetCount > 0, "How'd that happen?");
     --mPendingSheetCount;
 
--- a/dom/base/nsContentSink.h
+++ b/dom/base/nsContentSink.h
@@ -80,17 +80,17 @@ class nsContentSink : public nsICSSLoade
 {
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsContentSink,
                                            nsICSSLoaderObserver)
     // nsITimerCallback
   NS_DECL_NSITIMERCALLBACK
 
   // nsICSSLoaderObserver
-  NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheetHandle aSheet,
+  NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheet* aSheet,
                               bool aWasAlternate,
                               nsresult aStatus) override;
 
   virtual nsresult ProcessMETATag(nsIContent* aContent);
 
   // nsIContentSink implementation helpers
   nsresult WillParseImpl(void);
   nsresult WillInterruptImpl(void);
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -104,17 +104,17 @@
 #include "nsContentPermissionHelper.h"
 #include "nsCSSPseudoElements.h"            // for CSSPseudoElementType
 #include "nsNetUtil.h"
 #include "nsDocument.h"
 #include "HTMLImageElement.h"
 #include "mozilla/css/ImageLoader.h"
 #include "mozilla/layers/APZCTreeManager.h" // for layers::ZoomToRectBehavior
 #include "mozilla/dom/Promise.h"
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 #ifdef XP_WIN
 #undef GetClassName
 #endif
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::ipc;
--- a/dom/base/nsDocument.cpp
+++ b/dom/base/nsDocument.cpp
@@ -245,18 +245,18 @@
 #include "nsWindowMemoryReporter.h"
 #include "mozilla/dom/Location.h"
 #include "mozilla/dom/FontFaceSet.h"
 #include "mozilla/dom/BoxObject.h"
 #include "gfxPrefs.h"
 #include "nsISupportsPrimitives.h"
 #include "mozilla/StyleSetHandle.h"
 #include "mozilla/StyleSetHandleInlines.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 #include "mozilla/DocLoadingTimelineMarker.h"
 
 #include "nsISpeculativeConnect.h"
 
 #include "mozilla/MediaManager.h"
 #ifdef MOZ_WEBRTC
 #include "IPeerConnection.h"
@@ -595,17 +595,17 @@ CSSStyleSheet*
 nsDOMStyleSheetList::IndexedGetter(uint32_t aIndex, bool& aFound)
 {
   if (!mDocument || aIndex >= (uint32_t)mDocument->GetNumberOfStyleSheets()) {
     aFound = false;
     return nullptr;
   }
 
   aFound = true;
-  StyleSheetHandle sheet = mDocument->GetStyleSheetAt(aIndex);
+  StyleSheet* sheet = mDocument->GetStyleSheetAt(aIndex);
   NS_ASSERTION(sheet, "Must have a sheet");
 
   // XXXheycam Return null until ServoStyleSheet implements the right DOM
   // interfaces.
   if (sheet->IsServo()) {
     NS_ERROR("stylo: can't return a ServoStyleSheet to the DOM yet");
     return nullptr;
   }
@@ -614,26 +614,26 @@ nsDOMStyleSheetList::IndexedGetter(uint3
 
 void
 nsDOMStyleSheetList::NodeWillBeDestroyed(const nsINode *aNode)
 {
   mDocument = nullptr;
 }
 
 void
-nsDOMStyleSheetList::StyleSheetAdded(StyleSheetHandle aStyleSheet,
+nsDOMStyleSheetList::StyleSheetAdded(StyleSheet* aStyleSheet,
                                      bool aDocumentSheet)
 {
   if (aDocumentSheet && -1 != mLength) {
     mLength++;
   }
 }
 
 void
-nsDOMStyleSheetList::StyleSheetRemoved(StyleSheetHandle aStyleSheet,
+nsDOMStyleSheetList::StyleSheetRemoved(StyleSheet* aStyleSheet,
                                        bool aDocumentSheet)
 {
   if (aDocumentSheet && -1 != mLength) {
     mLength--;
   }
 }
 
 // nsOnloadBlocker implementation
@@ -1191,17 +1191,17 @@ nsDOMStyleSheetSetList::EnsureFresh()
   if (!mDocument) {
     return; // Spec says "no exceptions", and we have no style sets if we have
             // no document, for sure
   }
 
   int32_t count = mDocument->GetNumberOfStyleSheets();
   nsAutoString title;
   for (int32_t index = 0; index < count; index++) {
-    StyleSheetHandle sheet = mDocument->GetStyleSheetAt(index);
+    StyleSheet* sheet = mDocument->GetStyleSheetAt(index);
     NS_ASSERTION(sheet, "Null sheet in sheet list!");
     // XXXheycam ServoStyleSheets don't expose their title yet.
     if (sheet->IsServo()) {
       NS_ERROR("stylo: ServoStyleSets don't expose their title yet");
       continue;
     }
     sheet->AsGecko()->GetTitle(title);
     if (!title.IsEmpty() && !mNames.Contains(title) && !Add(title)) {
@@ -1492,17 +1492,17 @@ nsDocument::~nsDocument()
   for (uint32_t indx = mChildren.ChildCount(); indx-- != 0; ) {
     mChildren.ChildAt(indx)->UnbindFromTree();
     mChildren.RemoveChildAt(indx);
   }
   mFirstChild = nullptr;
   mCachedRootElement = nullptr;
 
   // Let the stylesheets know we're going away
-  for (StyleSheetHandle sheet : mStyleSheets) {
+  for (StyleSheet* sheet : mStyleSheets) {
     sheet->SetOwningDocument(nullptr);
   }
   if (mAttrStyleSheet) {
     mAttrStyleSheet->SetOwningDocument(nullptr);
   }
   // We don't own the mOnDemandBuiltInUASheets, so we don't need to reset them.
 
   if (mListenerManager) {
@@ -2148,36 +2148,36 @@ nsDocument::ResetToURI(nsIURI *aURI, nsI
     nsGlobalWindow::Cast(win)->RefreshCompartmentPrincipal();
   }
 }
 
 void
 nsDocument::RemoveDocStyleSheetsFromStyleSets()
 {
   // The stylesheets should forget us
-  for (StyleSheetHandle sheet : Reversed(mStyleSheets)) {
+  for (StyleSheet* sheet : Reversed(mStyleSheets)) {
     sheet->SetOwningDocument(nullptr);
 
     if (sheet->IsApplicable()) {
       nsCOMPtr<nsIPresShell> shell = GetShell();
       if (shell) {
         shell->StyleSet()->RemoveDocStyleSheet(sheet);
       }
     }
     // XXX Tell observers?
   }
 }
 
 void
 nsDocument::RemoveStyleSheetsFromStyleSets(
-    const nsTArray<StyleSheetHandle::RefPtr>& aSheets,
+    const nsTArray<RefPtr<StyleSheet>>& aSheets,
     SheetType aType)
 {
   // The stylesheets should forget us
-  for (StyleSheetHandle sheet : Reversed(aSheets)) {
+  for (StyleSheet* sheet : Reversed(aSheets)) {
     sheet->SetOwningDocument(nullptr);
 
     if (sheet->IsApplicable()) {
       nsCOMPtr<nsIPresShell> shell = GetShell();
       if (shell) {
         shell->StyleSet()->RemoveStyleSheet(aType, sheet);
       }
     }
@@ -2245,50 +2245,50 @@ nsDocument::ResetStylesheetsToURI(nsIURI
   nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     FillStyleSet(shell->StyleSet());
   }
 }
 
 static void
 AppendSheetsToStyleSet(StyleSetHandle aStyleSet,
-                       const nsTArray<StyleSheetHandle::RefPtr>& aSheets,
+                       const nsTArray<RefPtr<StyleSheet>>& aSheets,
                        SheetType aType)
 {
-  for (StyleSheetHandle sheet : Reversed(aSheets)) {
+  for (StyleSheet* sheet : Reversed(aSheets)) {
     aStyleSet->AppendStyleSheet(aType, sheet);
   }
 }
 
 
 void
 nsDocument::FillStyleSet(StyleSetHandle aStyleSet)
 {
   NS_PRECONDITION(aStyleSet, "Must have a style set");
   NS_PRECONDITION(aStyleSet->SheetCount(SheetType::Doc) == 0,
                   "Style set already has document sheets?");
 
   MOZ_ASSERT(!mStyleSetFilled);
 
-  for (StyleSheetHandle sheet : Reversed(mStyleSheets)) {
+  for (StyleSheet* sheet : Reversed(mStyleSheets)) {
     if (sheet->IsApplicable()) {
       aStyleSet->AddDocStyleSheet(sheet, this);
     }
   }
 
   if (aStyleSet->IsGecko()) {
     nsStyleSheetService *sheetService = nsStyleSheetService::GetInstance();
     if (sheetService) {
-      for (StyleSheetHandle sheet : *sheetService->AuthorStyleSheets()) {
+      for (StyleSheet* sheet : *sheetService->AuthorStyleSheets()) {
         aStyleSet->AppendStyleSheet(SheetType::Doc, sheet);
       }
     }
 
     // Iterate backwards to maintain order
-    for (StyleSheetHandle sheet : Reversed(mOnDemandBuiltInUASheets)) {
+    for (StyleSheet* sheet : Reversed(mOnDemandBuiltInUASheets)) {
       if (sheet->IsApplicable()) {
         aStyleSet->PrependStyleSheet(SheetType::Agent, sheet);
       }
     }
   } else {
     NS_WARNING("stylo: Not yet checking nsStyleSheetService for Servo-backed "
                "documents. See bug 1290224");
   }
@@ -3934,28 +3934,28 @@ nsDocument::RemoveChildAt(uint32_t aInde
     DestroyElementMaps();
   }
 
   doRemoveChildAt(aIndex, aNotify, oldKid, mChildren);
   mCachedRootElement = nullptr;
 }
 
 void
-nsDocument::EnsureOnDemandBuiltInUASheet(StyleSheetHandle aSheet)
+nsDocument::EnsureOnDemandBuiltInUASheet(StyleSheet* aSheet)
 {
   if (mOnDemandBuiltInUASheets.Contains(aSheet)) {
     return;
   }
   BeginUpdate(UPDATE_STYLE);
   AddOnDemandBuiltInUASheet(aSheet);
   EndUpdate(UPDATE_STYLE);
 }
 
 void
-nsDocument::AddOnDemandBuiltInUASheet(StyleSheetHandle aSheet)
+nsDocument::AddOnDemandBuiltInUASheet(StyleSheet* aSheet)
 {
   MOZ_ASSERT(!mOnDemandBuiltInUASheets.Contains(aSheet));
 
   // Prepend here so that we store the sheets in mOnDemandBuiltInUASheets in
   // the same order that they should end up in the style set.
   mOnDemandBuiltInUASheets.InsertElementAt(0, aSheet);
 
   if (aSheet->IsApplicable()) {
@@ -3974,30 +3974,30 @@ nsDocument::AddOnDemandBuiltInUASheet(St
 }
 
 int32_t
 nsDocument::GetNumberOfStyleSheets() const
 {
   return mStyleSheets.Length();
 }
 
-StyleSheetHandle
+StyleSheet*
 nsDocument::GetStyleSheetAt(int32_t aIndex) const
 {
-  return mStyleSheets.SafeElementAt(aIndex, StyleSheetHandle());
+  return mStyleSheets.SafeElementAt(aIndex, nullptr);
 }
 
 int32_t
-nsDocument::GetIndexOfStyleSheet(const StyleSheetHandle aSheet) const
+nsDocument::GetIndexOfStyleSheet(const StyleSheet* aSheet) const
 {
   return mStyleSheets.IndexOf(aSheet);
 }
 
 void
-nsDocument::AddStyleSheetToStyleSets(StyleSheetHandle aSheet)
+nsDocument::AddStyleSheetToStyleSets(StyleSheet* aSheet)
 {
   nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     shell->StyleSet()->AddDocStyleSheet(aSheet, this);
   }
 }
 
 #define DO_STYLESHEET_NOTIFICATION(className, type, memberName, argName)      \
@@ -4018,69 +4018,69 @@ nsDocument::AddStyleSheetToStyleSets(Sty
     event->SetTarget(this);                                                   \
     RefPtr<AsyncEventDispatcher> asyncDispatcher =                          \
       new AsyncEventDispatcher(this, event);                                  \
     asyncDispatcher->mOnlyChromeDispatch = true;                              \
     asyncDispatcher->PostDOMEvent();                                          \
   } while (0);
 
 void
-nsDocument::NotifyStyleSheetAdded(StyleSheetHandle aSheet, bool aDocumentSheet)
+nsDocument::NotifyStyleSheetAdded(StyleSheet* aSheet, bool aDocumentSheet)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleSheetAdded, (aSheet, aDocumentSheet));
 
   if (StyleSheetChangeEventsEnabled()) {
     DO_STYLESHEET_NOTIFICATION(StyleSheetChangeEvent,
                                "StyleSheetAdded",
                                mDocumentSheet,
                                aDocumentSheet);
   }
 }
 
 void
-nsDocument::NotifyStyleSheetRemoved(StyleSheetHandle aSheet, bool aDocumentSheet)
+nsDocument::NotifyStyleSheetRemoved(StyleSheet* aSheet, bool aDocumentSheet)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleSheetRemoved, (aSheet, aDocumentSheet));
 
   if (StyleSheetChangeEventsEnabled()) {
     DO_STYLESHEET_NOTIFICATION(StyleSheetChangeEvent,
                                "StyleSheetRemoved",
                                mDocumentSheet,
                                aDocumentSheet);
   }
 }
 
 void
-nsDocument::AddStyleSheet(StyleSheetHandle aSheet)
+nsDocument::AddStyleSheet(StyleSheet* aSheet)
 {
   NS_PRECONDITION(aSheet, "null arg");
   mStyleSheets.AppendElement(aSheet);
   aSheet->SetOwningDocument(this);
 
   if (aSheet->IsApplicable()) {
     AddStyleSheetToStyleSets(aSheet);
   }
 
   NotifyStyleSheetAdded(aSheet, true);
 }
 
 void
-nsDocument::RemoveStyleSheetFromStyleSets(StyleSheetHandle aSheet)
+nsDocument::RemoveStyleSheetFromStyleSets(StyleSheet* aSheet)
 {
   nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     shell->StyleSet()->RemoveDocStyleSheet(aSheet);
   }
 }
 
 void
-nsDocument::RemoveStyleSheet(StyleSheetHandle aSheet)
+nsDocument::RemoveStyleSheet(StyleSheet* aSheet)
 {
   NS_PRECONDITION(aSheet, "null arg");
-  StyleSheetHandle::RefPtr sheet = aSheet; // hold ref so it won't die too soon
+  RefPtr<StyleSheet> sheet = aSheet; // hold ref so it won't die too soon
 
   if (!mStyleSheets.RemoveElement(aSheet)) {
     NS_ASSERTION(mInUnlinkOrDeletion, "stylesheet not found");
     return;
   }
 
   if (!mIsGoingAway) {
     if (aSheet->IsApplicable()) {
@@ -4089,71 +4089,71 @@ nsDocument::RemoveStyleSheet(StyleSheetH
 
     NotifyStyleSheetRemoved(aSheet, true);
   }
 
   aSheet->SetOwningDocument(nullptr);
 }
 
 void
-nsDocument::UpdateStyleSheets(nsTArray<StyleSheetHandle::RefPtr>& aOldSheets,
-                              nsTArray<StyleSheetHandle::RefPtr>& aNewSheets)
+nsDocument::UpdateStyleSheets(nsTArray<RefPtr<StyleSheet>>& aOldSheets,
+                              nsTArray<RefPtr<StyleSheet>>& aNewSheets)
 {
   BeginUpdate(UPDATE_STYLE);
 
   // XXX Need to set the sheet on the ownernode, if any
   NS_PRECONDITION(aOldSheets.Length() == aNewSheets.Length(),
                   "The lists must be the same length!");
   int32_t count = aOldSheets.Length();
 
-  StyleSheetHandle::RefPtr oldSheet;
+  RefPtr<StyleSheet> oldSheet;
   int32_t i;
   for (i = 0; i < count; ++i) {
     oldSheet = aOldSheets[i];
 
     // First remove the old sheet.
     NS_ASSERTION(oldSheet, "None of the old sheets should be null");
     int32_t oldIndex = mStyleSheets.IndexOf(oldSheet);
     RemoveStyleSheet(oldSheet);  // This does the right notifications
 
     // Now put the new one in its place.  If it's null, just ignore it.
-    StyleSheetHandle newSheet = aNewSheets[i];
+    StyleSheet* newSheet = aNewSheets[i];
     if (newSheet) {
       mStyleSheets.InsertElementAt(oldIndex, newSheet);
       newSheet->SetOwningDocument(this);
       if (newSheet->IsApplicable()) {
         AddStyleSheetToStyleSets(newSheet);
       }
 
       NotifyStyleSheetAdded(newSheet, true);
     }
   }
 
   EndUpdate(UPDATE_STYLE);
 }
 
 void
-nsDocument::InsertStyleSheetAt(StyleSheetHandle aSheet, int32_t aIndex)
+nsDocument::InsertStyleSheetAt(StyleSheet* aSheet, int32_t aIndex)
 {
   NS_PRECONDITION(aSheet, "null ptr");
 
   mStyleSheets.InsertElementAt(aIndex, aSheet);
 
   aSheet->SetOwningDocument(this);
 
   if (aSheet->IsApplicable()) {
     AddStyleSheetToStyleSets(aSheet);
   }
 
   NotifyStyleSheetAdded(aSheet, true);
 }
 
 
 void
-nsDocument::SetStyleSheetApplicableState(StyleSheetHandle aSheet,
+nsDocument::SetStyleSheetApplicableState(StyleSheet* aSheet,
                                          bool aApplicable)
 {
   NS_PRECONDITION(aSheet, "null arg");
 
   // If we're actually in the document style sheet list
   if (mStyleSheets.IndexOf(aSheet) != mStyleSheets.NoIndex) {
     if (aApplicable) {
       AddStyleSheetToStyleSets(aSheet);
@@ -4209,17 +4209,17 @@ ConvertAdditionalSheetType(nsIDocument::
     default:
       MOZ_ASSERT(false, "wrong type");
       // we must return something although this should never happen
       return SheetType::Count;
   }
 }
 
 static int32_t
-FindSheet(const nsTArray<StyleSheetHandle::RefPtr>& aSheets, nsIURI* aSheetURI)
+FindSheet(const nsTArray<RefPtr<StyleSheet>>& aSheets, nsIURI* aSheetURI)
 {
   for (int32_t i = aSheets.Length() - 1; i >= 0; i-- ) {
     bool bEqual;
     nsIURI* uri = aSheets[i]->GetSheetURI();
 
     if (uri && NS_SUCCEEDED(uri->Equals(aSheetURI, &bEqual)) && bEqual)
       return i;
   }
@@ -4253,28 +4253,28 @@ nsDocument::LoadAdditionalStyleSheet(add
     case nsIDocument::eAuthorSheet:
       parsingMode = css::eAuthorSheetFeatures;
       break;
 
     default:
       MOZ_CRASH("impossible value for aType");
   }
 
-  StyleSheetHandle::RefPtr sheet;
+  RefPtr<StyleSheet> sheet;
   nsresult rv = loader->LoadSheetSync(aSheetURI, parsingMode, true, &sheet);
   NS_ENSURE_SUCCESS(rv, rv);
 
   sheet->SetOwningDocument(this);
   MOZ_ASSERT(sheet->IsApplicable());
 
   return AddAdditionalStyleSheet(aType, sheet);
 }
 
 nsresult
-nsDocument::AddAdditionalStyleSheet(additionalSheetType aType, StyleSheetHandle aSheet)
+nsDocument::AddAdditionalStyleSheet(additionalSheetType aType, StyleSheet* aSheet)
 {
   if (mAdditionalSheets[aType].Contains(aSheet))
     return NS_ERROR_INVALID_ARG;
 
   if (!aSheet->IsApplicable())
     return NS_ERROR_INVALID_ARG;
 
   mAdditionalSheets[aType].AppendElement(aSheet);
@@ -4293,21 +4293,21 @@ nsDocument::AddAdditionalStyleSheet(addi
   return NS_OK;
 }
 
 void
 nsDocument::RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* aSheetURI)
 {
   MOZ_ASSERT(aSheetURI);
 
-  nsTArray<StyleSheetHandle::RefPtr>& sheets = mAdditionalSheets[aType];
+  nsTArray<RefPtr<StyleSheet>>& sheets = mAdditionalSheets[aType];
 
   int32_t i = FindSheet(mAdditionalSheets[aType], aSheetURI);
   if (i >= 0) {
-    StyleSheetHandle::RefPtr sheetRef = sheets[i];
+    RefPtr<StyleSheet> sheetRef = sheets[i];
     sheets.RemoveElementAt(i);
 
     BeginUpdate(UPDATE_STYLE);
     if (!mIsGoingAway) {
       MOZ_ASSERT(sheetRef->IsApplicable());
       nsCOMPtr<nsIPresShell> shell = GetShell();
       if (shell) {
         SheetType type = ConvertAdditionalSheetType(aType);
@@ -4319,20 +4319,20 @@ nsDocument::RemoveAdditionalStyleSheet(a
     // these additional sheets.
     NotifyStyleSheetRemoved(sheetRef, false);
     EndUpdate(UPDATE_STYLE);
 
     sheetRef->SetOwningDocument(nullptr);
   }
 }
 
-StyleSheetHandle
+StyleSheet*
 nsDocument::GetFirstAdditionalAuthorSheet()
 {
-  return mAdditionalSheets[eAuthorSheet].SafeElementAt(0, StyleSheetHandle());
+  return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
 }
 
 nsIGlobalObject*
 nsDocument::GetScopeObject() const
 {
   nsCOMPtr<nsIGlobalObject> scope(do_QueryReferent(mScopeObject));
   return scope;
 }
@@ -5127,46 +5127,46 @@ nsDocument::DocumentStatesChanged(EventS
   // Invalidate our cached state.
   mGotDocumentState &= ~aStateMask;
   mDocumentState &= ~aStateMask;
 
   NS_DOCUMENT_NOTIFY_OBSERVERS(DocumentStatesChanged, (this, aStateMask));
 }
 
 void
-nsDocument::StyleRuleChanged(StyleSheetHandle aSheet,
+nsDocument::StyleRuleChanged(StyleSheet* aSheet,
                              css::Rule* aStyleRule)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleRuleChanged, (aSheet));
 
   if (StyleSheetChangeEventsEnabled()) {
     DO_STYLESHEET_NOTIFICATION(StyleRuleChangeEvent,
                                "StyleRuleChanged",
                                mRule,
                                aStyleRule ? aStyleRule->GetDOMRule() : nullptr);
   }
 }
 
 void
-nsDocument::StyleRuleAdded(StyleSheetHandle aSheet,
+nsDocument::StyleRuleAdded(StyleSheet* aSheet,
                            css::Rule* aStyleRule)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleRuleAdded, (aSheet));
 
   if (StyleSheetChangeEventsEnabled()) {
     DO_STYLESHEET_NOTIFICATION(StyleRuleChangeEvent,
                                "StyleRuleAdded",
                                mRule,
                                aStyleRule ? aStyleRule->GetDOMRule()
                                           : nullptr);
   }
 }
 
 void
-nsDocument::StyleRuleRemoved(StyleSheetHandle aSheet,
+nsDocument::StyleRuleRemoved(StyleSheet* aSheet,
                              css::Rule* aStyleRule)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleRuleRemoved, (aSheet));
 
   if (StyleSheetChangeEventsEnabled()) {
     DO_STYLESHEET_NOTIFICATION(StyleRuleChangeEvent,
                                "StyleRuleRemoved",
                                mRule,
@@ -6024,17 +6024,17 @@ void
 nsIDocument::GetSelectedStyleSheetSet(nsAString& aSheetSet)
 {
   aSheetSet.Truncate();
 
   // Look through our sheets, find the selected set title
   int32_t count = GetNumberOfStyleSheets();
   nsAutoString title;
   for (int32_t index = 0; index < count; index++) {
-    StyleSheetHandle sheet = GetStyleSheetAt(index);
+    StyleSheet* sheet = GetStyleSheetAt(index);
     NS_ASSERTION(sheet, "Null sheet in sheet list!");
 
     // XXXheycam Make this work with ServoStyleSheets.
     if (sheet->IsServo()) {
       NS_ERROR("stylo: can't handle alternate ServoStyleSheets yet");
       continue;
     }
 
@@ -6144,17 +6144,17 @@ nsDocument::EnableStyleSheetsForSet(cons
 void
 nsDocument::EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
                                             bool aUpdateCSSLoader)
 {
   BeginUpdate(UPDATE_STYLE);
   int32_t count = GetNumberOfStyleSheets();
   nsAutoString title;
   for (int32_t index = 0; index < count; index++) {
-    StyleSheetHandle sheet = GetStyleSheetAt(index);
+    StyleSheet* sheet = GetStyleSheetAt(index);
     NS_ASSERTION(sheet, "Null sheet in sheet list!");
 
     // XXXheycam Make this work with ServoStyleSheets.
     if (sheet->IsServo()) {
       NS_ERROR("stylo: can't handle alternate ServoStyleSheets yet");
       continue;
     }
 
@@ -9427,17 +9427,17 @@ namespace {
 /**
  * Stub for LoadSheet(), since all we want is to get the sheet into
  * the CSSLoader's style cache
  */
 class StubCSSLoaderObserver final : public nsICSSLoaderObserver {
   ~StubCSSLoaderObserver() {}
 public:
   NS_IMETHOD
-  StyleSheetLoaded(StyleSheetHandle, bool, nsresult) override
+  StyleSheetLoaded(StyleSheet*, bool, nsresult) override
   {
     return NS_OK;
   }
   NS_DECL_ISUPPORTS
 };
 NS_IMPL_ISUPPORTS(StubCSSLoaderObserver, nsICSSLoaderObserver)
 
 } // namespace
@@ -9456,17 +9456,17 @@ nsDocument::PreloadStyle(nsIURI* uri, co
                          NS_LossyConvertUTF16toASCII(charset),
                          obs,
                          Element::StringToCORSMode(aCrossOriginAttr),
                          aReferrerPolicy, aIntegrity);
 }
 
 nsresult
 nsDocument::LoadChromeSheetSync(nsIURI* uri, bool isAgentSheet,
-                                mozilla::StyleSheetHandle::RefPtr* aSheet)
+                                RefPtr<mozilla::StyleSheet>* aSheet)
 {
   css::SheetParsingMode mode =
     isAgentSheet ? css::eAgentSheetFeatures
                  : css::eAuthorSheetFeatures;
   return CSSLoader()->LoadSheetSync(uri, mode, isAgentSheet, aSheet);
 }
 
 class nsDelayedEventDispatcher : public Runnable
@@ -9792,17 +9792,17 @@ nsIDocument::CreateStaticClone(nsIDocShe
       } else {
         clonedDoc->mOriginalDocument = this;
       }
 
       clonedDoc->mOriginalDocument->mStaticCloneCount++;
 
       int32_t sheetsCount = GetNumberOfStyleSheets();
       for (int32_t i = 0; i < sheetsCount; ++i) {
-        StyleSheetHandle::RefPtr sheet = GetStyleSheetAt(i);
+        RefPtr<StyleSheet> sheet = GetStyleSheetAt(i);
         if (sheet) {
           if (sheet->IsApplicable()) {
             // XXXheycam Need to make ServoStyleSheet cloning work.
             if (sheet->IsGecko()) {
               RefPtr<CSSStyleSheet> clonedSheet =
                 sheet->AsGecko()->Clone(nullptr, nullptr, clonedDoc, nullptr);
               NS_WARNING_ASSERTION(clonedSheet,
                                    "Cloning a stylesheet didn't work!");
@@ -9812,17 +9812,17 @@ nsIDocument::CreateStaticClone(nsIDocShe
             } else {
               NS_ERROR("stylo: ServoStyleSheet doesn't support cloning");
             }
           }
         }
       }
 
       // Iterate backwards to maintain order
-      for (StyleSheetHandle sheet : Reversed(thisAsDoc->mOnDemandBuiltInUASheets)) {
+      for (StyleSheet* sheet : Reversed(thisAsDoc->mOnDemandBuiltInUASheets)) {
         if (sheet) {
           if (sheet->IsApplicable()) {
             // XXXheycam Need to make ServoStyleSheet cloning work.
             if (sheet->IsGecko()) {
               RefPtr<CSSStyleSheet> clonedSheet =
                 sheet->AsGecko()->Clone(nullptr, nullptr, clonedDoc, nullptr);
               NS_WARNING_ASSERTION(clonedSheet,
                                    "Cloning a stylesheet didn't work!");
@@ -12004,17 +12004,17 @@ nsDocument::OnAppThemeChanged()
 {
   // Bail out if there is no theme support set up properly.
   auto themeOrigin = Preferences::GetString("b2g.theme.origin");
   if (!themeOrigin || !Preferences::GetBool("dom.mozApps.themable")) {
     return;
   }
 
   for (int32_t i = 0; i < GetNumberOfStyleSheets(); i++) {
-    StyleSheetHandle::RefPtr sheet = GetStyleSheetAt(i);
+    RefPtr<StyleSheet> sheet = GetStyleSheetAt(i);
     if (!sheet) {
       continue;
     }
 
     nsINode* owningNode = sheet->GetOwnerNode();
     if (!owningNode) {
       continue;
     }
@@ -12159,22 +12159,22 @@ nsIDocument::DocAddSizeOfExcludingThis(n
 void
 nsIDocument::DocAddSizeOfIncludingThis(nsWindowSizes* aWindowSizes) const
 {
   aWindowSizes->mDOMOtherSize += aWindowSizes->mMallocSizeOf(this);
   DocAddSizeOfExcludingThis(aWindowSizes);
 }
 
 static size_t
-SizeOfOwnedSheetArrayExcludingThis(const nsTArray<StyleSheetHandle::RefPtr>& aSheets,
+SizeOfOwnedSheetArrayExcludingThis(const nsTArray<RefPtr<StyleSheet>>& aSheets,
                                    MallocSizeOf aMallocSizeOf)
 {
   size_t n = 0;
   n += aSheets.ShallowSizeOfExcludingThis(aMallocSizeOf);
-  for (StyleSheetHandle sheet : aSheets) {
+  for (StyleSheet* sheet : aSheets) {
     if (!sheet->GetOwningDocument()) {
       // Avoid over-reporting shared sheets.
       continue;
     }
     n += sheet->SizeOfIncludingThis(aMallocSizeOf);
   }
   return n;
 }
--- a/dom/base/nsDocument.h
+++ b/dom/base/nsDocument.h
@@ -616,47 +616,47 @@ public:
       nsTArray<RefPtr<mozilla::dom::Animation>>& aAnimations) override;
 
   virtual nsresult SetSubDocumentFor(Element* aContent,
                                      nsIDocument* aSubDoc) override;
   virtual nsIDocument* GetSubDocumentFor(nsIContent* aContent) const override;
   virtual Element* FindContentForSubDocument(nsIDocument *aDocument) const override;
   virtual Element* GetRootElementInternal() const override;
 
-  virtual void EnsureOnDemandBuiltInUASheet(mozilla::StyleSheetHandle aSheet) override;
+  virtual void EnsureOnDemandBuiltInUASheet(mozilla::StyleSheet* aSheet) override;
 
   /**
    * Get the (document) style sheets owned by this document.
    * These are ordered, highest priority last
    */
   virtual int32_t GetNumberOfStyleSheets() const override;
-  virtual mozilla::StyleSheetHandle GetStyleSheetAt(int32_t aIndex) const override;
+  virtual mozilla::StyleSheet* GetStyleSheetAt(int32_t aIndex) const override;
   virtual int32_t GetIndexOfStyleSheet(
-      const mozilla::StyleSheetHandle aSheet) const override;
-  virtual void AddStyleSheet(mozilla::StyleSheetHandle aSheet) override;
-  virtual void RemoveStyleSheet(mozilla::StyleSheetHandle aSheet) override;
+      const mozilla::StyleSheet* aSheet) const override;
+  virtual void AddStyleSheet(mozilla::StyleSheet* aSheet) override;
+  virtual void RemoveStyleSheet(mozilla::StyleSheet* aSheet) override;
 
   virtual void UpdateStyleSheets(
-      nsTArray<mozilla::StyleSheetHandle::RefPtr>& aOldSheets,
-      nsTArray<mozilla::StyleSheetHandle::RefPtr>& aNewSheets) override;
-  virtual void AddStyleSheetToStyleSets(mozilla::StyleSheetHandle aSheet);
-  virtual void RemoveStyleSheetFromStyleSets(mozilla::StyleSheetHandle aSheet);
+      nsTArray<RefPtr<mozilla::StyleSheet>>& aOldSheets,
+      nsTArray<RefPtr<mozilla::StyleSheet>>& aNewSheets) override;
+  virtual void AddStyleSheetToStyleSets(mozilla::StyleSheet* aSheet);
+  virtual void RemoveStyleSheetFromStyleSets(mozilla::StyleSheet* aSheet);
 
-  virtual void InsertStyleSheetAt(mozilla::StyleSheetHandle aSheet,
+  virtual void InsertStyleSheetAt(mozilla::StyleSheet* aSheet,
                                   int32_t aIndex) override;
-  virtual void SetStyleSheetApplicableState(mozilla::StyleSheetHandle aSheet,
+  virtual void SetStyleSheetApplicableState(mozilla::StyleSheet* aSheet,
                                             bool aApplicable) override;
 
   virtual nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
                                             nsIURI* aSheetURI) override;
   virtual nsresult AddAdditionalStyleSheet(additionalSheetType aType,
-                                           mozilla::StyleSheetHandle aSheet) override;
+                                           mozilla::StyleSheet* aSheet) override;
   virtual void RemoveAdditionalStyleSheet(additionalSheetType aType,
                                           nsIURI* sheetURI) override;
-  virtual mozilla::StyleSheetHandle GetFirstAdditionalAuthorSheet() override;
+  virtual mozilla::StyleSheet* GetFirstAdditionalAuthorSheet() override;
 
   virtual nsIChannel* GetChannel() const override {
     return mChannel;
   }
 
   virtual nsIChannel* GetFailedChannel() const override {
     return mFailedChannel;
   }
@@ -706,21 +706,21 @@ public:
   virtual void SetReadyStateInternal(ReadyState rs) override;
 
   virtual void ContentStateChanged(nsIContent* aContent,
                                    mozilla::EventStates aStateMask)
                                      override;
   virtual void DocumentStatesChanged(
                  mozilla::EventStates aStateMask) override;
 
-  virtual void StyleRuleChanged(mozilla::StyleSheetHandle aStyleSheet,
+  virtual void StyleRuleChanged(mozilla::StyleSheet* aStyleSheet,
                                 mozilla::css::Rule* aStyleRule) override;
-  virtual void StyleRuleAdded(mozilla::StyleSheetHandle aStyleSheet,
+  virtual void StyleRuleAdded(mozilla::StyleSheet* aStyleSheet,
                               mozilla::css::Rule* aStyleRule) override;
-  virtual void StyleRuleRemoved(mozilla::StyleSheetHandle aStyleSheet,
+  virtual void StyleRuleRemoved(mozilla::StyleSheet* aStyleSheet,
                                 mozilla::css::Rule* aStyleRule) override;
 
   virtual void FlushPendingNotifications(mozFlushType aType) override;
   virtual void FlushExternalResources(mozFlushType aType) override;
   virtual void SetXMLDeclaration(const char16_t *aVersion,
                                  const char16_t *aEncoding,
                                  const int32_t aStandalone) override;
   virtual void GetXMLDeclaration(nsAString& aVersion,
@@ -782,17 +782,17 @@ public:
    * Called when an app-theme-changed observer notification is
    * received by this document.
    */
   void OnAppThemeChanged();
 
   void ReportUseCounters();
 
 private:
-  void AddOnDemandBuiltInUASheet(mozilla::StyleSheetHandle aSheet);
+  void AddOnDemandBuiltInUASheet(mozilla::StyleSheet* aSheet);
   nsRadioGroupStruct* GetRadioGroupInternal(const nsAString& aName) const;
   void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
 
 public:
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE_TO_NSINODE_OVERRIDABLE
 
   // nsIDOMDocument
@@ -965,17 +965,17 @@ public:
                                mozilla::CORSMode aCORSMode) override;
 
   virtual void PreloadStyle(nsIURI* uri, const nsAString& charset,
                             const nsAString& aCrossOriginAttr,
                             ReferrerPolicy aReferrerPolicy,
                             const nsAString& aIntegrity) override;
 
   virtual nsresult LoadChromeSheetSync(nsIURI* uri, bool isAgentSheet,
-                                       mozilla::StyleSheetHandle::RefPtr* aSheet) override;
+                                       RefPtr<mozilla::StyleSheet>* aSheet) override;
 
   virtual nsISupports* GetCurrentContentSink() override;
 
   virtual mozilla::EventStates GetDocumentState() override;
 
   // Only BlockOnload should call this!
   void AsyncBlockOnload();
 
@@ -1283,17 +1283,17 @@ public:
 
 protected:
   already_AddRefed<nsIPresShell> doCreateShell(nsPresContext* aContext,
                                                nsViewManager* aViewManager,
                                                mozilla::StyleSetHandle aStyleSet);
 
   void RemoveDocStyleSheetsFromStyleSets();
   void RemoveStyleSheetsFromStyleSets(
-      const nsTArray<mozilla::StyleSheetHandle::RefPtr>& aSheets,
+      const nsTArray<RefPtr<mozilla::StyleSheet>>& aSheets,
       mozilla::SheetType aType);
   void ResetStylesheetsToURI(nsIURI* aURI);
   void FillStyleSet(mozilla::StyleSetHandle aStyleSet);
 
   // Return whether all the presshells for this document are safe to flush
   bool IsSafeToFlush() const;
 
   void DispatchPageTransition(mozilla::dom::EventTarget* aDispatchTarget,
@@ -1337,19 +1337,19 @@ protected:
   // parsed into.
   nsCOMPtr<nsIParser> mParser;
 
   // Weak reference to our sink for in case we no longer have a parser.  This
   // will allow us to flush out any pending stuff from the sink even if
   // EndLoad() has already happened.
   nsWeakPtr mWeakSink;
 
-  nsTArray<mozilla::StyleSheetHandle::RefPtr> mStyleSheets;
-  nsTArray<mozilla::StyleSheetHandle::RefPtr> mOnDemandBuiltInUASheets;
-  nsTArray<mozilla::StyleSheetHandle::RefPtr> mAdditionalSheets[AdditionalSheetTypeCount];
+  nsTArray<RefPtr<mozilla::StyleSheet>> mStyleSheets;
+  nsTArray<RefPtr<mozilla::StyleSheet>> mOnDemandBuiltInUASheets;
+  nsTArray<RefPtr<mozilla::StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
 
   // Array of observers
   nsTObserverArray<nsIDocumentObserver*> mObservers;
 
   // Tracker for animations that are waiting to start.
   // nullptr until GetOrCreatePendingAnimationTracker is called.
   RefPtr<mozilla::PendingAnimationTracker> mPendingAnimationTracker;
 
@@ -1493,18 +1493,18 @@ public:
   mozilla::EventStates mDocumentState;
   mozilla::EventStates mGotDocumentState;
 
   RefPtr<nsDOMNavigationTiming> mTiming;
 private:
   friend class nsUnblockOnloadEvent;
   // Recomputes the visibility state but doesn't set the new value.
   mozilla::dom::VisibilityState GetVisibilityState() const;
-  void NotifyStyleSheetAdded(mozilla::StyleSheetHandle aSheet, bool aDocumentSheet);
-  void NotifyStyleSheetRemoved(mozilla::StyleSheetHandle aSheet, bool aDocumentSheet);
+  void NotifyStyleSheetAdded(mozilla::StyleSheet* aSheet, bool aDocumentSheet);
+  void NotifyStyleSheetRemoved(mozilla::StyleSheet* aSheet, bool aDocumentSheet);
 
   void PostUnblockOnloadEvent();
   void DoUnblockOnload();
 
   nsresult CheckFrameOptions();
   nsresult InitCSP(nsIChannel* aChannel);
 
   /**
--- a/dom/base/nsIDocument.h
+++ b/dom/base/nsIDocument.h
@@ -29,17 +29,17 @@
 #include "Units.h"
 #include "nsContentListDeclarations.h"
 #include "nsExpirationTracker.h"
 #include "nsClassHashtable.h"
 #include "prclist.h"
 #include "mozilla/UniquePtr.h"
 #include "mozilla/CORSMode.h"
 #include "mozilla/StyleBackendType.h"
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 #include <bitset>                        // for member
 
 #ifdef MOZILLA_INTERNAL_API
 #include "mozilla/dom/DocumentBinding.h"
 #else
 namespace mozilla {
 namespace dom {
 class ElementCreationOptionsOrString;
@@ -992,96 +992,96 @@ public:
    * This function prepends the given style sheet to the document's style set
    * in order to make sure that it does not override user-agent style sheets
    * supplied by add-ons or by the app (Firefox OS or Firefox Mobile, for
    * example), since their sheets should override built-in sheets.
    *
    * TODO We can get rid of the whole concept of delayed loading if we fix
    * bug 77999.
    */
-  virtual void EnsureOnDemandBuiltInUASheet(mozilla::StyleSheetHandle aSheet) = 0;
+  virtual void EnsureOnDemandBuiltInUASheet(mozilla::StyleSheet* aSheet) = 0;
 
   /**
    * Get the number of (document) stylesheets
    *
    * @return the number of stylesheets
    * @throws no exceptions
    */
   virtual int32_t GetNumberOfStyleSheets() const = 0;
 
   /**
    * Get a particular stylesheet
    * @param aIndex the index the stylesheet lives at.  This is zero-based
    * @return the stylesheet at aIndex.  Null if aIndex is out of range.
    * @throws no exceptions
    */
-  virtual mozilla::StyleSheetHandle GetStyleSheetAt(int32_t aIndex) const = 0;
+  virtual mozilla::StyleSheet* GetStyleSheetAt(int32_t aIndex) const = 0;
 
   /**
    * Insert a sheet at a particular spot in the stylesheet list (zero-based)
    * @param aSheet the sheet to insert
    * @param aIndex the index to insert at.  This index will be
    *   adjusted for the "special" sheets.
    * @throws no exceptions
    */
-  virtual void InsertStyleSheetAt(mozilla::StyleSheetHandle aSheet,
+  virtual void InsertStyleSheetAt(mozilla::StyleSheet* aSheet,
                                   int32_t aIndex) = 0;
 
   /**
    * Get the index of a particular stylesheet.  This will _always_
    * consider the "special" sheets as part of the sheet list.
    * @param aSheet the sheet to get the index of
    * @return aIndex the index of the sheet in the full list
    */
   virtual int32_t GetIndexOfStyleSheet(
-      const mozilla::StyleSheetHandle aSheet) const = 0;
+      const mozilla::StyleSheet* aSheet) const = 0;
 
   /**
    * Replace the stylesheets in aOldSheets with the stylesheets in
    * aNewSheets. The two lists must have equal length, and the sheet
    * at positon J in the first list will be replaced by the sheet at
    * position J in the second list.  Some sheets in the second list
    * may be null; if so the corresponding sheets in the first list
    * will simply be removed.
    */
   virtual void UpdateStyleSheets(
-      nsTArray<mozilla::StyleSheetHandle::RefPtr>& aOldSheets,
-      nsTArray<mozilla::StyleSheetHandle::RefPtr>& aNewSheets) = 0;
+      nsTArray<RefPtr<mozilla::StyleSheet>>& aOldSheets,
+      nsTArray<RefPtr<mozilla::StyleSheet>>& aNewSheets) = 0;
 
   /**
    * Add a stylesheet to the document
    */
-  virtual void AddStyleSheet(mozilla::StyleSheetHandle aSheet) = 0;
+  virtual void AddStyleSheet(mozilla::StyleSheet* aSheet) = 0;
 
   /**
    * Remove a stylesheet from the document
    */
-  virtual void RemoveStyleSheet(mozilla::StyleSheetHandle aSheet) = 0;
+  virtual void RemoveStyleSheet(mozilla::StyleSheet* aSheet) = 0;
 
   /**
    * Notify the document that the applicable state of the sheet changed
    * and that observers should be notified and style sets updated
    */
-  virtual void SetStyleSheetApplicableState(mozilla::StyleSheetHandle aSheet,
+  virtual void SetStyleSheetApplicableState(mozilla::StyleSheet* aSheet,
                                             bool aApplicable) = 0;
 
   enum additionalSheetType {
     eAgentSheet,
     eUserSheet,
     eAuthorSheet,
     AdditionalSheetTypeCount
   };
 
   virtual nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
                                             nsIURI* aSheetURI) = 0;
   virtual nsresult AddAdditionalStyleSheet(additionalSheetType aType,
-                                           mozilla::StyleSheetHandle aSheet) = 0;
+                                           mozilla::StyleSheet* aSheet) = 0;
   virtual void RemoveAdditionalStyleSheet(additionalSheetType aType,
                                           nsIURI* sheetURI) = 0;
-  virtual mozilla::StyleSheetHandle GetFirstAdditionalAuthorSheet() = 0;
+  virtual mozilla::StyleSheet* GetFirstAdditionalAuthorSheet() = 0;
 
   /**
    * Assuming that aDocSheets is an array of document-level style
    * sheets for this document, returns the index that aSheet should
    * be inserted at to maintain document ordering.
    *
    * Defined in nsIDocumentInlines.h.
    */
@@ -1392,21 +1392,21 @@ public:
 
   // Notify that a document state has changed.
   // This should only be called by callers whose state is also reflected in the
   // implementation of nsDocument::GetDocumentState.
   virtual void DocumentStatesChanged(mozilla::EventStates aStateMask) = 0;
 
   // Observation hooks for style data to propagate notifications
   // to document observers
-  virtual void StyleRuleChanged(mozilla::StyleSheetHandle aStyleSheet,
+  virtual void StyleRuleChanged(mozilla::StyleSheet* aStyleSheet,
                                 mozilla::css::Rule* aStyleRule) = 0;
-  virtual void StyleRuleAdded(mozilla::StyleSheetHandle aStyleSheet,
+  virtual void StyleRuleAdded(mozilla::StyleSheet* aStyleSheet,
                               mozilla::css::Rule* aStyleRule) = 0;
-  virtual void StyleRuleRemoved(mozilla::StyleSheetHandle aStyleSheet,
+  virtual void StyleRuleRemoved(mozilla::StyleSheet* aStyleSheet,
                                 mozilla::css::Rule* aStyleRule) = 0;
 
   /**
    * Flush notifications for this document and its parent documents
    * (since those may affect the layout of this one).
    */
   virtual void FlushPendingNotifications(mozFlushType aType) = 0;
 
@@ -2204,17 +2204,17 @@ public:
    * Called by the chrome registry to load style sheets.  Can be put
    * back there if and when when that module is merged with libgklayout.
    *
    * This always does a synchronous load.  If aIsAgentSheet is true,
    * it also uses the system principal and enables unsafe rules.
    * DO NOT USE FOR UNTRUSTED CONTENT.
    */
   virtual nsresult LoadChromeSheetSync(nsIURI* aURI, bool aIsAgentSheet,
-                                       mozilla::StyleSheetHandle::RefPtr* aSheet) = 0;
+                                       RefPtr<mozilla::StyleSheet>* aSheet) = 0;
 
   /**
    * Returns true if the locale used for the document specifies a direction of
    * right to left. For chrome documents, this comes from the chrome registry.
    * This is used to determine the current state for the :-moz-locale-dir pseudoclass
    * so once can know whether a document is expected to be rendered left-to-right
    * or right-to-left.
    */
--- a/dom/base/nsIDocumentInlines.h
+++ b/dom/base/nsIDocumentInlines.h
@@ -30,17 +30,17 @@ nsIDocument::FindDocStyleSheetInsertionP
   int32_t count = aDocSheets.Length();
   int32_t index;
   for (index = 0; index < count; index++) {
     T* sheet = aDocSheets[index];
     int32_t sheetDocIndex = GetIndexOfStyleSheet(sheet);
     if (sheetDocIndex > newDocIndex)
       break;
 
-    mozilla::StyleSheetHandle sheetHandle = sheet;
+    mozilla::StyleSheet* sheetHandle = sheet;
 
     // If the sheet is not owned by the document it can be an author
     // sheet registered at nsStyleSheetService or an additional author
     // sheet on the document, which means the new
     // doc sheet should end up before it.
     if (sheetDocIndex < 0) {
       if (sheetService) {
         auto& authorSheets = *sheetService->AuthorStyleSheets();
--- a/dom/base/nsIDocumentObserver.h
+++ b/dom/base/nsIDocumentObserver.h
@@ -2,17 +2,17 @@
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsIDocumentObserver_h___
 #define nsIDocumentObserver_h___
 
 #include "mozilla/EventStates.h"
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 #include "nsISupports.h"
 #include "nsIMutationObserver.h"
 
 class nsIContent;
 class nsIDocument;
 
 namespace mozilla {
 namespace css {
@@ -95,75 +95,75 @@ public:
    * called automatically when a StyleSheet gets added to the
    * document, even if the stylesheet is not applicable. The
    * notification is passed on to all of the document observers.
    *
    * @param aStyleSheet the StyleSheet that has been added
    * @param aDocumentSheet True if sheet is in document's style sheet list,
    *                       false if sheet is not (i.e., UA or user sheet)
    */
-  virtual void StyleSheetAdded(mozilla::StyleSheetHandle aStyleSheet,
+  virtual void StyleSheetAdded(mozilla::StyleSheet* aStyleSheet,
                                bool aDocumentSheet) = 0;
 
   /**
    * A StyleSheet has just been removed from the document.  This
    * method is called automatically when a StyleSheet gets removed
    * from the document, even if the stylesheet is not applicable. The
    * notification is passed on to all of the document observers.
    *
    * @param aStyleSheet the StyleSheet that has been removed
    * @param aDocumentSheet True if sheet is in document's style sheet list,
    *                       false if sheet is not (i.e., UA or user sheet)
    */
-  virtual void StyleSheetRemoved(mozilla::StyleSheetHandle aStyleSheet,
+  virtual void StyleSheetRemoved(mozilla::StyleSheet* aStyleSheet,
                                  bool aDocumentSheet) = 0;
   
   /**
    * A StyleSheet has just changed its applicable state.
    * This method is called automatically when the applicable state
    * of a StyleSheet gets changed. The style sheet passes this
    * notification to the document. The notification is passed on 
    * to all of the document observers.
    *
    * @param aStyleSheet the StyleSheet that has changed state
    */
-  virtual void StyleSheetApplicableStateChanged(mozilla::StyleSheetHandle aStyleSheet) = 0;
+  virtual void StyleSheetApplicableStateChanged(mozilla::StyleSheet* aStyleSheet) = 0;
 
   /**
    * A StyleRule has just been modified within a style sheet.
    * This method is called automatically when the rule gets
    * modified. The style sheet passes this notification to 
    * the document. The notification is passed on to all of 
    * the document observers.
    *
    * @param aStyleSheet the StyleSheet that contians the rule
    */
-  virtual void StyleRuleChanged(mozilla::StyleSheetHandle aStyleSheet) = 0;
+  virtual void StyleRuleChanged(mozilla::StyleSheet* aStyleSheet) = 0;
 
   /**
    * A StyleRule has just been added to a style sheet.
    * This method is called automatically when the rule gets
    * added to the sheet. The style sheet passes this
    * notification to the document. The notification is passed on 
    * to all of the document observers.
    *
    * @param aStyleSheet the StyleSheet that has been modified
    */
-  virtual void StyleRuleAdded(mozilla::StyleSheetHandle aStyleSheet) = 0;
+  virtual void StyleRuleAdded(mozilla::StyleSheet* aStyleSheet) = 0;
 
   /**
    * A StyleRule has just been removed from a style sheet.
    * This method is called automatically when the rule gets
    * removed from the sheet. The style sheet passes this
    * notification to the document. The notification is passed on 
    * to all of the document observers.
    *
    * @param aStyleSheet the StyleSheet that has been modified
    */
-  virtual void StyleRuleRemoved(mozilla::StyleSheetHandle aStyleSheet) = 0;
+  virtual void StyleRuleRemoved(mozilla::StyleSheet* aStyleSheet) = 0;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsIDocumentObserver, NS_IDOCUMENT_OBSERVER_IID)
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_BEGINUPDATE                              \
     virtual void BeginUpdate(nsIDocument* aDocument,                         \
                              nsUpdateType aUpdateType) override;
 
@@ -181,35 +181,35 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsIDocumen
                                      nsIContent* aContent,                   \
                                      mozilla::EventStates aStateMask) override;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_DOCUMENTSTATESCHANGED                    \
     virtual void DocumentStatesChanged(nsIDocument* aDocument,               \
                                        mozilla::EventStates aStateMask) override;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLESHEETADDED                          \
-    virtual void StyleSheetAdded(mozilla::StyleSheetHandle aStyleSheet,      \
+    virtual void StyleSheetAdded(mozilla::StyleSheet* aStyleSheet,           \
                                  bool aDocumentSheet) override;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLESHEETREMOVED                        \
-    virtual void StyleSheetRemoved(mozilla::StyleSheetHandle aStyleSheet,    \
+    virtual void StyleSheetRemoved(mozilla::StyleSheet* aStyleSheet,         \
                                    bool aDocumentSheet) override;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLESHEETAPPLICABLESTATECHANGED         \
     virtual void StyleSheetApplicableStateChanged(                           \
-        mozilla::StyleSheetHandle aStyleSheet) override;
+        mozilla::StyleSheet* aStyleSheet) override;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLERULECHANGED                         \
-    virtual void StyleRuleChanged(mozilla::StyleSheetHandle aStyleSheet) override;
+    virtual void StyleRuleChanged(mozilla::StyleSheet* aStyleSheet) override;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLERULEADDED                           \
-    virtual void StyleRuleAdded(mozilla::StyleSheetHandle aStyleSheet) override;
+    virtual void StyleRuleAdded(mozilla::StyleSheet* aStyleSheet) override;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER_STYLERULEREMOVED                         \
-    virtual void StyleRuleRemoved(mozilla::StyleSheetHandle aStyleSheet) override;
+    virtual void StyleRuleRemoved(mozilla::StyleSheet* aStyleSheet) override;
 
 #define NS_DECL_NSIDOCUMENTOBSERVER                                          \
     NS_DECL_NSIDOCUMENTOBSERVER_BEGINUPDATE                                  \
     NS_DECL_NSIDOCUMENTOBSERVER_ENDUPDATE                                    \
     NS_DECL_NSIDOCUMENTOBSERVER_BEGINLOAD                                    \
     NS_DECL_NSIDOCUMENTOBSERVER_ENDLOAD                                      \
     NS_DECL_NSIDOCUMENTOBSERVER_CONTENTSTATECHANGED                          \
     NS_DECL_NSIDOCUMENTOBSERVER_DOCUMENTSTATESCHANGED                        \
@@ -257,35 +257,35 @@ void                                    
 {                                                                         \
 }
 
 #define NS_IMPL_NSIDOCUMENTOBSERVER_CONTENT(_class)                       \
 NS_IMPL_NSIMUTATIONOBSERVER_CONTENT(_class)
 
 #define NS_IMPL_NSIDOCUMENTOBSERVER_STYLE_STUB(_class)                    \
 void                                                                      \
-_class::StyleSheetAdded(mozilla::StyleSheetHandle aStyleSheet,            \
+_class::StyleSheetAdded(mozilla::StyleSheet* aStyleSheet,                 \
                         bool aDocumentSheet)                              \
 {                                                                         \
 }                                                                         \
 void                                                                      \
-_class::StyleSheetRemoved(mozilla::StyleSheetHandle aStyleSheet,          \
+_class::StyleSheetRemoved(mozilla::StyleSheet* aStyleSheet,               \
                           bool aDocumentSheet)                            \
 {                                                                         \
 }                                                                         \
 void                                                                      \
-_class::StyleSheetApplicableStateChanged(mozilla::StyleSheetHandle aStyleSheet) \
+_class::StyleSheetApplicableStateChanged(mozilla::StyleSheet* aStyleSheet)\
 {                                                                         \
 }                                                                         \
 void                                                                      \
-_class::StyleRuleChanged(mozilla::StyleSheetHandle aStyleSheet)           \
+_class::StyleRuleChanged(mozilla::StyleSheet* aStyleSheet)                \
 {                                                                         \
 }                                                                         \
 void                                                                      \
-_class::StyleRuleAdded(mozilla::StyleSheetHandle aStyleSheet)             \
+_class::StyleRuleAdded(mozilla::StyleSheet* aStyleSheet)                  \
 {                                                                         \
 }                                                                         \
 void                                                                      \
-_class::StyleRuleRemoved(mozilla::StyleSheetHandle aStyleSheet)           \
+_class::StyleRuleRemoved(mozilla::StyleSheet* aStyleSheet)                \
 {                                                                         \
 }
 
 #endif /* nsIDocumentObserver_h___ */
--- a/dom/base/nsIStyleSheetLinkingElement.h
+++ b/dom/base/nsIStyleSheetLinkingElement.h
@@ -3,17 +3,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsIStyleSheetLinkingElement_h__
 #define nsIStyleSheetLinkingElement_h__
 
 
 #include "nsISupports.h"
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 
 class nsICSSLoaderObserver;
 class nsIURI;
 
 #define NS_ISTYLESHEETLINKINGELEMENT_IID          \
 { 0xa8b79f3b, 0x9d18, 0x4f9c, \
   { 0xb1, 0xaa, 0x8c, 0x9b, 0x1b, 0xaa, 0xac, 0xad } }
 
@@ -23,24 +23,24 @@ public:
 
   /**
    * Used to make the association between a style sheet and
    * the element that linked it to the document.
    *
    * @param aStyleSheet the style sheet associated with this
    *                    element.
    */
-  NS_IMETHOD SetStyleSheet(mozilla::StyleSheetHandle aStyleSheet) = 0;
+  NS_IMETHOD SetStyleSheet(mozilla::StyleSheet* aStyleSheet) = 0;
 
   /**
    * Used to obtain the style sheet linked in by this element.
    *
    * @return the style sheet associated with this element.
    */
-  NS_IMETHOD_(mozilla::StyleSheetHandle) GetStyleSheet() = 0;
+  NS_IMETHOD_(mozilla::StyleSheet*) GetStyleSheet() = 0;
 
   /**
    * Initialize the stylesheet linking element. If aDontLoadStyle is
    * true the element will ignore the first modification to the
    * element that would cause a stylesheet to be loaded. Subsequent
    * modifications to the element will not be ignored.
    */
   NS_IMETHOD InitStyleLinkElement(bool aDontLoadStyle) = 0;
--- a/dom/base/nsStyleLinkElement.cpp
+++ b/dom/base/nsStyleLinkElement.cpp
@@ -7,18 +7,18 @@
 /*
  * A base class which implements nsIStyleSheetLinkingElement and can
  * be subclassed by various content nodes that want to load
  * stylesheets (<style>, <link>, processing instructions, etc).
  */
 
 #include "nsStyleLinkElement.h"
 
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/css/Loader.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/FragmentOrElement.h"
 #include "mozilla/dom/HTMLLinkElement.h"
 #include "mozilla/dom/ShadowRoot.h"
 #include "mozilla/dom/SRILogHelper.h"
 #include "mozilla/Preferences.h"
 #include "nsIContent.h"
@@ -58,34 +58,34 @@ nsStyleLinkElement::Unlink()
 void
 nsStyleLinkElement::Traverse(nsCycleCollectionTraversalCallback &cb)
 {
   nsStyleLinkElement* tmp = this;
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyleSheet);
 }
 
 NS_IMETHODIMP 
-nsStyleLinkElement::SetStyleSheet(StyleSheetHandle aStyleSheet)
+nsStyleLinkElement::SetStyleSheet(StyleSheet* aStyleSheet)
 {
   if (mStyleSheet) {
     mStyleSheet->SetOwningNode(nullptr);
   }
 
   mStyleSheet = aStyleSheet;
   if (mStyleSheet) {
     nsCOMPtr<nsINode> node = do_QueryObject(this);
     if (node) {
       mStyleSheet->SetOwningNode(node);
     }
   }
     
   return NS_OK;
 }
 
-NS_IMETHODIMP_(StyleSheetHandle)
+NS_IMETHODIMP_(StyleSheet*)
 nsStyleLinkElement::GetStyleSheet()
 {
   return mStyleSheet;
 }
 
 NS_IMETHODIMP 
 nsStyleLinkElement::InitStyleLinkElement(bool aDontLoadStyle)
 {
--- a/dom/base/nsStyleLinkElement.h
+++ b/dom/base/nsStyleLinkElement.h
@@ -10,17 +10,17 @@
  * stylesheets (<style>, <link>, processing instructions, etc).
  */
 
 #ifndef nsStyleLinkElement_h___
 #define nsStyleLinkElement_h___
 
 #include "mozilla/Attributes.h"
 #include "mozilla/CORSMode.h"
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/net/ReferrerPolicy.h"
 #include "nsCOMPtr.h"
 #include "nsIStyleSheetLinkingElement.h"
 #include "nsTArray.h"
 
 class nsIDocument;
 class nsIURI;
 
@@ -45,18 +45,18 @@ public:
     // exposing them to script.
     NS_ASSERTION(!mStyleSheet || mStyleSheet->IsGecko(),
                  "stylo: ServoStyleSheets can't be exposed to script yet");
     return mStyleSheet && mStyleSheet->IsGecko() ? mStyleSheet->AsGecko() :
                                                    nullptr;
   }
 
   // nsIStyleSheetLinkingElement  
-  NS_IMETHOD SetStyleSheet(mozilla::StyleSheetHandle aStyleSheet) override;
-  NS_IMETHOD_(mozilla::StyleSheetHandle) GetStyleSheet() override;
+  NS_IMETHOD SetStyleSheet(mozilla::StyleSheet* aStyleSheet) override;
+  NS_IMETHOD_(mozilla::StyleSheet*) GetStyleSheet() override;
   NS_IMETHOD InitStyleLinkElement(bool aDontLoadStyle) override;
   NS_IMETHOD UpdateStyleSheet(nsICSSLoaderObserver* aObserver,
                               bool* aWillNotify,
                               bool* aIsAlternate,
                               bool aForceReload) override;
   NS_IMETHOD SetEnableUpdates(bool aEnableUpdates) override;
   NS_IMETHOD GetCharset(nsAString& aCharset) override;
 
@@ -138,17 +138,17 @@ private:
    */
   nsresult DoUpdateStyleSheet(nsIDocument* aOldDocument,
                               mozilla::dom::ShadowRoot* aOldShadowRoot,
                               nsICSSLoaderObserver* aObserver,
                               bool* aWillNotify,
                               bool* aIsAlternate,
                               bool aForceUpdate);
 
-  mozilla::StyleSheetHandle::RefPtr mStyleSheet;
+  RefPtr<mozilla::StyleSheet> mStyleSheet;
 protected:
   bool mDontLoadStyle;
   bool mUpdatesEnabled;
   uint32_t mLineNumber;
 };
 
 #endif /* nsStyleLinkElement_h___ */
 
--- a/dom/base/nsTreeSanitizer.cpp
+++ b/dom/base/nsTreeSanitizer.cpp
@@ -2,17 +2,17 @@
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsTreeSanitizer.h"
 
 #include "mozilla/ArrayUtils.h"
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/css/Declaration.h"
 #include "mozilla/css/StyleRule.h"
 #include "mozilla/css/Rule.h"
 #include "nsCSSParser.h"
 #include "nsCSSPropertyID.h"
 #include "nsUnicharInputStream.h"
 #include "nsIDOMCSSRule.h"
 #include "nsAttrName.h"
--- a/dom/fetch/FetchDriver.h
+++ b/dom/fetch/FetchDriver.h
@@ -7,17 +7,17 @@
 #ifndef mozilla_dom_FetchDriver_h
 #define mozilla_dom_FetchDriver_h
 
 #include "nsIChannelEventSink.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIStreamListener.h"
 #include "nsIThreadRetargetableStreamListener.h"
 #include "mozilla/ConsoleReportCollector.h"
-#include "mozilla/dom/SRICheck.h"
+#include "mozilla/dom/SRIMetadata.h"
 #include "mozilla/RefPtr.h"
 
 #include "mozilla/DebugOnly.h"
 #include "mozilla/net/ReferrerPolicy.h"
 
 class nsIConsoleReportCollector;
 class nsIDocument;
 class nsIOutputStream;
--- a/dom/html/nsHTMLDocument.cpp
+++ b/dom/html/nsHTMLDocument.cpp
@@ -109,18 +109,18 @@
 #include "mozilla/dom/HTMLDocumentBinding.h"
 #include "nsCharsetSource.h"
 #include "nsIStringBundle.h"
 #include "nsDOMClassInfo.h"
 #include "nsFocusManager.h"
 #include "nsIFrame.h"
 #include "nsIContent.h"
 #include "nsLayoutStylesheetCache.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 #define NS_MAX_DOCUMENT_WRITE_DEPTH 20
 
 #include "prtime.h"
 
@@ -2545,17 +2545,17 @@ nsHTMLDocument::TearingDownEditor(nsIEdi
   if (IsEditingOn()) {
     EditingState oldState = mEditingState;
     mEditingState = eTearingDown;
 
     nsCOMPtr<nsIPresShell> presShell = GetShell();
     if (!presShell)
       return;
 
-    nsTArray<StyleSheetHandle::RefPtr> agentSheets;
+    nsTArray<RefPtr<StyleSheet>> agentSheets;
     presShell->GetAgentStyleSheets(agentSheets);
 
     auto cache = nsLayoutStylesheetCache::For(GetStyleBackendType());
 
     agentSheets.RemoveElement(cache->ContentEditableSheet());
     if (oldState == eDesignMode)
       agentSheets.RemoveElement(cache->DesignModeSheet());
 
@@ -2688,34 +2688,34 @@ nsHTMLDocument::EditingStateChanged()
     nsAutoEditingState push(this, eSettingUp);
 
     nsCOMPtr<nsIPresShell> presShell = GetShell();
     NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
 
     // Before making this window editable, we need to modify UA style sheet
     // because new style may change whether focused element will be focusable
     // or not.
-    nsTArray<StyleSheetHandle::RefPtr> agentSheets;
+    nsTArray<RefPtr<StyleSheet>> agentSheets;
     rv = presShell->GetAgentStyleSheets(agentSheets);
     NS_ENSURE_SUCCESS(rv, rv);
 
     auto cache = nsLayoutStylesheetCache::For(GetStyleBackendType());
 
-    StyleSheetHandle contentEditableSheet = cache->ContentEditableSheet();
+    StyleSheet* contentEditableSheet = cache->ContentEditableSheet();
 
     if (!agentSheets.Contains(contentEditableSheet)) {
       agentSheets.AppendElement(contentEditableSheet);
     }
 
     // Should we update the editable state of all the nodes in the document? We
     // need to do this when the designMode value changes, as that overrides
     // specific states on the elements.
     if (designMode) {
       // designMode is being turned on (overrides contentEditable).
-      StyleSheetHandle designModeSheet = cache->DesignModeSheet();
+      StyleSheet* designModeSheet = cache->DesignModeSheet();
       if (!agentSheets.Contains(designModeSheet)) {
         agentSheets.AppendElement(designModeSheet);
       }
 
       updateState = true;
       spellRecheckAll = oldState == eContentEditable;
     }
     else if (oldState == eDesignMode) {
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -30,17 +30,17 @@
 #include "CrashReporterParent.h"
 #include "DeviceStorageStatics.h"
 #include "GMPServiceParent.h"
 #include "HandlerServiceParent.h"
 #include "IHistory.h"
 #include "imgIContainer.h"
 #include "mozIApplication.h"
 #include "mozilla/ClearOnShutdown.h"
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/DataStorage.h"
 #include "mozilla/devtools/HeapSnapshotTempFileHelperParent.h"
 #include "mozilla/docshell/OfflineCacheUpdateParent.h"
 #include "mozilla/dom/DataTransfer.h"
 #include "mozilla/dom/DOMStorageIPC.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/File.h"
 #include "mozilla/dom/ExternalHelperAppParent.h"
@@ -182,18 +182,18 @@
 #include "prio.h"
 #include "private/pprio.h"
 #include "ContentProcessManager.h"
 #include "mozilla/dom/ipc/StructuredCloneData.h"
 #include "mozilla/psm/PSMContentListener.h"
 #include "nsPluginHost.h"
 #include "nsPluginTags.h"
 #include "nsIBlocklistService.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "nsHostObjectProtocolHandler.h"
 
 #include "nsIBidiKeyboard.h"
 
 #ifdef MOZ_WEBRTC
 #include "signaling/src/peerconnection/WebrtcGlobalParent.h"
 #endif
 
@@ -2262,29 +2262,29 @@ ContentParent::InitInternal(ProcessPrior
     Unused << SendAppInit();
   }
 
   nsStyleSheetService *sheetService = nsStyleSheetService::GetInstance();
   if (sheetService) {
     // This looks like a lot of work, but in a normal browser session we just
     // send two loads.
 
-    for (StyleSheetHandle sheet : *sheetService->AgentStyleSheets()) {
+    for (StyleSheet* sheet : *sheetService->AgentStyleSheets()) {
       URIParams uri;
       SerializeURI(sheet->GetSheetURI(), uri);
       Unused << SendLoadAndRegisterSheet(uri, nsIStyleSheetService::AGENT_SHEET);
     }
 
-    for (StyleSheetHandle sheet : *sheetService->UserStyleSheets()) {
+    for (StyleSheet* sheet : *sheetService->UserStyleSheets()) {
       URIParams uri;
       SerializeURI(sheet->GetSheetURI(), uri);
       Unused << SendLoadAndRegisterSheet(uri, nsIStyleSheetService::USER_SHEET);
     }
 
-    for (StyleSheetHandle sheet : *sheetService->AuthorStyleSheets()) {
+    for (StyleSheet* sheet : *sheetService->AuthorStyleSheets()) {
       URIParams uri;
       SerializeURI(sheet->GetSheetURI(), uri);
       Unused << SendLoadAndRegisterSheet(uri, nsIStyleSheetService::AUTHOR_SHEET);
     }
   }
 
 #ifdef MOZ_CONTENT_SANDBOX
   bool shouldSandbox = true;
--- a/dom/media/ipc/VideoDecoderManagerChild.cpp
+++ b/dom/media/ipc/VideoDecoderManagerChild.cpp
@@ -47,19 +47,19 @@ VideoDecoderManagerChild::Initialize()
       AbstractThread::CreateXPCOMThreadWrapper(childThread, false);
   }
 
   Endpoint<PVideoDecoderManagerChild> endpoint;
   if (!ContentChild::GetSingleton()->SendInitVideoDecoderManager(&endpoint)) {
     return;
   }
 
-  // TODO: The above message should return an empty endpoint if there wasn't a GPU
-  // process. Unfortunately IPDL will assert in this case, so it can't actually
-  // happen. Bug 1302009 is filed for fixing this.
+  if (!endpoint.IsValid()) {
+    return;
+  }
 
   sDecoderManager = new VideoDecoderManagerChild();
 
   RefPtr<Runnable> task = NewRunnableMethod<Endpoint<PVideoDecoderManagerChild>&&>(
     sDecoderManager, &VideoDecoderManagerChild::Open, Move(endpoint));
   sVideoDecoderChildThread->Dispatch(task.forget(), NS_DISPATCH_NORMAL);
 #else
   return;
--- a/dom/security/SRICheck.cpp
+++ b/dom/security/SRICheck.cpp
@@ -6,16 +6,17 @@
 
 #include "SRICheck.h"
 
 #include "mozilla/Base64.h"
 #include "mozilla/LoadTainting.h"
 #include "mozilla/Logging.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/SRILogHelper.h"
+#include "mozilla/dom/SRIMetadata.h"
 #include "nsContentUtils.h"
 #include "nsIChannel.h"
 #include "nsIConsoleReportCollector.h"
 #include "nsIProtocolHandler.h"
 #include "nsIScriptError.h"
 #include "nsIIncrementalStreamLoader.h"
 #include "nsIUnicharStreamLoader.h"
 #include "nsIURI.h"
--- a/dom/security/SRICheck.h
+++ b/dom/security/SRICheck.h
@@ -4,25 +4,26 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_SRICheck_h
 #define mozilla_dom_SRICheck_h
 
 #include "nsCOMPtr.h"
 #include "nsICryptoHash.h"
-#include "SRIMetadata.h"
 
 class nsIChannel;
 class nsIUnicharStreamLoader;
 class nsIConsoleReportCollector;
 
 namespace mozilla {
 namespace dom {
 
+class SRIMetadata;
+
 class SRICheck final
 {
 public:
   static const uint32_t MAX_METADATA_LENGTH = 24*1024;
   static const uint32_t MAX_METADATA_TOKENS = 512;
 
   /**
    * Parse the multiple hashes specified in the integrity attribute and
--- a/dom/svg/SVGDocument.cpp
+++ b/dom/svg/SVGDocument.cpp
@@ -15,18 +15,18 @@
 #include "nsNetUtil.h"
 #include "nsServiceManagerUtils.h"
 #include "nsString.h"
 #include "nsLiteralString.h"
 #include "nsIDOMSVGElement.h"
 #include "mozilla/dom/Element.h"
 #include "nsSVGElement.h"
 #include "mozilla/dom/SVGDocumentBinding.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 using namespace mozilla::css;
 using namespace mozilla::dom;
 
 namespace mozilla {
 namespace dom {
 
 //----------------------------------------------------------------------
@@ -152,33 +152,33 @@ SVGDocument::EnsureNonSVGUserAgentStyleS
           catMan->GetCategoryEntry("agent-style-sheets", name.get(),
                                    getter_Copies(spec));
 
           mozilla::css::Loader* cssLoader = CSSLoader();
           if (cssLoader->GetEnabled()) {
             nsCOMPtr<nsIURI> uri;
             NS_NewURI(getter_AddRefs(uri), spec);
             if (uri) {
-              StyleSheetHandle::RefPtr sheet;
+              RefPtr<StyleSheet> sheet;
               cssLoader->LoadSheetSync(uri,
                                        mozilla::css::eAgentSheetFeatures,
                                        true, &sheet);
               if (sheet) {
                 EnsureOnDemandBuiltInUASheet(sheet);
               }
             }
           }
         }
       }
     }
   }
 
   auto cache = nsLayoutStylesheetCache::For(GetStyleBackendType());
 
-  StyleSheetHandle sheet = cache->NumberControlSheet();
+  StyleSheet* sheet = cache->NumberControlSheet();
   if (sheet) {
     // number-control.css can be behind a pref
     EnsureOnDemandBuiltInUASheet(sheet);
   }
   EnsureOnDemandBuiltInUASheet(cache->FormsSheet());
   EnsureOnDemandBuiltInUASheet(cache->CounterStylesSheet());
   EnsureOnDemandBuiltInUASheet(cache->HTMLSheet());
   if (nsLayoutUtils::ShouldUseNoFramesSheet(this)) {
--- a/dom/xbl/nsBindingManager.cpp
+++ b/dom/xbl/nsBindingManager.cpp
@@ -765,17 +765,17 @@ nsBindingManager::MediumFeaturesChanged(
     bool thisChanged = ruleProcessor->MediumFeaturesChanged(aPresContext);
     *aRulesChanged = *aRulesChanged || thisChanged;
   }
 
   return NS_OK;
 }
 
 void
-nsBindingManager::AppendAllSheets(nsTArray<StyleSheetHandle>& aArray)
+nsBindingManager::AppendAllSheets(nsTArray<StyleSheet*>& aArray)
 {
   if (!mBoundContentSet) {
     return;
   }
 
   for (auto iter = mBoundContentSet->Iter(); !iter.Done(); iter.Next()) {
     nsIContent* boundContent = iter.Get()->GetKey();
     for (nsXBLBinding* binding = boundContent->GetXBLBinding(); binding;
--- a/dom/xbl/nsBindingManager.h
+++ b/dom/xbl/nsBindingManager.h
@@ -13,17 +13,17 @@
 #include "nsHashKeys.h"
 #include "nsInterfaceHashtable.h"
 #include "nsRefPtrHashtable.h"
 #include "nsURIHashKey.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsXBLBinding.h"
 #include "nsTArray.h"
 #include "nsThreadUtils.h"
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 
 struct ElementDependentRuleProcessorData;
 class nsIXPConnectWrappedJS;
 class nsIAtom;
 class nsIDOMNodeList;
 class nsIDocument;
 class nsIURI;
 class nsXBLDocumentInfo;
@@ -133,17 +133,17 @@ public:
   /**
    * Do any processing that needs to happen as a result of a change in
    * the characteristics of the medium, and return whether this rule
    * processor's rules have changed (e.g., because of media queries).
    */
   nsresult MediumFeaturesChanged(nsPresContext* aPresContext,
                                  bool* aRulesChanged);
 
-  void AppendAllSheets(nsTArray<mozilla::StyleSheetHandle>& aArray);
+  void AppendAllSheets(nsTArray<mozilla::StyleSheet*>& aArray);
 
   void Traverse(nsIContent *aContent,
                             nsCycleCollectionTraversalCallback &cb);
 
   NS_DECL_CYCLE_COLLECTION_CLASS(nsBindingManager)
 
   // Notify the binding manager when an outermost update begins and
   // ends.  The end method can execute script.
--- a/dom/xbl/nsXBLPrototypeBinding.cpp
+++ b/dom/xbl/nsXBLPrototypeBinding.cpp
@@ -39,18 +39,18 @@
 #include "nsIScriptError.h"
 
 #include "nsCSSRuleProcessor.h"
 #include "nsXBLResourceLoader.h"
 #include "mozilla/AddonPathService.h"
 #include "mozilla/dom/CDATASection.h"
 #include "mozilla/dom/Comment.h"
 #include "mozilla/dom/Element.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 #ifdef MOZ_XUL
 #include "nsXULElement.h"
 #endif
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
@@ -1639,40 +1639,40 @@ void
 nsXBLPrototypeBinding::EnsureResources()
 {
   if (!mResources) {
     mResources = new nsXBLPrototypeResources(this);
   }
 }
 
 void
-nsXBLPrototypeBinding::AppendStyleSheet(StyleSheetHandle aSheet)
+nsXBLPrototypeBinding::AppendStyleSheet(StyleSheet* aSheet)
 {
   EnsureResources();
   mResources->AppendStyleSheet(aSheet);
 }
 
 void
-nsXBLPrototypeBinding::RemoveStyleSheet(StyleSheetHandle aSheet)
+nsXBLPrototypeBinding::RemoveStyleSheet(StyleSheet* aSheet)
 {
   if (!mResources) {
     MOZ_ASSERT(false, "Trying to remove a sheet that does not exist.");
     return;
   }
 
   mResources->RemoveStyleSheet(aSheet);
 }
 void
-nsXBLPrototypeBinding::InsertStyleSheetAt(size_t aIndex, StyleSheetHandle aSheet)
+nsXBLPrototypeBinding::InsertStyleSheetAt(size_t aIndex, StyleSheet* aSheet)
 {
   EnsureResources();
   mResources->InsertStyleSheetAt(aIndex, aSheet);
 }
 
-StyleSheetHandle
+StyleSheet*
 nsXBLPrototypeBinding::StyleSheetAt(size_t aIndex) const
 {
   MOZ_ASSERT(mResources);
   return mResources->StyleSheetAt(aIndex);
 }
 
 size_t
 nsXBLPrototypeBinding::SheetCount() const
@@ -1683,14 +1683,14 @@ nsXBLPrototypeBinding::SheetCount() cons
 bool
 nsXBLPrototypeBinding::HasStyleSheets() const
 {
   return mResources && mResources->HasStyleSheets();
 }
 
 void
 nsXBLPrototypeBinding::AppendStyleSheetsTo(
-                                      nsTArray<StyleSheetHandle>& aResult) const
+                                      nsTArray<StyleSheet*>& aResult) const
 {
   if (mResources) {
     mResources->AppendStyleSheetsTo(aResult);
   }
 }
--- a/dom/xbl/nsXBLPrototypeBinding.h
+++ b/dom/xbl/nsXBLPrototypeBinding.h
@@ -15,17 +15,17 @@
 #include "nsInterfaceHashtable.h"
 #include "nsWeakReference.h"
 #include "nsXBLDocumentInfo.h"
 #include "nsXBLProtoImpl.h"
 #include "nsXBLProtoImplMethod.h"
 #include "nsXBLPrototypeHandler.h"
 #include "nsXBLPrototypeResources.h"
 #include "mozilla/WeakPtr.h"
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 
 class nsIAtom;
 class nsIContent;
 class nsIDocument;
 class nsXBLAttributeEntry;
 class nsXBLBinding;
 class nsXBLProtoImplField;
 
@@ -115,23 +115,23 @@ public:
   void SetBasePrototype(nsXBLPrototypeBinding* aBinding);
   nsXBLPrototypeBinding* GetBasePrototype() { return mBaseBinding; }
 
   nsXBLDocumentInfo* XBLDocumentInfo() const { return mXBLDocInfoWeak; }
   bool IsChrome() { return mXBLDocInfoWeak->IsChrome(); }
 
   void SetInitialAttributes(nsIContent* aBoundElement, nsIContent* aAnonymousContent);
 
-  void AppendStyleSheet(mozilla::StyleSheetHandle aSheet);
-  void RemoveStyleSheet(mozilla::StyleSheetHandle aSheet);
-  void InsertStyleSheetAt(size_t aIndex, mozilla::StyleSheetHandle aSheet);
-  mozilla::StyleSheetHandle StyleSheetAt(size_t aIndex) const;
+  void AppendStyleSheet(mozilla::StyleSheet* aSheet);
+  void RemoveStyleSheet(mozilla::StyleSheet* aSheet);
+  void InsertStyleSheetAt(size_t aIndex, mozilla::StyleSheet* aSheet);
+  mozilla::StyleSheet* StyleSheetAt(size_t aIndex) const;
   size_t SheetCount() const;
   bool HasStyleSheets() const;
-  void AppendStyleSheetsTo(nsTArray<mozilla::StyleSheetHandle>& aResult) const;
+  void AppendStyleSheetsTo(nsTArray<mozilla::StyleSheet*>& aResult) const;
 
   nsIStyleRuleProcessor* GetRuleProcessor();
 
   nsresult FlushSkinSheets();
 
   nsIAtom* GetBaseTag(int32_t* aNamespaceID);
   void SetBaseTag(int32_t aNamespaceID, nsIAtom* aTag);
 
--- a/dom/xbl/nsXBLPrototypeResources.cpp
+++ b/dom/xbl/nsXBLPrototypeResources.cpp
@@ -14,18 +14,18 @@
 #include "nsIDocumentObserver.h"
 #include "mozilla/css/Loader.h"
 #include "nsIURI.h"
 #include "nsLayoutCID.h"
 #include "nsCSSRuleProcessor.h"
 #include "nsStyleSet.h"
 #include "mozilla/dom/URL.h"
 #include "mozilla/DebugOnly.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 using namespace mozilla;
 using mozilla::dom::IsChromeURI;
 
 nsXBLPrototypeResources::nsXBLPrototypeResources(nsXBLPrototypeBinding* aBinding)
 {
   MOZ_COUNT_CTOR(nsXBLPrototypeResources);
 
@@ -79,28 +79,28 @@ nsXBLPrototypeResources::FlushSkinSheets
   }
 
   // We have scoped stylesheets.  Reload any chrome stylesheets we
   // encounter.  (If they aren't skin sheets, it doesn't matter, since
   // they'll still be in the chrome cache.  Skip inline sheets, which
   // skin sheets can't be, and which in any case don't have a usable
   // URL to reload.)
 
-  nsTArray<StyleSheetHandle::RefPtr> oldSheets;
+  nsTArray<RefPtr<StyleSheet>> oldSheets;
 
   oldSheets.SwapElements(mStyleSheetList);
 
   mozilla::css::Loader* cssLoader = doc->CSSLoader();
 
   for (size_t i = 0, count = oldSheets.Length(); i < count; ++i) {
-    StyleSheetHandle oldSheet = oldSheets[i];
+    StyleSheet* oldSheet = oldSheets[i];
 
     nsIURI* uri = oldSheet->GetSheetURI();
 
-    StyleSheetHandle::RefPtr newSheet;
+    RefPtr<StyleSheet> newSheet;
     if (!oldSheet->IsInline() && IsChromeURI(uri)) {
       if (NS_FAILED(cssLoader->LoadSheetSync(uri, &newSheet)))
         continue;
     }
     else {
       newSheet = oldSheet;
     }
 
@@ -142,48 +142,48 @@ nsXBLPrototypeResources::ClearLoader()
 {
   mLoader = nullptr;
 }
 
 void
 nsXBLPrototypeResources::GatherRuleProcessor()
 {
   nsTArray<RefPtr<CSSStyleSheet>> sheets(mStyleSheetList.Length());
-  for (StyleSheetHandle sheet : mStyleSheetList) {
+  for (StyleSheet* sheet : mStyleSheetList) {
     MOZ_ASSERT(sheet->IsGecko(),
                "GatherRuleProcessor must only be called for "
                "nsXBLPrototypeResources objects with Gecko-flavored style "
                "backends");
     sheets.AppendElement(sheet->AsGecko());
   }
   mRuleProcessor = new nsCSSRuleProcessor(Move(sheets),
                                           SheetType::Doc,
                                           nullptr,
                                           mRuleProcessor);
 }
 
 void
-nsXBLPrototypeResources::AppendStyleSheet(StyleSheetHandle aSheet)
+nsXBLPrototypeResources::AppendStyleSheet(StyleSheet* aSheet)
 {
   mStyleSheetList.AppendElement(aSheet);
 }
 
 void
-nsXBLPrototypeResources::RemoveStyleSheet(StyleSheetHandle aSheet)
+nsXBLPrototypeResources::RemoveStyleSheet(StyleSheet* aSheet)
 {
   mStyleSheetList.RemoveElement(aSheet);
 }
 
 void
-nsXBLPrototypeResources::InsertStyleSheetAt(size_t aIndex, StyleSheetHandle aSheet)
+nsXBLPrototypeResources::InsertStyleSheetAt(size_t aIndex, StyleSheet* aSheet)
 {
   mStyleSheetList.InsertElementAt(aIndex, aSheet);
 }
 
-StyleSheetHandle
+StyleSheet*
 nsXBLPrototypeResources::StyleSheetAt(size_t aIndex) const
 {
   return mStyleSheetList[aIndex];
 }
 
 size_t
 nsXBLPrototypeResources::SheetCount() const
 {
@@ -193,12 +193,12 @@ nsXBLPrototypeResources::SheetCount() co
 bool
 nsXBLPrototypeResources::HasStyleSheets() const
 {
   return !mStyleSheetList.IsEmpty();
 }
 
 void
 nsXBLPrototypeResources::AppendStyleSheetsTo(
-                                      nsTArray<StyleSheetHandle>& aResult) const
+                                      nsTArray<StyleSheet*>& aResult) const
 {
   aResult.AppendElements(mStyleSheetList);
 }
--- a/dom/xbl/nsXBLPrototypeResources.h
+++ b/dom/xbl/nsXBLPrototypeResources.h
@@ -2,17 +2,17 @@
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsXBLPrototypeResources_h__
 #define nsXBLPrototypeResources_h__
 
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 #include "nsICSSLoaderObserver.h"
 
 class nsCSSRuleProcessor;
 class nsIAtom;
 class nsIContent;
 class nsXBLPrototypeBinding;
 class nsXBLResourceLoader;
 
@@ -36,37 +36,37 @@ public:
 
   nsresult Write(nsIObjectOutputStream* aStream);
 
   void Traverse(nsCycleCollectionTraversalCallback &cb);
   void Unlink();
 
   void ClearLoader();
 
-  void AppendStyleSheet(mozilla::StyleSheetHandle aSheet);
-  void RemoveStyleSheet(mozilla::StyleSheetHandle aSheet);
-  void InsertStyleSheetAt(size_t aIndex, mozilla::StyleSheetHandle aSheet);
-  mozilla::StyleSheetHandle StyleSheetAt(size_t aIndex) const;
+  void AppendStyleSheet(mozilla::StyleSheet* aSheet);
+  void RemoveStyleSheet(mozilla::StyleSheet* aSheet);
+  void InsertStyleSheetAt(size_t aIndex, mozilla::StyleSheet* aSheet);
+  mozilla::StyleSheet* StyleSheetAt(size_t aIndex) const;
   size_t SheetCount() const;
   bool HasStyleSheets() const;
-  void AppendStyleSheetsTo(nsTArray<mozilla::StyleSheetHandle>& aResult) const;
+  void AppendStyleSheetsTo(nsTArray<mozilla::StyleSheet*>& aResult) const;
 
   /**
    * Recreates mRuleProcessor to represent the current list of style sheets
    * stored in mStyleSheetList.  (Named GatherRuleProcessor to parallel
    * nsStyleSet::GatherRuleProcessors.)
    */
   void GatherRuleProcessor();
 
   nsCSSRuleProcessor* GetRuleProcessor() const { return mRuleProcessor; }
 
 private:
   // A loader object. Exists only long enough to load resources, and then it dies.
   RefPtr<nsXBLResourceLoader> mLoader;
 
   // A list of loaded stylesheets for this binding.
-  nsTArray<mozilla::StyleSheetHandle::RefPtr> mStyleSheetList;
+  nsTArray<RefPtr<mozilla::StyleSheet>> mStyleSheetList;
 
   // The list of stylesheets converted to a rule processor.
   RefPtr<nsCSSRuleProcessor> mRuleProcessor;
 };
 
 #endif
--- a/dom/xbl/nsXBLResourceLoader.cpp
+++ b/dom/xbl/nsXBLResourceLoader.cpp
@@ -12,18 +12,18 @@
 #include "nsIPresShell.h"
 #include "nsXBLService.h"
 #include "nsIServiceManager.h"
 #include "nsXBLResourceLoader.h"
 #include "nsXBLPrototypeResources.h"
 #include "nsIDocumentObserver.h"
 #include "imgILoader.h"
 #include "imgRequestProxy.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/css/Loader.h"
 #include "nsIURI.h"
 #include "nsNetUtil.h"
 #include "nsGkAtoms.h"
 #include "nsFrameManager.h"
 #include "nsStyleContext.h"
 #include "nsXBLPrototypeBinding.h"
 #include "nsCSSRuleProcessor.h"
@@ -130,17 +130,17 @@ nsXBLResourceLoader::LoadResources(bool*
       bool chrome;
       nsresult rv;
       if (NS_SUCCEEDED(url->SchemeIs("chrome", &chrome)) && chrome)
       {
         rv = nsContentUtils::GetSecurityManager()->
           CheckLoadURIWithPrincipal(docPrincipal, url,
                                     nsIScriptSecurityManager::ALLOW_CHROME);
         if (NS_SUCCEEDED(rv)) {
-          StyleSheetHandle::RefPtr sheet;
+          RefPtr<StyleSheet> sheet;
           rv = cssLoader->LoadSheetSync(url, &sheet);
           NS_ASSERTION(NS_SUCCEEDED(rv), "Load failed!!!");
           if (NS_SUCCEEDED(rv))
           {
             rv = StyleSheetLoaded(sheet, false, NS_OK);
             NS_ASSERTION(NS_SUCCEEDED(rv), "Processing the style sheet failed!!!");
           }
         }
@@ -159,17 +159,17 @@ nsXBLResourceLoader::LoadResources(bool*
   
   // Destroy our resource list.
   delete mResourceList;
   mResourceList = nullptr;
 }
 
 // nsICSSLoaderObserver
 NS_IMETHODIMP
-nsXBLResourceLoader::StyleSheetLoaded(StyleSheetHandle aSheet,
+nsXBLResourceLoader::StyleSheetLoaded(StyleSheet* aSheet,
                                       bool aWasAlternate,
                                       nsresult aStatus)
 {
   if (!mResources) {
     // Our resources got destroyed -- just bail out
     return NS_OK;
   }
    
--- a/dom/xbl/nsXBLResourceLoader.h
+++ b/dom/xbl/nsXBLResourceLoader.h
@@ -25,17 +25,17 @@ class nsIObjectOutputStream;
 
 class nsXBLResourceLoader : public nsICSSLoaderObserver
 {
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS(nsXBLResourceLoader)
 
   // nsICSSLoaderObserver
-  NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheetHandle aSheet,
+  NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheet* aSheet,
                               bool aWasAlternate,
                               nsresult aStatus) override;
 
   void LoadResources(bool* aResult);
   void AddResource(nsIAtom* aResourceType, const nsAString& aSrc);
   void AddResourceListener(nsIContent* aElement);
 
   nsXBLResourceLoader(nsXBLPrototypeBinding* aBinding,
--- a/dom/xml/nsXMLContentSink.cpp
+++ b/dom/xml/nsXMLContentSink.cpp
@@ -15,17 +15,17 @@
 #include "nsNetUtil.h"
 #include "nsIDocShell.h"
 #include "nsIStyleSheetLinkingElement.h"
 #include "nsIDOMComment.h"
 #include "nsIDOMCDATASection.h"
 #include "DocumentType.h"
 #include "nsHTMLParts.h"
 #include "nsCRT.h"
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/css/Loader.h"
 #include "nsGkAtoms.h"
 #include "nsContentUtils.h"
 #include "nsIScriptContext.h"
 #include "nsNameSpaceManager.h"
 #include "nsIServiceManager.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIContentViewer.h"
@@ -406,17 +406,17 @@ nsXMLContentSink::OnTransformDone(nsresu
   ScrollToRef();
 
   originalDocument->EndLoad();
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsXMLContentSink::StyleSheetLoaded(StyleSheetHandle aSheet,
+nsXMLContentSink::StyleSheetLoaded(StyleSheet* aSheet,
                                    bool aWasAlternate,
                                    nsresult aStatus)
 {
   if (!mPrettyPrinting) {
     return nsContentSink::StyleSheetLoaded(aSheet, aWasAlternate, aStatus);
   }
 
   if (!mDocument->CSSLoader()->HasPendingLoads()) {
--- a/dom/xml/nsXMLContentSink.h
+++ b/dom/xml/nsXMLContentSink.h
@@ -77,17 +77,17 @@ public:
   virtual bool IsScriptExecuting() override;
   virtual void ContinueInterruptedParsingAsync() override;
 
   // nsITransformObserver
   NS_IMETHOD OnDocumentCreated(nsIDocument *aResultDocument) override;
   NS_IMETHOD OnTransformDone(nsresult aResult, nsIDocument *aResultDocument) override;
 
   // nsICSSLoaderObserver
-  NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheetHandle aSheet,
+  NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheet* aSheet,
                               bool aWasAlternate,
                               nsresult aStatus) override;
   static bool ParsePIData(const nsString &aData, nsString &aHref,
                           nsString &aTitle, nsString &aMedia,
                           bool &aIsAlternate);
 
 protected:
   virtual ~nsXMLContentSink();
--- a/dom/xslt/xslt/txMozillaXMLOutput.cpp
+++ b/dom/xslt/xslt/txMozillaXMLOutput.cpp
@@ -22,17 +22,17 @@
 #include "nsIConsoleService.h"
 #include "nsIDOMDocumentFragment.h"
 #include "nsNameSpaceManager.h"
 #include "txStringUtils.h"
 #include "txURIUtils.h"
 #include "nsIHTMLDocument.h"
 #include "nsIStyleSheetLinkingElement.h"
 #include "nsIDocumentTransformer.h"
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/css/Loader.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/EncodingUtils.h"
 #include "nsContentUtils.h"
 #include "txXMLUtils.h"
 #include "nsContentSink.h"
 #include "nsINode.h"
 #include "nsContentCreatorFunctions.h"
@@ -971,17 +971,17 @@ txTransformNotifier::ScriptEvaluated(nsr
     if (mScriptElements.RemoveObject(aElement)) {
         SignalTransformEnd();
     }
 
     return NS_OK;
 }
 
 NS_IMETHODIMP 
-txTransformNotifier::StyleSheetLoaded(StyleSheetHandle aSheet,
+txTransformNotifier::StyleSheetLoaded(StyleSheet* aSheet,
                                       bool aWasAlternate,
                                       nsresult aStatus)
 {
     if (mPendingStylesheetCount == 0) {
         // We weren't waiting on this stylesheet anyway.  This can happen if
         // SignalTransformEnd got called with an error aResult.  See
         // http://bugzilla.mozilla.org/show_bug.cgi?id=215465.
         return NS_OK;
--- a/dom/xslt/xslt/txMozillaXMLOutput.h
+++ b/dom/xslt/xslt/txMozillaXMLOutput.h
@@ -30,17 +30,17 @@ class txTransformNotifier final : public
 {
 public:
     txTransformNotifier();
 
     NS_DECL_ISUPPORTS
     NS_DECL_NSISCRIPTLOADEROBSERVER
     
     // nsICSSLoaderObserver
-    NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheetHandle aSheet,
+    NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheet* aSheet,
                                 bool aWasAlternate,
                                 nsresult aStatus) override;
 
     void Init(nsITransformObserver* aObserver);
     nsresult AddScriptElement(nsIScriptElement* aElement);
     void AddPendingStylesheet();
     void OnTransformEnd(nsresult aResult = NS_OK);
     void OnTransformStart();
--- a/dom/xul/XULDocument.cpp
+++ b/dom/xul/XULDocument.cpp
@@ -62,17 +62,17 @@
 #include "nsIScriptGlobalObject.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsNodeInfoManager.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsContentUtils.h"
 #include "nsIParser.h"
 #include "nsCharsetSource.h"
 #include "nsIParserService.h"
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/css/Loader.h"
 #include "nsIScriptError.h"
 #include "nsIStyleSheetLinkingElement.h"
 #include "nsIObserverService.h"
 #include "nsNodeUtils.h"
 #include "nsIDocShellTreeOwner.h"
 #include "nsIXULWindow.h"
 #include "nsXULPopupManager.h"
@@ -89,18 +89,18 @@
 #include "mozilla/LoadInfo.h"
 #include "mozilla/Preferences.h"
 #include "nsTextNode.h"
 #include "nsJSUtils.h"
 #include "mozilla/dom/URL.h"
 #include "nsIContentPolicy.h"
 #include "mozAutoDocUpdate.h"
 #include "xpcpublic.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 //----------------------------------------------------------------------
 //
 // CIDs
 //
@@ -3101,17 +3101,17 @@ XULDocument::DoneWalking()
             }
         }
     }
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
-XULDocument::StyleSheetLoaded(StyleSheetHandle aSheet,
+XULDocument::StyleSheetLoaded(StyleSheet* aSheet,
                               bool aWasAlternate,
                               nsresult aStatus)
 {
     if (!aWasAlternate) {
         // Don't care about when alternate sheets finish loading
 
         NS_ASSERTION(mPendingSheets > 0,
             "Unexpected StyleSheetLoaded notification");
@@ -3725,17 +3725,17 @@ XULDocument::AddPrototypeSheets()
 {
     nsresult rv;
 
     const nsCOMArray<nsIURI>& sheets = mCurrentPrototype->GetStyleSheetReferences();
 
     for (int32_t i = 0; i < sheets.Count(); i++) {
         nsCOMPtr<nsIURI> uri = sheets[i];
 
-        StyleSheetHandle::RefPtr incompleteSheet;
+        RefPtr<StyleSheet> incompleteSheet;
         rv = CSSLoader()->LoadSheet(uri,
                                     mCurrentPrototype->DocumentPrincipal(),
                                     EmptyCString(), this,
                                     &incompleteSheet);
 
         // XXXldb We need to prevent bogus sheets from being held in the
         // prototype's list, but until then, don't propagate the failure
         // from LoadSheet (and thus exit the loop).
--- a/dom/xul/XULDocument.h
+++ b/dom/xul/XULDocument.h
@@ -8,17 +8,17 @@
 
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsXULPrototypeDocument.h"
 #include "nsXULPrototypeCache.h"
 #include "nsTArray.h"
 
 #include "mozilla/dom/XMLDocument.h"
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 #include "nsForwardReference.h"
 #include "nsIContent.h"
 #include "nsIDOMXULCommandDispatcher.h"
 #include "nsIDOMXULDocument.h"
 #include "nsCOMArray.h"
 #include "nsIURI.h"
 #include "nsIXULDocument.h"
 #include "nsScriptLoader.h"
@@ -158,17 +158,17 @@ public:
 
     // nsDocument interface overrides
     virtual Element* GetElementById(const nsAString & elementId) override;
 
     // nsIDOMXULDocument interface
     NS_DECL_NSIDOMXULDOCUMENT
 
     // nsICSSLoaderObserver
-    NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheetHandle aSheet,
+    NS_IMETHOD StyleSheetLoaded(mozilla::StyleSheet* aSheet,
                                 bool aWasAlternate,
                                 nsresult aStatus) override;
 
     virtual void EndUpdate(nsUpdateType aUpdateType) override;
 
     virtual bool IsDocumentRightToLeft() override;
 
     virtual void ResetDocumentDirection() override;
@@ -339,17 +339,17 @@ protected:
      */
     bool                           mRestrictPersistence;
     nsTHashtable<nsStringHashKey>  mPersistenceIds;
 
     /**
      * An array of style sheets, that will be added (preserving order) to the
      * document after all of them are loaded (in DoneWalking).
      */
-    nsTArray<StyleSheetHandle::RefPtr> mOverlaySheets;
+    nsTArray<RefPtr<StyleSheet>> mOverlaySheets;
 
     nsCOMPtr<nsIDOMXULCommandDispatcher>     mCommandDispatcher; // [OWNER] of the focus tracker
 
     // Maintains the template builders that have been attached to
     // content elements
     typedef nsInterfaceHashtable<nsISupportsHashKey, nsIXULTemplateBuilder>
         BuilderTable;
     BuilderTable* mTemplateBuilderTable;
--- a/dom/xul/nsXULPrototypeCache.cpp
+++ b/dom/xul/nsXULPrototypeCache.cpp
@@ -18,17 +18,17 @@
 #include "nsIObserverService.h"
 #include "nsIStringStream.h"
 #include "nsIStorageStream.h"
 
 #include "nsAppDirectoryServiceDefs.h"
 
 #include "js/TracingAPI.h"
 
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/scache/StartupCache.h"
 #include "mozilla/scache/StartupCacheUtils.h"
 #include "mozilla/Telemetry.h"
 
 using namespace mozilla;
 using namespace mozilla::scache;
 
--- a/editor/libeditor/EditorBase.cpp
+++ b/editor/libeditor/EditorBase.cpp
@@ -4232,32 +4232,32 @@ EditorBase::CreateTxnForComposition(cons
   RefPtr<CompositionTransaction> transaction =
     new CompositionTransaction(*mIMETextNode, mIMETextOffset, mIMETextLength,
                                mComposition->GetRanges(), aStringToInsert,
                                *this);
   return transaction.forget();
 }
 
 NS_IMETHODIMP
-EditorBase::CreateTxnForAddStyleSheet(StyleSheetHandle aSheet,
+EditorBase::CreateTxnForAddStyleSheet(StyleSheet* aSheet,
                                       AddStyleSheetTransaction** aTransaction)
 {
   RefPtr<AddStyleSheetTransaction> transaction = new AddStyleSheetTransaction();
 
   nsresult rv = transaction->Init(this, aSheet);
   if (NS_SUCCEEDED(rv)) {
     transaction.forget(aTransaction);
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 EditorBase::CreateTxnForRemoveStyleSheet(
-              StyleSheetHandle aSheet,
+              StyleSheet* aSheet,
               RemoveStyleSheetTransaction** aTransaction)
 {
   RefPtr<RemoveStyleSheetTransaction> transaction =
     new RemoveStyleSheetTransaction();
 
   nsresult rv = transaction->Init(this, aSheet);
   if (NS_SUCCEEDED(rv)) {
     transaction.forget(aTransaction);
--- a/editor/libeditor/EditorBase.h
+++ b/editor/libeditor/EditorBase.h
@@ -4,17 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_EditorBase_h
 #define mozilla_EditorBase_h
 
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc.
 #include "mozilla/OwningNonNull.h"      // for OwningNonNull
 #include "mozilla/SelectionState.h"     // for RangeUpdater, etc.
-#include "mozilla/StyleSheetHandle.h"   // for StyleSheetHandle
+#include "mozilla/StyleSheet.h"   // for StyleSheet
 #include "mozilla/dom/Text.h"
 #include "nsCOMPtr.h"                   // for already_AddRefed, nsCOMPtr
 #include "nsCycleCollectionParticipant.h"
 #include "nsGkAtoms.h"
 #include "nsIEditor.h"                  // for nsIEditor::EDirection, etc.
 #include "nsIEditorIMESupport.h"        // for NS_DECL_NSIEDITORIMESUPPORT, etc.
 #include "nsIObserver.h"                // for NS_DECL_NSIOBSERVER, etc.
 #include "nsIPhonetic.h"                // for NS_DECL_NSIPHONETIC, etc.
@@ -323,24 +323,24 @@ protected:
    */
   already_AddRefed<mozilla::CompositionTransaction>
     CreateTxnForComposition(const nsAString& aStringToInsert);
 
   /**
    * Create a transaction for adding a style sheet.
    */
   NS_IMETHOD CreateTxnForAddStyleSheet(
-               StyleSheetHandle aSheet,
+               StyleSheet* aSheet,
                AddStyleSheetTransaction** aTransaction);
 
   /**
    * Create a transaction for removing a style sheet.
    */
   NS_IMETHOD CreateTxnForRemoveStyleSheet(
-               StyleSheetHandle aSheet,
+               StyleSheet* aSheet,
                RemoveStyleSheetTransaction** aTransaction);
 
   nsresult DeleteText(nsGenericDOMDataNode& aElement,
                       uint32_t aOffset, uint32_t aLength);
 
   already_AddRefed<DeleteTextTransaction>
     CreateTxnForDeleteText(nsGenericDOMDataNode& aElement,
                            uint32_t aOffset, uint32_t aLength);
--- a/editor/libeditor/HTMLEditor.cpp
+++ b/editor/libeditor/HTMLEditor.cpp
@@ -67,18 +67,18 @@
 #include "mozilla/dom/Selection.h"
 #include "mozilla/dom/DocumentFragment.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/Event.h"
 #include "mozilla/dom/EventTarget.h"
 #include "mozilla/dom/HTMLBodyElement.h"
 #include "nsTextFragment.h"
 #include "nsContentList.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 namespace mozilla {
 
 using namespace dom;
 using namespace widget;
 
 // Some utilities to handle overloading of "A" tag for link and named anchor.
 static bool
@@ -2849,17 +2849,17 @@ HTMLEditor::ReplaceStyleSheet(const nsAS
 
   return ps->GetDocument()->CSSLoader()->
     LoadSheet(uaURI, false, nullptr, EmptyCString(), this);
 }
 
 NS_IMETHODIMP
 HTMLEditor::RemoveStyleSheet(const nsAString& aURL)
 {
-  StyleSheetHandle::RefPtr sheet = GetStyleSheetForURL(aURL);
+  RefPtr<StyleSheet> sheet = GetStyleSheetForURL(aURL);
   NS_ENSURE_TRUE(sheet, NS_ERROR_UNEXPECTED);
 
   RefPtr<RemoveStyleSheetTransaction> transaction;
   nsresult rv =
     CreateTxnForRemoveStyleSheet(sheet, getter_AddRefs(transaction));
   if (!transaction) {
     rv = NS_ERROR_NULL_POINTER;
   }
@@ -2889,17 +2889,17 @@ HTMLEditor::AddOverrideStyleSheet(const 
 
   nsCOMPtr<nsIURI> uaURI;
   nsresult rv = NS_NewURI(getter_AddRefs(uaURI), aURL);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // We MUST ONLY load synchronous local files (no @import)
   // XXXbz Except this will actually try to load remote files
   // synchronously, of course..
-  StyleSheetHandle::RefPtr sheet;
+  RefPtr<StyleSheet> sheet;
   // Editor override style sheets may want to style Gecko anonymous boxes
   rv = ps->GetDocument()->CSSLoader()->
     LoadSheetSync(uaURI, mozilla::css::eAgentSheetFeatures, true,
                   &sheet);
 
   // Synchronous loads should ALWAYS return completed
   NS_ENSURE_TRUE(sheet, NS_ERROR_NULL_POINTER);
 
@@ -2934,17 +2934,17 @@ HTMLEditor::ReplaceOverrideStyleSheet(co
 
   return AddOverrideStyleSheet(aURL);
 }
 
 // Do NOT use transaction system for override style sheets
 NS_IMETHODIMP
 HTMLEditor::RemoveOverrideStyleSheet(const nsAString& aURL)
 {
-  StyleSheetHandle::RefPtr sheet = GetStyleSheetForURL(aURL);
+  RefPtr<StyleSheet> sheet = GetStyleSheetForURL(aURL);
 
   // Make sure we remove the stylesheet from our internal list in all
   // cases.
   nsresult rv = RemoveStyleSheetFromList(aURL);
 
   NS_ENSURE_TRUE(sheet, NS_OK); /// Don't fail if sheet not found
 
   NS_ENSURE_TRUE(mDocWeak, NS_ERROR_NOT_INITIALIZED);
@@ -2957,17 +2957,17 @@ HTMLEditor::RemoveOverrideStyleSheet(con
   // Remove it from our internal list
   return rv;
 }
 
 NS_IMETHODIMP
 HTMLEditor::EnableStyleSheet(const nsAString& aURL,
                              bool aEnable)
 {
-  StyleSheetHandle::RefPtr sheet = GetStyleSheetForURL(aURL);
+  RefPtr<StyleSheet> sheet = GetStyleSheetForURL(aURL);
   NS_ENSURE_TRUE(sheet, NS_OK); // Don't fail if sheet not found
 
   // Ensure the style sheet is owned by our document.
   nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocWeak);
   sheet->SetOwningDocument(doc);
 
   if (sheet->IsServo()) {
     // XXXheycam ServoStyleSheets don't support being enabled/disabled yet.
@@ -2975,17 +2975,17 @@ HTMLEditor::EnableStyleSheet(const nsASt
     return NS_ERROR_FAILURE;
   }
   return sheet->AsGecko()->SetDisabled(!aEnable);
 }
 
 bool
 HTMLEditor::EnableExistingStyleSheet(const nsAString& aURL)
 {
-  StyleSheetHandle::RefPtr sheet = GetStyleSheetForURL(aURL);
+  RefPtr<StyleSheet> sheet = GetStyleSheetForURL(aURL);
 
   // Enable sheet if already loaded.
   if (sheet)
   {
     // Ensure the style sheet is owned by our document.
     nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocWeak);
     sheet->SetOwningDocument(doc);
 
@@ -2997,17 +2997,17 @@ HTMLEditor::EnableExistingStyleSheet(con
     sheet->AsGecko()->SetDisabled(false);
     return true;
   }
   return false;
 }
 
 nsresult
 HTMLEditor::AddNewStyleSheetToList(const nsAString& aURL,
-                                   StyleSheetHandle aStyleSheet)
+                                   StyleSheet* aStyleSheet)
 {
   uint32_t countSS = mStyleSheets.Length();
   uint32_t countU = mStyleSheetURLs.Length();
 
   if (countSS != countU)
     return NS_ERROR_UNEXPECTED;
 
   if (!mStyleSheetURLs.AppendElement(aURL))
@@ -3027,32 +3027,32 @@ HTMLEditor::RemoveStyleSheetFromList(con
 
   // Attempt both removals; if one fails there's not much we can do.
   mStyleSheets.RemoveElementAt(foundIndex);
   mStyleSheetURLs.RemoveElementAt(foundIndex);
 
   return NS_OK;
 }
 
-StyleSheetHandle
+StyleSheet*
 HTMLEditor::GetStyleSheetForURL(const nsAString& aURL)
 {
   // is it already in the list?
   size_t foundIndex;
   foundIndex = mStyleSheetURLs.IndexOf(aURL);
   if (foundIndex == mStyleSheetURLs.NoIndex) {
     return nullptr;
   }
 
   MOZ_ASSERT(mStyleSheets[foundIndex]);
   return mStyleSheets[foundIndex];
 }
 
 void
-HTMLEditor::GetURLForStyleSheet(StyleSheetHandle aStyleSheet,
+HTMLEditor::GetURLForStyleSheet(StyleSheet* aStyleSheet,
                                 nsAString& aURL)
 {
   // is it already in the list?
   int32_t foundIndex = mStyleSheets.IndexOf(aStyleSheet);
 
   // Don't fail if we don't find it in our list
   if (foundIndex == -1)
     return;
@@ -3421,17 +3421,17 @@ HTMLEditor::DebugUnitTests(int32_t* outN
   delete tester;
   return NS_OK;
 #else
   return NS_ERROR_NOT_IMPLEMENTED;
 #endif
 }
 
 NS_IMETHODIMP
-HTMLEditor::StyleSheetLoaded(StyleSheetHandle aSheet,
+HTMLEditor::StyleSheetLoaded(StyleSheet* aSheet,
                              bool aWasAlternate,
                              nsresult aStatus)
 {
   nsresult rv = NS_OK;
   AutoEditBatch batchIt(this);
 
   if (!mLastStyleSheetURL.IsEmpty())
     RemoveStyleSheet(mLastStyleSheetURL);
--- a/editor/libeditor/HTMLEditor.h
+++ b/editor/libeditor/HTMLEditor.h
@@ -3,17 +3,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_HTMLEditor_h
 #define mozilla_HTMLEditor_h
 
 #include "mozilla/Attributes.h"
 #include "mozilla/CSSEditUtils.h"
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 #include "mozilla/TextEditor.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/File.h"
 
 #include "nsAttrName.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsIContentFilter.h"
@@ -360,17 +360,17 @@ public:
 
   NS_IMETHOD GetIsSelectionEditable(bool* aIsSelectionEditable) override;
 
   NS_IMETHOD SelectAll() override;
 
   NS_IMETHOD GetRootElement(nsIDOMElement** aRootElement) override;
 
   // nsICSSLoaderObserver
-  NS_IMETHOD StyleSheetLoaded(StyleSheetHandle aSheet,
+  NS_IMETHOD StyleSheetLoaded(StyleSheet* aSheet,
                               bool aWasAlternate, nsresult aStatus) override;
 
   // Utility Routines, not part of public API
   NS_IMETHOD TypedText(const nsAString& aString,
                        ETypingAction aAction) override;
   nsresult InsertNodeAtPoint(nsIDOMNode* aNode,
                              nsCOMPtr<nsIDOMNode>* ioParent,
                              int32_t* ioOffset,
@@ -412,25 +412,25 @@ public:
   /**
    * Returns TRUE if sheet was loaded, false if it wasn't.
    */
   bool EnableExistingStyleSheet(const nsAString& aURL);
 
   /**
    * Dealing with the internal style sheet lists.
    */
-  StyleSheetHandle GetStyleSheetForURL(const nsAString& aURL);
-  void GetURLForStyleSheet(StyleSheetHandle aStyleSheet,
+  StyleSheet* GetStyleSheetForURL(const nsAString& aURL);
+  void GetURLForStyleSheet(StyleSheet* aStyleSheet,
                            nsAString& aURL);
 
   /**
    * Add a url + known style sheet to the internal lists.
    */
   nsresult AddNewStyleSheetToList(const nsAString &aURL,
-                                  StyleSheetHandle aStyleSheet);
+                                  StyleSheet* aStyleSheet);
   nsresult RemoveStyleSheetFromList(const nsAString &aURL);
 
   bool IsCSSEnabled()
   {
     // TODO: removal of mCSSAware and use only the presence of mCSSEditUtils
     return mCSSAware && mCSSEditUtils && mCSSEditUtils->IsCSSPrefChecked();
   }
 
@@ -902,17 +902,17 @@ protected:
   // Used by GetFirstSelectedCell and GetNextSelectedCell
   int32_t  mSelectedCellIndex;
 
   nsString mLastStyleSheetURL;
   nsString mLastOverrideStyleSheetURL;
 
   // Maintain a list of associated style sheets and their urls.
   nsTArray<nsString> mStyleSheetURLs;
-  nsTArray<StyleSheetHandle::RefPtr> mStyleSheets;
+  nsTArray<RefPtr<StyleSheet>> mStyleSheets;
 
   // an array for holding default style settings
   nsTArray<PropItem*> mDefaultStyles;
 
 protected:
   // ANONYMOUS UTILS
   void RemoveListenerAndDeleteRef(const nsAString& aEvent,
                                   nsIDOMEventListener* aListener,
--- a/editor/libeditor/StyleSheetTransactions.cpp
+++ b/editor/libeditor/StyleSheetTransactions.cpp
@@ -4,42 +4,42 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "StyleSheetTransactions.h"
 
 #include <stddef.h>                     // for nullptr
 
 #include "nsAString.h"
 #include "nsCOMPtr.h"                   // for nsCOMPtr, do_QueryInterface, etc.
-#include "mozilla/StyleSheetHandle.h"   // for mozilla::StyleSheetHandle
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"   // for mozilla::StyleSheet
+#include "mozilla/StyleSheetInlines.h"
 #include "nsDebug.h"                    // for NS_ENSURE_TRUE
 #include "nsError.h"                    // for NS_OK, etc.
 #include "nsIDOMDocument.h"             // for nsIDOMDocument
 #include "nsIDocument.h"                // for nsIDocument
 #include "nsIDocumentObserver.h"        // for UPDATE_STYLE
 #include "nsIEditor.h"                  // for nsIEditor
 
 namespace mozilla {
 
 static void
-AddStyleSheet(nsIEditor* aEditor, StyleSheetHandle aSheet)
+AddStyleSheet(nsIEditor* aEditor, StyleSheet* aSheet)
 {
   nsCOMPtr<nsIDOMDocument> domDoc;
   aEditor->GetDocument(getter_AddRefs(domDoc));
   nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
   if (doc) {
     doc->BeginUpdate(UPDATE_STYLE);
     doc->AddStyleSheet(aSheet);
     doc->EndUpdate(UPDATE_STYLE);
   }
 }
 
 static void
-RemoveStyleSheet(nsIEditor* aEditor, StyleSheetHandle aSheet)
+RemoveStyleSheet(nsIEditor* aEditor, StyleSheet* aSheet)
 {
   nsCOMPtr<nsIDOMDocument> domDoc;
   aEditor->GetDocument(getter_AddRefs(domDoc));
   nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
   if (doc) {
     doc->BeginUpdate(UPDATE_STYLE);
     doc->RemoveStyleSheet(aSheet);
     doc->EndUpdate(UPDATE_STYLE);
@@ -59,17 +59,17 @@ NS_IMPL_CYCLE_COLLECTION_INHERITED(AddSt
                                    EditTransactionBase,
                                    mSheet)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(AddStyleSheetTransaction)
 NS_INTERFACE_MAP_END_INHERITING(EditTransactionBase)
 
 NS_IMETHODIMP
 AddStyleSheetTransaction::Init(nsIEditor* aEditor,
-                               StyleSheetHandle aSheet)
+                               StyleSheet* aSheet)
 {
   NS_ENSURE_TRUE(aEditor && aSheet, NS_ERROR_INVALID_ARG);
 
   mEditor = aEditor;
   mSheet = aSheet;
 
   return NS_OK;
 }
@@ -113,17 +113,17 @@ NS_IMPL_CYCLE_COLLECTION_INHERITED(Remov
                                    EditTransactionBase,
                                    mSheet)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(RemoveStyleSheetTransaction)
 NS_INTERFACE_MAP_END_INHERITING(EditTransactionBase)
 
 NS_IMETHODIMP
 RemoveStyleSheetTransaction::Init(nsIEditor* aEditor,
-                                  StyleSheetHandle aSheet)
+                                  StyleSheet* aSheet)
 {
   NS_ENSURE_TRUE(aEditor && aSheet, NS_ERROR_INVALID_ARG);
 
   mEditor = aEditor;
   mSheet = aSheet;
 
   return NS_OK;
 }
--- a/editor/libeditor/StyleSheetTransactions.h
+++ b/editor/libeditor/StyleSheetTransactions.h
@@ -2,72 +2,72 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef StylesheetTransactions_h
 #define StylesheetTransactions_h
 
 #include "mozilla/EditTransactionBase.h" // for EditTransactionBase, etc.
-#include "mozilla/StyleSheetHandle.h"   // for mozilla::StyleSheetHandle
+#include "mozilla/StyleSheet.h"   // for mozilla::StyleSheet
 #include "nsCycleCollectionParticipant.h"
 #include "nsID.h"                       // for REFNSIID
 #include "nscore.h"                     // for NS_IMETHOD
 
 class nsIEditor;
 
 namespace mozilla {
 
 class AddStyleSheetTransaction final : public EditTransactionBase
 {
 public:
   /**
    * Initialize the transaction.
    * @param aEditor     The object providing core editing operations
    * @param aSheet      The stylesheet to add
     */
-  NS_IMETHOD Init(nsIEditor* aEditor, StyleSheetHandle aSheet);
+  NS_IMETHOD Init(nsIEditor* aEditor, StyleSheet* aSheet);
 
   AddStyleSheetTransaction();
 
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(AddStyleSheetTransaction,
                                            EditTransactionBase)
   NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr) override;
 
   NS_DECL_EDITTRANSACTIONBASE
 
 protected:
   // The editor that created this transaction.
   nsIEditor* mEditor;
   // The style sheet to add.
-  mozilla::StyleSheetHandle::RefPtr mSheet;
+  RefPtr<mozilla::StyleSheet> mSheet;
 };
 
 
 class RemoveStyleSheetTransaction final : public EditTransactionBase
 {
 public:
   /**
    * Initialize the transaction.
    * @param aEditor     The object providing core editing operations.
    * @param aSheet      The stylesheet to remove.
    */
-  NS_IMETHOD Init(nsIEditor* aEditor, StyleSheetHandle aSheet);
+  NS_IMETHOD Init(nsIEditor* aEditor, StyleSheet* aSheet);
 
   RemoveStyleSheetTransaction();
 
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(RemoveStyleSheetTransaction,
                                            EditTransactionBase)
   NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr) override;
 
   NS_DECL_EDITTRANSACTIONBASE
 
 protected:
   // The editor that created this transaction.
   nsIEditor* mEditor;
   // The style sheet to remove.
-  StyleSheetHandle::RefPtr mSheet;
+  RefPtr<StyleSheet> mSheet;
 
 };
 
 } // namespace mozilla
 
 #endif // #ifndef StylesheetTransactions_h
--- a/gfx/gl/GLScreenBuffer.cpp
+++ b/gfx/gl/GLScreenBuffer.cpp
@@ -10,17 +10,17 @@
 #include "GLContext.h"
 #include "GLBlitHelper.h"
 #include "GLReadTexImageHelper.h"
 #include "SharedSurfaceEGL.h"
 #include "SharedSurfaceGL.h"
 #include "ScopedGLHelpers.h"
 #include "gfx2DGlue.h"
 #include "../layers/ipc/ShadowLayers.h"
-#include "mozilla/layers/CompositableForwarder.h"
+#include "mozilla/layers/TextureForwarder.h"
 #include "mozilla/layers/TextureClientSharedSurface.h"
 
 #ifdef XP_WIN
 #include "SharedSurfaceANGLE.h"         // for SurfaceFactory_ANGLEShareHandle
 #include "SharedSurfaceD3D11Interop.h"  // for SurfaceFactory_D3D11Interop
 #include "mozilla/gfx/DeviceManagerDx.h"
 #endif
 
@@ -64,76 +64,77 @@ GLScreenBuffer::Create(GLContext* gl,
 
     ret.reset( new GLScreenBuffer(gl, caps, Move(factory)) );
     return Move(ret);
 }
 
 /* static */ UniquePtr<SurfaceFactory>
 GLScreenBuffer::CreateFactory(GLContext* gl,
                               const SurfaceCaps& caps,
-                              const RefPtr<layers::CompositableForwarder>& forwarder,
+                              KnowsCompositor* compositorConnection,
                               const layers::TextureFlags& flags)
 {
-  return CreateFactory(gl, caps, forwarder, forwarder->GetCompositorBackendType(), flags);
+  return CreateFactory(gl, caps, compositorConnection->GetTextureForwarder(),
+                       compositorConnection->GetCompositorBackendType(), flags);
 }
 
 /* static */ UniquePtr<SurfaceFactory>
 GLScreenBuffer::CreateFactory(GLContext* gl,
                               const SurfaceCaps& caps,
-                              const RefPtr<layers::ClientIPCAllocator>& allocator,
+                              LayersIPCChannel* ipcChannel,
                               const mozilla::layers::LayersBackend backend,
                               const layers::TextureFlags& flags)
 {
     UniquePtr<SurfaceFactory> factory = nullptr;
     if (!gfxPrefs::WebGLForceLayersReadback()) {
         switch (backend) {
             case mozilla::layers::LayersBackend::LAYERS_OPENGL: {
 #if defined(XP_MACOSX)
-                factory = SurfaceFactory_IOSurface::Create(gl, caps, allocator, flags);
+                factory = SurfaceFactory_IOSurface::Create(gl, caps, ipcChannel, flags);
 #elif defined(MOZ_WIDGET_GONK)
-                factory = MakeUnique<SurfaceFactory_Gralloc>(gl, caps, allocator, flags);
+                factory = MakeUnique<SurfaceFactory_Gralloc>(gl, caps, ipcChannel, flags);
 #elif defined(GL_PROVIDER_GLX)
                 if (sGLXLibrary.UseTextureFromPixmap())
-                  factory = SurfaceFactory_GLXDrawable::Create(gl, caps, allocator, flags);
+                  factory = SurfaceFactory_GLXDrawable::Create(gl, caps, ipcChannel, flags);
 #elif defined(MOZ_WIDGET_UIKIT)
-                factory = MakeUnique<SurfaceFactory_GLTexture>(mGLContext, caps, allocator, mFlags);
+                factory = MakeUnique<SurfaceFactory_GLTexture>(mGLContext, caps, ipcChannel, mFlags);
 #else
                 if (gl->GetContextType() == GLContextType::EGL) {
                     if (XRE_IsParentProcess()) {
-                        factory = SurfaceFactory_EGLImage::Create(gl, caps, allocator, flags);
+                        factory = SurfaceFactory_EGLImage::Create(gl, caps, ipcChannel, flags);
                     }
                 }
 #endif
                 break;
             }
             case mozilla::layers::LayersBackend::LAYERS_D3D11: {
 #ifdef XP_WIN
                 // Enable surface sharing only if ANGLE and compositing devices
                 // are both WARP or both not WARP
                 gfx::DeviceManagerDx* dm = gfx::DeviceManagerDx::Get();
                 if (gl->IsANGLE() &&
                     (gl->IsWARP() == dm->IsWARP()) &&
                     dm->TextureSharingWorks())
                 {
-                    factory = SurfaceFactory_ANGLEShareHandle::Create(gl, caps, allocator, flags);
+                    factory = SurfaceFactory_ANGLEShareHandle::Create(gl, caps, ipcChannel, flags);
                 }
 
                 if (!factory && gfxPrefs::WebGLDXGLEnabled()) {
-                  factory = SurfaceFactory_D3D11Interop::Create(gl, caps, allocator, flags);
+                  factory = SurfaceFactory_D3D11Interop::Create(gl, caps, ipcChannel, flags);
                 }
 #endif
               break;
             }
             default:
               break;
         }
 
 #ifdef GL_PROVIDER_GLX
         if (!factory && sGLXLibrary.UseTextureFromPixmap()) {
-            factory = SurfaceFactory_GLXDrawable::Create(gl, caps, allocator, flags);
+            factory = SurfaceFactory_GLXDrawable::Create(gl, caps, ipcChannel, flags);
         }
 #endif
     }
 
     return factory;
 }
 
 GLScreenBuffer::GLScreenBuffer(GLContext* gl,
--- a/gfx/gl/GLScreenBuffer.h
+++ b/gfx/gl/GLScreenBuffer.h
@@ -20,17 +20,18 @@
 #include "mozilla/gfx/2D.h"
 #include "mozilla/gfx/Point.h"
 #include "mozilla/UniquePtr.h"
 #include "SharedSurface.h"
 #include "SurfaceTypes.h"
 
 namespace mozilla {
 namespace layers {
-class CompositableForwarder;
+class KnowsCompositor;
+class LayersIPCChannel;
 class SharedSurfaceTextureClient;
 } // namespace layers
 
 namespace gl {
 
 class GLContext;
 class SharedSurface;
 class ShSurfHandle;
@@ -132,22 +133,22 @@ public:
     // Infallible.
     static UniquePtr<GLScreenBuffer> Create(GLContext* gl,
                                             const gfx::IntSize& size,
                                             const SurfaceCaps& caps);
 
     static UniquePtr<SurfaceFactory>
     CreateFactory(GLContext* gl,
                   const SurfaceCaps& caps,
-                  const RefPtr<layers::CompositableForwarder>& forwarder,
+                  layers::KnowsCompositor* compositorConnection,
                   const layers::TextureFlags& flags);
     static UniquePtr<SurfaceFactory>
     CreateFactory(GLContext* gl,
                   const SurfaceCaps& caps,
-                  const RefPtr<layers::ClientIPCAllocator>& allocator,
+                  layers::LayersIPCChannel* ipcChannel,
                   const mozilla::layers::LayersBackend backend,
                   const layers::TextureFlags& flags);
 
 protected:
     GLContext* const mGL; // Owns us.
 public:
     const SurfaceCaps mCaps;
 protected:
--- a/gfx/gl/SharedSurface.cpp
+++ b/gfx/gl/SharedSurface.cpp
@@ -10,16 +10,17 @@
 #include "GLContext.h"
 #include "GLReadTexImageHelper.h"
 #include "GLScreenBuffer.h"
 #include "nsThreadUtils.h"
 #include "ScopedGLHelpers.h"
 #include "SharedSurfaceGL.h"
 #include "mozilla/layers/CompositorTypes.h"
 #include "mozilla/layers/TextureClientSharedSurface.h"
+#include "mozilla/layers/TextureForwarder.h"
 #include "mozilla/Unused.h"
 
 namespace mozilla {
 namespace gl {
 
 /*static*/ void
 SharedSurface::ProdCopy(SharedSurface* src, SharedSurface* dest,
                         SurfaceFactory* factory)
@@ -282,17 +283,17 @@ ChooseBufferBits(const SurfaceCaps& caps
     } else {
         out_drawCaps->Clear();
         *out_readCaps = screenCaps;
     }
 }
 
 SurfaceFactory::SurfaceFactory(SharedSurfaceType type, GLContext* gl,
                                const SurfaceCaps& caps,
-                               const RefPtr<layers::ClientIPCAllocator>& allocator,
+                               const RefPtr<layers::LayersIPCChannel>& allocator,
                                const layers::TextureFlags& flags)
     : mType(type)
     , mGL(gl)
     , mCaps(caps)
     , mAllocator(allocator)
     , mFlags(flags)
     , mFormats(gl->ChooseGLFormats(caps))
     , mMutex("SurfaceFactor::mMutex")
--- a/gfx/gl/SharedSurface.h
+++ b/gfx/gl/SharedSurface.h
@@ -34,17 +34,17 @@ class nsIThread;
 
 namespace mozilla {
 namespace gfx {
 class DataSourceSurface;
 class DrawTarget;
 } // namespace gfx
 
 namespace layers {
-class ClientIPCAllocator;
+class LayersIPCChannel;
 class SharedSurfaceTextureClient;
 enum class TextureFlags : uint32_t;
 class SurfaceDescriptor;
 class TextureClient;
 } // namespace layers
 
 namespace gl {
 
@@ -262,28 +262,28 @@ class SurfaceFactory : public SupportsWe
 public:
     // Should use the VIRTUAL version, but it's currently incompatible
     // with SupportsWeakPtr. (bug 1049278)
     MOZ_DECLARE_WEAKREFERENCE_TYPENAME(SurfaceFactory)
 
     const SharedSurfaceType mType;
     GLContext* const mGL;
     const SurfaceCaps mCaps;
-    const RefPtr<layers::ClientIPCAllocator> mAllocator;
+    const RefPtr<layers::LayersIPCChannel> mAllocator;
     const layers::TextureFlags mFlags;
     const GLFormats mFormats;
     Mutex mMutex;
 protected:
     SurfaceCaps mDrawCaps;
     SurfaceCaps mReadCaps;
     RefQueue<layers::SharedSurfaceTextureClient> mRecycleFreePool;
     RefSet<layers::SharedSurfaceTextureClient> mRecycleTotalPool;
 
     SurfaceFactory(SharedSurfaceType type, GLContext* gl, const SurfaceCaps& caps,
-                   const RefPtr<layers::ClientIPCAllocator>& allocator,
+                   const RefPtr<layers::LayersIPCChannel>& allocator,
                    const layers::TextureFlags& flags);
 
 public:
     virtual ~SurfaceFactory();
 
     const SurfaceCaps& DrawCaps() const {
         return mDrawCaps;
     }
--- a/gfx/gl/SharedSurfaceANGLE.cpp
+++ b/gfx/gl/SharedSurfaceANGLE.cpp
@@ -315,17 +315,17 @@ SharedSurface_ANGLEShareHandle::Readback
     return true;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // Factory
 
 /*static*/ UniquePtr<SurfaceFactory_ANGLEShareHandle>
 SurfaceFactory_ANGLEShareHandle::Create(GLContext* gl, const SurfaceCaps& caps,
-                                        const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                        const RefPtr<layers::LayersIPCChannel>& allocator,
                                         const layers::TextureFlags& flags)
 {
     GLLibraryEGL* egl = &sEGLLibrary;
     if (!egl)
         return nullptr;
 
     auto ext = GLLibraryEGL::ANGLE_surface_d3d_texture_2d_share_handle;
     if (!egl->IsExtensionSupported(ext))
@@ -335,17 +335,17 @@ SurfaceFactory_ANGLEShareHandle::Create(
 
     typedef SurfaceFactory_ANGLEShareHandle ptrT;
     UniquePtr<ptrT> ret( new ptrT(gl, caps, allocator, flags, egl, config) );
     return Move(ret);
 }
 
 SurfaceFactory_ANGLEShareHandle::SurfaceFactory_ANGLEShareHandle(GLContext* gl,
                                                                  const SurfaceCaps& caps,
-                                                                 const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                                                 const RefPtr<layers::LayersIPCChannel>& allocator,
                                                                  const layers::TextureFlags& flags,
                                                                  GLLibraryEGL* egl,
                                                                  EGLConfig config)
     : SurfaceFactory(SharedSurfaceType::EGLSurfaceANGLE, gl, caps, allocator, flags)
     , mProdGL(gl)
     , mEGL(egl)
     , mConfig(config)
 { }
--- a/gfx/gl/SharedSurfaceANGLE.h
+++ b/gfx/gl/SharedSurfaceANGLE.h
@@ -75,22 +75,22 @@ class SurfaceFactory_ANGLEShareHandle
 protected:
     GLContext* const mProdGL;
     GLLibraryEGL* const mEGL;
     const EGLConfig mConfig;
 
 public:
     static UniquePtr<SurfaceFactory_ANGLEShareHandle> Create(GLContext* gl,
                                                              const SurfaceCaps& caps,
-                                                             const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                                             const RefPtr<layers::LayersIPCChannel>& allocator,
                                                              const layers::TextureFlags& flags);
 
 protected:
     SurfaceFactory_ANGLEShareHandle(GLContext* gl, const SurfaceCaps& caps,
-                                    const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                    const RefPtr<layers::LayersIPCChannel>& allocator,
                                     const layers::TextureFlags& flags, GLLibraryEGL* egl,
                                     EGLConfig config);
 
     virtual UniquePtr<SharedSurface> CreateShared(const gfx::IntSize& size) override {
         bool hasAlpha = mReadCaps.alpha;
         return SharedSurface_ANGLEShareHandle::Create(mProdGL, mConfig, size, hasAlpha);
     }
 };
--- a/gfx/gl/SharedSurfaceD3D11Interop.cpp
+++ b/gfx/gl/SharedSurfaceD3D11Interop.cpp
@@ -386,17 +386,17 @@ SharedSurface_D3D11Interop::ToSurfaceDes
     return true;
 }
 
 //////////////////////////////////////////////////////////////////////////////////////////
 // Factory
 
 /*static*/ UniquePtr<SurfaceFactory_D3D11Interop>
 SurfaceFactory_D3D11Interop::Create(GLContext* gl, const SurfaceCaps& caps,
-                                    layers::ClientIPCAllocator* allocator,
+                                    layers::LayersIPCChannel* allocator,
                                     const layers::TextureFlags& flags)
 {
     WGLLibrary* wgl = &sWGLLib;
     if (!wgl || !wgl->HasDXInterop2())
         return nullptr;
 
     const RefPtr<DXInterop2Device> interop = DXInterop2Device::Open(wgl, gl);
     if (!interop) {
@@ -406,17 +406,17 @@ SurfaceFactory_D3D11Interop::Create(GLCo
 
     typedef SurfaceFactory_D3D11Interop ptrT;
     UniquePtr<ptrT> ret(new ptrT(gl, caps, allocator, flags, interop));
     return Move(ret);
 }
 
 SurfaceFactory_D3D11Interop::SurfaceFactory_D3D11Interop(GLContext* gl,
                                                          const SurfaceCaps& caps,
-                                                         layers::ClientIPCAllocator* allocator,
+                                                         layers::LayersIPCChannel* allocator,
                                                          const layers::TextureFlags& flags,
                                                          DXInterop2Device* interop)
     : SurfaceFactory(SharedSurfaceType::DXGLInterop2, gl, caps, allocator, flags)
     , mInterop(interop)
 { }
 
 SurfaceFactory_D3D11Interop::~SurfaceFactory_D3D11Interop()
 { }
--- a/gfx/gl/SharedSurfaceD3D11Interop.h
+++ b/gfx/gl/SharedSurfaceD3D11Interop.h
@@ -70,22 +70,22 @@ public:
 class SurfaceFactory_D3D11Interop
     : public SurfaceFactory
 {
 public:
     const RefPtr<DXInterop2Device> mInterop;
 
     static UniquePtr<SurfaceFactory_D3D11Interop> Create(GLContext* gl,
                                                          const SurfaceCaps& caps,
-                                                         layers::ClientIPCAllocator* allocator,
+                                                         layers::LayersIPCChannel* allocator,
                                                          const layers::TextureFlags& flags);
 
 protected:
     SurfaceFactory_D3D11Interop(GLContext* gl, const SurfaceCaps& caps,
-                                layers::ClientIPCAllocator* allocator,
+                                layers::LayersIPCChannel* allocator,
                                 const layers::TextureFlags& flags,
                                 DXInterop2Device* interop);
 
 public:
     virtual ~SurfaceFactory_D3D11Interop() override;
 
 protected:
     virtual UniquePtr<SharedSurface> CreateShared(const gfx::IntSize& size) override {
--- a/gfx/gl/SharedSurfaceEGL.cpp
+++ b/gfx/gl/SharedSurfaceEGL.cpp
@@ -165,17 +165,17 @@ SharedSurface_EGLImage::ReadbackByShared
     MOZ_ASSERT(NS_IsMainThread());
     return sEGLLibrary.ReadbackEGLImage(mImage, out_surface);
 }
 
 ////////////////////////////////////////////////////////////////////////
 
 /*static*/ UniquePtr<SurfaceFactory_EGLImage>
 SurfaceFactory_EGLImage::Create(GLContext* prodGL, const SurfaceCaps& caps,
-                                const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                const RefPtr<layers::LayersIPCChannel>& allocator,
                                 const layers::TextureFlags& flags)
 {
     EGLContext context = GLContextEGL::Cast(prodGL)->mContext;
 
     typedef SurfaceFactory_EGLImage ptrT;
     UniquePtr<ptrT> ret;
 
     GLLibraryEGL* egl = &sEGLLibrary;
--- a/gfx/gl/SharedSurfaceEGL.h
+++ b/gfx/gl/SharedSurfaceEGL.h
@@ -85,24 +85,24 @@ public:
 
 class SurfaceFactory_EGLImage
     : public SurfaceFactory
 {
 public:
     // Fallible:
     static UniquePtr<SurfaceFactory_EGLImage> Create(GLContext* prodGL,
                                                      const SurfaceCaps& caps,
-                                                     const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                                     const RefPtr<layers::LayersIPCChannel>& allocator,
                                                      const layers::TextureFlags& flags);
 
 protected:
     const EGLContext mContext;
 
     SurfaceFactory_EGLImage(GLContext* prodGL, const SurfaceCaps& caps,
-                            const RefPtr<layers::ClientIPCAllocator>& allocator,
+                            const RefPtr<layers::LayersIPCChannel>& allocator,
                             const layers::TextureFlags& flags,
                             EGLContext context)
         : SurfaceFactory(SharedSurfaceType::EGLImageShare, prodGL, caps, allocator, flags)
         , mContext(context)
     { }
 
 public:
     virtual UniquePtr<SharedSurface> CreateShared(const gfx::IntSize& size) override {
--- a/gfx/gl/SharedSurfaceGL.h
+++ b/gfx/gl/SharedSurfaceGL.h
@@ -143,17 +143,17 @@ public:
 };
 
 class SurfaceFactory_GLTexture
     : public SurfaceFactory
 {
 public:
     SurfaceFactory_GLTexture(GLContext* prodGL,
                              const SurfaceCaps& caps,
-                             const RefPtr<layers::ClientIPCAllocator>& allocator,
+                             const RefPtr<layers::LayersIPCChannel>& allocator,
                              const layers::TextureFlags& flags)
         : SurfaceFactory(SharedSurfaceType::SharedGLTexture, prodGL, caps, allocator, flags)
     {
     }
 
     virtual UniquePtr<SharedSurface> CreateShared(const gfx::IntSize& size) override {
         bool hasAlpha = mReadCaps.alpha;
         return SharedSurface_GLTexture::Create(mGL, mFormats, size, hasAlpha);
--- a/gfx/gl/SharedSurfaceGLX.cpp
+++ b/gfx/gl/SharedSurfaceGLX.cpp
@@ -8,16 +8,17 @@
 #include "GLXLibrary.h"
 #include "GLContextProvider.h"
 #include "GLContextGLX.h"
 #include "GLScreenBuffer.h"
 #include "mozilla/gfx/SourceSurfaceCairo.h"
 #include "mozilla/layers/LayersSurfaces.h"
 #include "mozilla/layers/ShadowLayerUtilsX11.h"
 #include "mozilla/layers/ISurfaceAllocator.h"
+#include "mozilla/layers/TextureForwarder.h"
 #include "mozilla/X11Util.h"
 
 namespace mozilla {
 namespace gl {
 
 /* static */
 UniquePtr<SharedSurface_GLXDrawable>
 SharedSurface_GLXDrawable::Create(GLContext* prodGL,
@@ -115,17 +116,17 @@ SharedSurface_GLXDrawable::ReadbackBySha
 
     return true;
 }
 
 /* static */
 UniquePtr<SurfaceFactory_GLXDrawable>
 SurfaceFactory_GLXDrawable::Create(GLContext* prodGL,
                                    const SurfaceCaps& caps,
-                                   const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                   const RefPtr<layers::LayersIPCChannel>& allocator,
                                    const layers::TextureFlags& flags)
 {
     MOZ_ASSERT(caps.alpha, "GLX surfaces require an alpha channel!");
 
     typedef SurfaceFactory_GLXDrawable ptrT;
     UniquePtr<ptrT> ret(new ptrT(prodGL, caps, allocator,
                                  flags & ~layers::TextureFlags::ORIGIN_BOTTOM_LEFT));
     return Move(ret);
--- a/gfx/gl/SharedSurfaceGLX.h
+++ b/gfx/gl/SharedSurfaceGLX.h
@@ -44,24 +44,24 @@ private:
 };
 
 class SurfaceFactory_GLXDrawable
     : public SurfaceFactory
 {
 public:
     static UniquePtr<SurfaceFactory_GLXDrawable> Create(GLContext* prodGL,
                                                         const SurfaceCaps& caps,
-                                                        const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                                        const RefPtr<layers::LayersIPCChannel>& allocator,
                                                         const layers::TextureFlags& flags);
 
     virtual UniquePtr<SharedSurface> CreateShared(const gfx::IntSize& size) override;
 
 private:
     SurfaceFactory_GLXDrawable(GLContext* prodGL, const SurfaceCaps& caps,
-                               const RefPtr<layers::ClientIPCAllocator>& allocator,
+                               const RefPtr<layers::LayersIPCChannel>& allocator,
                                const layers::TextureFlags& flags)
         : SurfaceFactory(SharedSurfaceType::GLXDrawable, prodGL, caps, allocator, flags)
     { }
 };
 
 } // namespace gl
 } // namespace mozilla
 
--- a/gfx/gl/SharedSurfaceGralloc.cpp
+++ b/gfx/gl/SharedSurfaceGralloc.cpp
@@ -30,30 +30,30 @@
 
 namespace mozilla {
 namespace gl {
 
 using namespace mozilla::layers;
 using namespace android;
 
 SurfaceFactory_Gralloc::SurfaceFactory_Gralloc(GLContext* prodGL, const SurfaceCaps& caps,
-                                               const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                               const RefPtr<layers::LayersIPCChannel>& allocator,
                                                const layers::TextureFlags& flags)
     : SurfaceFactory(SharedSurfaceType::Gralloc, prodGL, caps, allocator, flags)
 {
     MOZ_ASSERT(mAllocator);
 }
 
 /*static*/ UniquePtr<SharedSurface_Gralloc>
 SharedSurface_Gralloc::Create(GLContext* prodGL,
                               const GLFormats& formats,
                               const gfx::IntSize& size,
                               bool hasAlpha,
                               layers::TextureFlags flags,
-                              ClientIPCAllocator* allocator)
+                              LayersIPCChannel* allocator)
 {
     GLLibraryEGL* egl = &sEGLLibrary;
     MOZ_ASSERT(egl);
 
     UniquePtr<SharedSurface_Gralloc> ret;
 
     DEBUG_PRINT("SharedSurface_Gralloc::Create -------\n");
 
@@ -113,17 +113,17 @@ SharedSurface_Gralloc::Create(GLContext*
     return Move(ret);
 }
 
 
 SharedSurface_Gralloc::SharedSurface_Gralloc(GLContext* prodGL,
                                              const gfx::IntSize& size,
                                              bool hasAlpha,
                                              GLLibraryEGL* egl,
-                                             layers::ClientIPCAllocator* allocator,
+                                             layers::LayersIPCChannel* allocator,
                                              layers::TextureClient* textureClient,
                                              GLuint prodTex)
     : SharedSurface(SharedSurfaceType::Gralloc,
                     AttachmentType::GLTexture,
                     prodGL,
                     size,
                     hasAlpha,
                     true)
--- a/gfx/gl/SharedSurfaceGralloc.h
+++ b/gfx/gl/SharedSurfaceGralloc.h
@@ -7,53 +7,53 @@
 #define SHARED_SURFACE_GRALLOC_H_
 
 #include "mozilla/layers/CompositorTypes.h"
 #include "mozilla/layers/LayersSurfaces.h"
 #include "SharedSurface.h"
 
 namespace mozilla {
 namespace layers {
-class ClientIPCAllocator;
+class LayersIPCChannel;
 class TextureClient;
 }
 
 namespace gl {
 class GLContext;
 class GLLibraryEGL;
 
 class SharedSurface_Gralloc
     : public SharedSurface
 {
 public:
     static UniquePtr<SharedSurface_Gralloc> Create(GLContext* prodGL,
                                                    const GLFormats& formats,
                                                    const gfx::IntSize& size,
                                                    bool hasAlpha,
                                                    layers::TextureFlags flags,
-                                                   layers::ClientIPCAllocator* allocator);
+                                                   layers::LayersIPCChannel* allocator);
 
     static SharedSurface_Gralloc* Cast(SharedSurface* surf) {
         MOZ_ASSERT(surf->mType == SharedSurfaceType::Gralloc);
 
         return (SharedSurface_Gralloc*)surf;
     }
 
 protected:
     GLLibraryEGL* const mEGL;
     EGLSync mSync;
-    RefPtr<layers::ClientIPCAllocator> mAllocator;
+    RefPtr<layers::LayersIPCChannel> mAllocator;
     RefPtr<layers::TextureClient> mTextureClient;
     const GLuint mProdTex;
 
     SharedSurface_Gralloc(GLContext* prodGL,
                           const gfx::IntSize& size,
                           bool hasAlpha,
                           GLLibraryEGL* egl,
-                          layers::ClientIPCAllocator* allocator,
+                          layers::LayersIPCChannel* allocator,
                           layers::TextureClient* textureClient,
                           GLuint prodTex);
 
     static bool HasExtensions(GLLibraryEGL* egl, GLContext* gl);
 
 public:
     virtual ~SharedSurface_Gralloc();
 
@@ -78,17 +78,17 @@ public:
     virtual bool ReadbackBySharedHandle(gfx::DataSourceSurface* out_surface) override;
 };
 
 class SurfaceFactory_Gralloc
     : public SurfaceFactory
 {
 public:
     SurfaceFactory_Gralloc(GLContext* prodGL, const SurfaceCaps& caps,
-                           const RefPtr<layers::ClientIPCAllocator>& allocator,
+                           const RefPtr<layers::LayersIPCChannel>& allocator,
                            const layers::TextureFlags& flags);
 
     virtual UniquePtr<SharedSurface> CreateShared(const gfx::IntSize& size) override {
         bool hasAlpha = mReadCaps.alpha;
 
         UniquePtr<SharedSurface> ret;
         if (mAllocator) {
             ret = SharedSurface_Gralloc::Create(mGL, mFormats, size, hasAlpha,
--- a/gfx/gl/SharedSurfaceIO.cpp
+++ b/gfx/gl/SharedSurfaceIO.cpp
@@ -206,17 +206,17 @@ SharedSurface_IOSurface::ReadbackByShare
     return true;
 }
 
 ////////////////////////////////////////////////////////////////////////
 // SurfaceFactory_IOSurface
 
 /*static*/ UniquePtr<SurfaceFactory_IOSurface>
 SurfaceFactory_IOSurface::Create(GLContext* gl, const SurfaceCaps& caps,
-                                 const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                 const RefPtr<layers::LayersIPCChannel>& allocator,
                                  const layers::TextureFlags& flags)
 {
     auto maxDims = gfx::IntSize::Truncate(MacIOSurface::GetMaxWidth(),
                                           MacIOSurface::GetMaxHeight());
 
     typedef SurfaceFactory_IOSurface ptrT;
     UniquePtr<ptrT> ret( new ptrT(gl, caps, allocator, flags, maxDims) );
     return Move(ret);
--- a/gfx/gl/SharedSurfaceIO.h
+++ b/gfx/gl/SharedSurfaceIO.h
@@ -72,23 +72,23 @@ public:
 };
 
 class SurfaceFactory_IOSurface : public SurfaceFactory
 {
 public:
     // Infallible.
     static UniquePtr<SurfaceFactory_IOSurface> Create(GLContext* gl,
                                                       const SurfaceCaps& caps,
-                                                      const RefPtr<layers::ClientIPCAllocator>& allocator,
+                                                      const RefPtr<layers::LayersIPCChannel>& allocator,
                                                       const layers::TextureFlags& flags);
 protected:
     const gfx::IntSize mMaxDims;
 
     SurfaceFactory_IOSurface(GLContext* gl, const SurfaceCaps& caps,
-                             const RefPtr<layers::ClientIPCAllocator>& allocator,
+                             const RefPtr<layers::LayersIPCChannel>& allocator,
                              const layers::TextureFlags& flags,
                              const gfx::IntSize& maxDims)
         : SurfaceFactory(SharedSurfaceType::IOSurface, gl, caps, allocator, flags)
         , mMaxDims(maxDims)
     { }
 
     virtual UniquePtr<SharedSurface> CreateShared(const gfx::IntSize& size) override;
 };
--- a/gfx/layers/BufferTexture.cpp
+++ b/gfx/layers/BufferTexture.cpp
@@ -22,26 +22,27 @@ namespace layers {
 class MemoryTextureData : public BufferTextureData
 {
 public:
   static MemoryTextureData* Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                                    gfx::BackendType aMoz2DBackend,
                                    LayersBackend aLayersBackend,
                                    TextureFlags aFlags,
                                    TextureAllocationFlags aAllocFlags,
-                                   ClientIPCAllocator* aAllocator);
+                                   LayersIPCChannel* aAllocator);
 
   virtual TextureData*
-  CreateSimilar(ClientIPCAllocator* aAllocator,
+  CreateSimilar(LayersIPCChannel* aAllocator,
+                LayersBackend aLayersBackend,
                 TextureFlags aFlags = TextureFlags::DEFAULT,
                 TextureAllocationFlags aAllocFlags = ALLOC_DEFAULT) const override;
 
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
-  virtual void Deallocate(ClientIPCAllocator*) override;
+  virtual void Deallocate(LayersIPCChannel*) override;
 
   MemoryTextureData(const BufferDescriptor& aDesc,
                     gfx::BackendType aMoz2DBackend,
                     uint8_t* aBuffer, size_t aBufferSize)
   : BufferTextureData(aDesc, aMoz2DBackend)
   , mBuffer(aBuffer)
   , mBufferSize(aBufferSize)
   {
@@ -61,26 +62,27 @@ protected:
 class ShmemTextureData : public BufferTextureData
 {
 public:
   static ShmemTextureData* Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                                   gfx::BackendType aMoz2DBackend,
                                   LayersBackend aLayersBackend,
                                   TextureFlags aFlags,
                                   TextureAllocationFlags aAllocFlags,
-                                  ClientIPCAllocator* aAllocator);
+                                  LayersIPCChannel* aAllocator);
 
   virtual TextureData*
-  CreateSimilar(ClientIPCAllocator* aAllocator,
+  CreateSimilar(LayersIPCChannel* aAllocator,
+                LayersBackend aLayersBackend,
                 TextureFlags aFlags = TextureFlags::DEFAULT,
                 TextureAllocationFlags aAllocFlags = ALLOC_DEFAULT) const override;
 
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
-  virtual void Deallocate(ClientIPCAllocator* aAllocator) override;
+  virtual void Deallocate(LayersIPCChannel* aAllocator) override;
 
   ShmemTextureData(const BufferDescriptor& aDesc,
                    gfx::BackendType aMoz2DBackend, mozilla::ipc::Shmem aShmem)
   : BufferTextureData(aDesc, aMoz2DBackend)
   , mShmem(aShmem)
   {
     MOZ_ASSERT(mShmem.Size<uint8_t>());
   }
@@ -109,83 +111,79 @@ bool ComputeHasIntermediateBuffer(gfx::S
       || aFormat == gfx::SurfaceFormat::UNKNOWN;
 }
 
 BufferTextureData*
 BufferTextureData::Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                           gfx::BackendType aMoz2DBackend,
                           LayersBackend aLayersBackend, TextureFlags aFlags,
                           TextureAllocationFlags aAllocFlags,
-                          ClientIPCAllocator* aAllocator)
+                          LayersIPCChannel* aAllocator)
 {
   if (!aAllocator || aAllocator->IsSameProcess()) {
     return MemoryTextureData::Create(aSize, aFormat, aMoz2DBackend,
                                      aLayersBackend, aFlags,
                                      aAllocFlags, aAllocator);
-  } else if (aAllocator->AsShmemAllocator()) {
+  } else {
     return ShmemTextureData::Create(aSize, aFormat, aMoz2DBackend,
                                     aLayersBackend, aFlags,
                                     aAllocFlags, aAllocator);
   }
-  return nullptr;
 }
 
 BufferTextureData*
-BufferTextureData::CreateInternal(ClientIPCAllocator* aAllocator,
+BufferTextureData::CreateInternal(LayersIPCChannel* aAllocator,
                                   const BufferDescriptor& aDesc,
                                   gfx::BackendType aMoz2DBackend,
                                   int32_t aBufferSize,
                                   TextureFlags aTextureFlags)
 {
   if (!aAllocator || aAllocator->IsSameProcess()) {
     uint8_t* buffer = new (fallible) uint8_t[aBufferSize];
     if (!buffer) {
       return nullptr;
     }
 
     GfxMemoryImageReporter::DidAlloc(buffer);
 
     return new MemoryTextureData(aDesc, aMoz2DBackend, buffer, aBufferSize);
-  } else if (aAllocator->AsShmemAllocator()) {
+  } else {
     ipc::Shmem shm;
-    if (!aAllocator->AsShmemAllocator()->AllocUnsafeShmem(aBufferSize, OptimalShmemType(), &shm)) {
+    if (!aAllocator->AllocUnsafeShmem(aBufferSize, OptimalShmemType(), &shm)) {
       return nullptr;
     }
 
     return new ShmemTextureData(aDesc, aMoz2DBackend, shm);
   }
-  return nullptr;
 }
 
 BufferTextureData*
-BufferTextureData::CreateForYCbCrWithBufferSize(ClientIPCAllocator* aAllocator,
+BufferTextureData::CreateForYCbCrWithBufferSize(KnowsCompositor* aAllocator,
                                                 int32_t aBufferSize,
                                                 TextureFlags aTextureFlags)
 {
   if (aBufferSize == 0 || !gfx::Factory::CheckBufferSize(aBufferSize)) {
     return nullptr;
   }
 
-  auto fwd = aAllocator->AsCompositableForwarder();
-  bool hasIntermediateBuffer = fwd ? ComputeHasIntermediateBuffer(gfx::SurfaceFormat::YUV,
-                                                                  fwd->GetCompositorBackendType())
-                                   : true;
+  bool hasIntermediateBuffer = ComputeHasIntermediateBuffer(gfx::SurfaceFormat::YUV,
+                                                            aAllocator->GetCompositorBackendType());
 
   // Initialize the metadata with something, even if it will have to be rewritten
   // afterwards since we don't know the dimensions of the texture at this point.
   BufferDescriptor desc = YCbCrDescriptor(gfx::IntSize(), gfx::IntSize(),
                                           0, 0, 0, StereoMode::MONO,
                                           hasIntermediateBuffer);
 
-  return CreateInternal(aAllocator, desc, gfx::BackendType::NONE, aBufferSize,
+  return CreateInternal(aAllocator->GetTextureForwarder(), desc, gfx::BackendType::NONE, aBufferSize,
                         aTextureFlags);
 }
 
 BufferTextureData*
-BufferTextureData::CreateForYCbCr(ClientIPCAllocator* aAllocator,
+BufferTextureData::CreateForYCbCr(KnowsCompositor* aAllocator,
                                   gfx::IntSize aYSize,
                                   gfx::IntSize aCbCrSize,
                                   StereoMode aStereoMode,
                                   TextureFlags aTextureFlags)
 {
   uint32_t bufSize = ImageDataSerializer::ComputeYCbCrBufferSize(aYSize, aCbCrSize);
   if (bufSize == 0) {
     return nullptr;
@@ -193,27 +191,26 @@ BufferTextureData::CreateForYCbCr(Client
 
   uint32_t yOffset;
   uint32_t cbOffset;
   uint32_t crOffset;
   ImageDataSerializer::ComputeYCbCrOffsets(aYSize.width, aYSize.height,
                                           aCbCrSize.width, aCbCrSize.height,
                                           yOffset, cbOffset, crOffset);
 
-  auto fwd = aAllocator ? aAllocator->AsCompositableForwarder() : nullptr;
-  bool hasIntermediateBuffer = fwd ? ComputeHasIntermediateBuffer(gfx::SurfaceFormat::YUV,
-                                                                  fwd->GetCompositorBackendType())
-                                   : true;
+  bool hasIntermediateBuffer = aAllocator ? ComputeHasIntermediateBuffer(gfx::SurfaceFormat::YUV,
+                                                                         aAllocator->GetCompositorBackendType())
+                                          : true;
 
   YCbCrDescriptor descriptor = YCbCrDescriptor(aYSize, aCbCrSize, yOffset, cbOffset,
                                                crOffset, aStereoMode,
                                                hasIntermediateBuffer);
 
- return CreateInternal(aAllocator, descriptor, gfx::BackendType::NONE, bufSize,
-                       aTextureFlags);
+ return CreateInternal(aAllocator ? aAllocator->GetTextureForwarder() : nullptr, descriptor,
+                       gfx::BackendType::NONE, bufSize, aTextureFlags);
 }
 
 void
 BufferTextureData::FillInfo(TextureData::Info& aInfo) const
 {
   aInfo.size = GetSize();
   aInfo.format = GetFormat();
   aInfo.hasSynchronization = false;
@@ -457,17 +454,17 @@ InitBuffer(uint8_t* buf, size_t bufSize,
   return true;
 }
 
 MemoryTextureData*
 MemoryTextureData::Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                           gfx::BackendType aMoz2DBackend,
                           LayersBackend aLayersBackend, TextureFlags aFlags,
                           TextureAllocationFlags aAllocFlags,
-                          ClientIPCAllocator* aAllocator)
+                          LayersIPCChannel* aAllocator)
 {
   // Should have used CreateForYCbCr.
   MOZ_ASSERT(aFormat != gfx::SurfaceFormat::YUV);
 
   if (aSize.width <= 0 || aSize.height <= 0) {
     gfxDebug() << "Asking for buffer of invalid size " << aSize.width << "x" << aSize.height;
     return nullptr;
   }
@@ -477,48 +474,42 @@ MemoryTextureData::Create(gfx::IntSize a
     return nullptr;
   }
 
   uint8_t* buf = new (fallible) uint8_t[bufSize];
   if (!InitBuffer(buf, bufSize, aFormat, aAllocFlags, false)) {
     return nullptr;
   }
 
-  // LAYERS_NONE must imply that we have no compositable forwarder
-  MOZ_ASSERT_IF(aLayersBackend == LayersBackend::LAYERS_NONE,
-                !aAllocator || !aAllocator->AsCompositableForwarder());
-
   bool hasIntermediateBuffer = ComputeHasIntermediateBuffer(aFormat, aLayersBackend);
 
   GfxMemoryImageReporter::DidAlloc(buf);
 
   BufferDescriptor descriptor = RGBDescriptor(aSize, aFormat, hasIntermediateBuffer);
 
   return new MemoryTextureData(descriptor, aMoz2DBackend, buf, bufSize);
 }
 
 void
-MemoryTextureData::Deallocate(ClientIPCAllocator*)
+MemoryTextureData::Deallocate(LayersIPCChannel*)
 {
   MOZ_ASSERT(mBuffer);
   GfxMemoryImageReporter::WillFree(mBuffer);
   delete [] mBuffer;
   mBuffer = nullptr;
 }
 
 TextureData*
-MemoryTextureData::CreateSimilar(ClientIPCAllocator* aAllocator,
+MemoryTextureData::CreateSimilar(LayersIPCChannel* aAllocator,
+                                 LayersBackend aLayersBackend,
                                  TextureFlags aFlags,
                                  TextureAllocationFlags aAllocFlags) const
 {
-  auto fwd = aAllocator ? aAllocator->AsCompositableForwarder() : nullptr;
-  auto backend = fwd ? fwd->GetCompositorBackendType() : LayersBackend::LAYERS_NONE;
-
   return MemoryTextureData::Create(GetSize(), GetFormat(), mMoz2DBackend,
-                                   backend, aFlags, aAllocFlags, aAllocator);
+                                   aLayersBackend, aFlags, aAllocFlags, aAllocator);
 }
 
 bool
 ShmemTextureData::Serialize(SurfaceDescriptor& aOutDescriptor)
 {
   MOZ_ASSERT(GetFormat() != gfx::SurfaceFormat::UNKNOWN);
   if (GetFormat() == gfx::SurfaceFormat::UNKNOWN) {
     return false;
@@ -529,71 +520,65 @@ ShmemTextureData::Serialize(SurfaceDescr
   return true;
 }
 
 ShmemTextureData*
 ShmemTextureData::Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                          gfx::BackendType aMoz2DBackend,
                          LayersBackend aLayersBackend, TextureFlags aFlags,
                          TextureAllocationFlags aAllocFlags,
-                         ClientIPCAllocator* aAllocator)
+                         LayersIPCChannel* aAllocator)
 {
   MOZ_ASSERT(aAllocator);
   // Should have used CreateForYCbCr.
   MOZ_ASSERT(aFormat != gfx::SurfaceFormat::YUV);
 
-  if (!aAllocator || !aAllocator->AsShmemAllocator()) {
+  if (!aAllocator) {
     return nullptr;
   }
 
   if (aSize.width <= 0 || aSize.height <= 0) {
     gfxDebug() << "Asking for buffer of invalid size " << aSize.width << "x" << aSize.height;
     return nullptr;
   }
 
   uint32_t bufSize = ImageDataSerializer::ComputeRGBBufferSize(aSize, aFormat);
   if (!bufSize) {
     return nullptr;
   }
 
   mozilla::ipc::Shmem shm;
-  if (!aAllocator->AsShmemAllocator()->AllocUnsafeShmem(bufSize, OptimalShmemType(), &shm)) {
+  if (!aAllocator->AllocUnsafeShmem(bufSize, OptimalShmemType(), &shm)) {
     return nullptr;
   }
 
   uint8_t* buf = shm.get<uint8_t>();
   if (!InitBuffer(buf, bufSize, aFormat, aAllocFlags, true)) {
     return nullptr;
   }
 
-  // LAYERS_NONE must imply that we have no compositable forwarder
-  MOZ_ASSERT_IF(aLayersBackend == LayersBackend::LAYERS_NONE,
-                !aAllocator || !aAllocator->AsCompositableForwarder());
-
   bool hasIntermediateBuffer = ComputeHasIntermediateBuffer(aFormat, aLayersBackend);
 
   BufferDescriptor descriptor = RGBDescriptor(aSize, aFormat, hasIntermediateBuffer);
 
   return new ShmemTextureData(descriptor, aMoz2DBackend, shm);
 
   return nullptr;
 }
 
 TextureData*
-ShmemTextureData::CreateSimilar(ClientIPCAllocator* aAllocator,
+ShmemTextureData::CreateSimilar(LayersIPCChannel* aAllocator,
+                                LayersBackend aLayersBackend,
                                 TextureFlags aFlags,
                                 TextureAllocationFlags aAllocFlags) const
 {
-  auto fwd = aAllocator ? aAllocator->AsCompositableForwarder() : nullptr;
-  auto backend = fwd ? fwd->GetCompositorBackendType() : LayersBackend::LAYERS_NONE;
-
   return ShmemTextureData::Create(GetSize(), GetFormat(), mMoz2DBackend,
-                                  backend, aFlags, aAllocFlags, aAllocator);
+                                  aLayersBackend, aFlags, aAllocFlags, aAllocator);
 }
 
 void
-ShmemTextureData::Deallocate(ClientIPCAllocator* aAllocator)
+ShmemTextureData::Deallocate(LayersIPCChannel* aAllocator)
 {
-  aAllocator->AsShmemAllocator()->DeallocShmem(mShmem);
+  aAllocator->DeallocShmem(mShmem);
 }
 
 } // namespace
 } // namespace
--- a/gfx/layers/BufferTexture.h
+++ b/gfx/layers/BufferTexture.h
@@ -21,28 +21,28 @@ bool ComputeHasIntermediateBuffer(gfx::S
 class BufferTextureData : public TextureData
 {
 public:
   static BufferTextureData* Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                                    gfx::BackendType aMoz2DBackend,
                                    LayersBackend aLayersBackend,
                                    TextureFlags aFlags,
                                    TextureAllocationFlags aAllocFlags,
-                                   ClientIPCAllocator* aAllocator);
+                                   LayersIPCChannel* aAllocator);
 
-  static BufferTextureData* CreateForYCbCr(ClientIPCAllocator* aAllocator,
+  static BufferTextureData* CreateForYCbCr(KnowsCompositor* aAllocator,
                                            gfx::IntSize aYSize,
                                            gfx::IntSize aCbCrSize,
                                            StereoMode aStereoMode,
                                            TextureFlags aTextureFlags);
 
   // It is generally better to use CreateForYCbCr instead.
   // This creates a half-initialized texture since we don't know the sizes and
   // offsets in the buffer.
-  static BufferTextureData* CreateForYCbCrWithBufferSize(ClientIPCAllocator* aAllocator,
+  static BufferTextureData* CreateForYCbCrWithBufferSize(KnowsCompositor* aAllocator,
                                                          int32_t aSize,
                                                          TextureFlags aTextureFlags);
 
   virtual bool Lock(OpenMode aMode, FenceHandle*) override { return true; }
 
   virtual void Unlock() override {}
 
   virtual void FillInfo(TextureData::Info& aInfo) const override;
@@ -65,17 +65,17 @@ public:
 
   Maybe<StereoMode> GetStereoMode() const;
 
 protected:
   gfx::IntSize GetSize() const;
 
   gfx::SurfaceFormat GetFormat() const;
 
-  static BufferTextureData* CreateInternal(ClientIPCAllocator* aAllocator,
+  static BufferTextureData* CreateInternal(LayersIPCChannel* aAllocator,
                                            const BufferDescriptor& aDesc,
                                            gfx::BackendType aMoz2DBackend,
                                            int32_t aBufferSize,
                                            TextureFlags aTextureFlags);
 
   virtual uint8_t* GetBuffer() = 0;
   virtual size_t GetBufferSize() = 0;
 
--- a/gfx/layers/D3D11ShareHandleImage.cpp
+++ b/gfx/layers/D3D11ShareHandleImage.cpp
@@ -48,17 +48,17 @@ D3D11ShareHandleImage::AllocateTexture(D
 
 gfx::IntSize
 D3D11ShareHandleImage::GetSize()
 {
   return mSize;
 }
 
 TextureClient*
-D3D11ShareHandleImage::GetTextureClient(TextureForwarder* aForwarder)
+D3D11ShareHandleImage::GetTextureClient(KnowsCompositor* aForwarder)
 {
   return mTextureClient;
 }
 
 already_AddRefed<gfx::SourceSurface>
 D3D11ShareHandleImage::GetAsSourceSurface()
 {
   RefPtr<ID3D11Texture2D> texture = GetTexture();
@@ -137,17 +137,17 @@ already_AddRefed<TextureClient>
 D3D11RecycleAllocator::Allocate(gfx::SurfaceFormat aFormat,
                                 gfx::IntSize aSize,
                                 BackendSelector aSelector,
                                 TextureFlags aTextureFlags,
                                 TextureAllocationFlags aAllocFlags)
 {
   return CreateD3D11TextureClientWithDevice(aSize, aFormat,
                                             aTextureFlags, aAllocFlags,
-                                            mDevice, mSurfaceAllocator);
+                                            mDevice, mSurfaceAllocator->GetTextureForwarder());
 }
 
 already_AddRefed<TextureClient>
 D3D11RecycleAllocator::CreateOrRecycleClient(gfx::SurfaceFormat aFormat,
                                              const gfx::IntSize& aSize)
 {
   RefPtr<TextureClient> textureClient =
     CreateOrRecycle(aFormat,
--- a/gfx/layers/D3D11ShareHandleImage.h
+++ b/gfx/layers/D3D11ShareHandleImage.h
@@ -14,17 +14,17 @@
 #include "mozilla/layers/TextureClientRecycleAllocator.h"
 
 namespace mozilla {
 namespace layers {
 
 class D3D11RecycleAllocator : public TextureClientRecycleAllocator
 {
 public:
-  explicit D3D11RecycleAllocator(TextureForwarder* aAllocator,
+  explicit D3D11RecycleAllocator(KnowsCompositor* aAllocator,
                                  ID3D11Device* aDevice)
     : TextureClientRecycleAllocator(aAllocator)
     , mDevice(aDevice)
   {}
 
   already_AddRefed<TextureClient>
   CreateOrRecycleClient(gfx::SurfaceFormat aFormat,
                         const gfx::IntSize& aSize);
@@ -49,17 +49,17 @@ public:
   D3D11ShareHandleImage(const gfx::IntSize& aSize,
                         const gfx::IntRect& aRect);
   ~D3D11ShareHandleImage() override {}
 
   bool AllocateTexture(D3D11RecycleAllocator* aAllocator, ID3D11Device* aDevice);
 
   gfx::IntSize GetSize() override;
   virtual already_AddRefed<gfx::SourceSurface> GetAsSourceSurface() override;
-  virtual TextureClient* GetTextureClient(TextureForwarder* aForwarder) override;
+  virtual TextureClient* GetTextureClient(KnowsCompositor* aForwarder) override;
   virtual gfx::IntRect GetPictureRect() override { return mPictureRect; }
 
   ID3D11Texture2D* GetTexture() const;
 
 private:
   gfx::IntSize mSize;
   gfx::IntRect mPictureRect;
   RefPtr<TextureClient> mTextureClient;
--- a/gfx/layers/D3D9SurfaceImage.cpp
+++ b/gfx/layers/D3D9SurfaceImage.cpp
@@ -123,20 +123,20 @@ D3D9SurfaceImage::GetShareHandle() const
 
 gfx::IntSize
 D3D9SurfaceImage::GetSize()
 {
   return mSize;
 }
 
 TextureClient*
-D3D9SurfaceImage::GetTextureClient(TextureForwarder* aForwarder)
+D3D9SurfaceImage::GetTextureClient(KnowsCompositor* aForwarder)
 {
   MOZ_ASSERT(mTextureClient);
-  MOZ_ASSERT(mTextureClient->GetAllocator() == aForwarder);
+  MOZ_ASSERT(mTextureClient->GetAllocator() == aForwarder->GetTextureForwarder());
   return mTextureClient;
 }
 
 already_AddRefed<gfx::SourceSurface>
 D3D9SurfaceImage::GetAsSourceSurface()
 {
   if (!mTexture) {
     return nullptr;
@@ -202,17 +202,18 @@ D3D9RecycleAllocator::Allocate(gfx::Surf
                                TextureFlags aTextureFlags,
                                TextureAllocationFlags aAllocFlags)
 {
   TextureData* data = DXGID3D9TextureData::Create(aSize, aFormat, aTextureFlags, mDevice);
   if (!data) {
     return nullptr;
   }
 
-  return MakeAndAddRef<TextureClient>(data, aTextureFlags, mSurfaceAllocator);
+  return MakeAndAddRef<TextureClient>(data, aTextureFlags,
+                                      mSurfaceAllocator->GetTextureForwarder());
 }
 
 already_AddRefed<TextureClient>
 D3D9RecycleAllocator::CreateOrRecycleClient(gfx::SurfaceFormat aFormat,
                                             const gfx::IntSize& aSize)
 {
   return CreateOrRecycle(aFormat, aSize, BackendSelector::Content,
                          TextureFlags::DEFAULT);
--- a/gfx/layers/D3D9SurfaceImage.h
+++ b/gfx/layers/D3D9SurfaceImage.h
@@ -14,17 +14,17 @@
 namespace mozilla {
 namespace layers {
 
 class TextureClient;
 
 class D3D9RecycleAllocator : public TextureClientRecycleAllocator
 {
 public:
-  explicit D3D9RecycleAllocator(TextureForwarder* aAllocator,
+  explicit D3D9RecycleAllocator(KnowsCompositor* aAllocator,
                                 IDirect3DDevice9* aDevice)
     : TextureClientRecycleAllocator(aAllocator)
     , mDevice(aDevice)
   {}
 
   already_AddRefed<TextureClient>
   CreateOrRecycleClient(gfx::SurfaceFormat aFormat,
                         const gfx::IntSize& aSize);
@@ -55,17 +55,17 @@ public:
 
   // Returns the description of the shared surface.
   const D3DSURFACE_DESC& GetDesc() const;
 
   gfx::IntSize GetSize() override;
 
   virtual already_AddRefed<gfx::SourceSurface> GetAsSourceSurface() override;
 
-  virtual TextureClient* GetTextureClient(TextureForwarder* aForwarder) override;
+  virtual TextureClient* GetTextureClient(KnowsCompositor* aForwarder) override;
 
   already_AddRefed<IDirect3DSurface9> GetD3D9Surface();
 
   HANDLE GetShareHandle() const;
 
   virtual bool IsValid() override { return mValid; }
 
   void Invalidate() { mValid = false; }
--- a/gfx/layers/GPUVideoImage.h
+++ b/gfx/layers/GPUVideoImage.h
@@ -35,17 +35,17 @@ public:
   ~GPUVideoImage() override {}
 
   gfx::IntSize GetSize() override { return mSize; }
 
   // TODO: We really want to be able to support this, but it's complex, since we need to readback
   // in the other process and send it across.
   virtual already_AddRefed<gfx::SourceSurface> GetAsSourceSurface() override { return nullptr; }
 
-  virtual TextureClient* GetTextureClient(TextureForwarder* aForwarder) override
+  virtual TextureClient* GetTextureClient(KnowsCompositor* aForwarder) override
   {
     MOZ_ASSERT(aForwarder == ImageBridgeChild::GetSingleton(), "Must only use GPUVideo on ImageBridge");
     return mTextureClient;
   }
 
 private:
   gfx::IntSize mSize;
   RefPtr<TextureClient> mTextureClient;
--- a/gfx/layers/IMFYCbCrImage.cpp
+++ b/gfx/layers/IMFYCbCrImage.cpp
@@ -150,17 +150,17 @@ static bool UploadData(IDirect3DDevice9*
              aSrcSize.width);
     }
   }
 
   return FinishTextures(aDevice, aTexture, surf);
 }
 
 TextureClient*
-IMFYCbCrImage::GetD3D9TextureClient(TextureForwarder* aForwarder)
+IMFYCbCrImage::GetD3D9TextureClient(KnowsCompositor* aForwarder)
 {
   RefPtr<IDirect3DDevice9> device = DeviceManagerD3D9::GetDevice();
   if (!device) {
     return nullptr;
   }
 
   RefPtr<IDirect3DTexture9> textureY;
   HANDLE shareHandleY = 0;
@@ -202,30 +202,29 @@ IMFYCbCrImage::GetD3D9TextureClient(Text
     break;
   }
 
   if (!valid) {
     return nullptr;
   }
 
   mTextureClient = TextureClient::CreateWithData(
-    DXGIYCbCrTextureData::Create(aForwarder,
-                                 TextureFlags::DEFAULT,
+    DXGIYCbCrTextureData::Create(TextureFlags::DEFAULT,
                                  textureY, textureCb, textureCr,
                                  shareHandleY, shareHandleCb, shareHandleCr,
                                  GetSize(), mData.mYSize, mData.mCbCrSize),
     TextureFlags::DEFAULT,
-    aForwarder
+    aForwarder->GetTextureForwarder()
   );
 
   return mTextureClient;
 }
 
 TextureClient*
-IMFYCbCrImage::GetTextureClient(TextureForwarder* aForwarder)
+IMFYCbCrImage::GetTextureClient(KnowsCompositor* aForwarder)
 {
   if (mTextureClient) {
     return mTextureClient;
   }
 
   RefPtr<ID3D11Device> device =
     gfx::DeviceManagerDx::Get()->GetContentDevice();
 
@@ -270,21 +269,20 @@ IMFYCbCrImage::GetTextureClient(TextureF
   // it appears that D3D doesn't include the initial memory upload within this
   // synchronization. Add an empty lock/unlock pair since that appears to
   // be sufficient to make sure we synchronize.
   {
     AutoLockTexture lockCr(textureCr);
   }
 
   mTextureClient = TextureClient::CreateWithData(
-    DXGIYCbCrTextureData::Create(aForwarder,
-                                 TextureFlags::DEFAULT,
+    DXGIYCbCrTextureData::Create(TextureFlags::DEFAULT,
                                  textureY, textureCb, textureCr,
                                  GetSize(), mData.mYSize, mData.mCbCrSize),
     TextureFlags::DEFAULT,
-    aForwarder
+    aForwarder->GetTextureForwarder()
   );
 
   return mTextureClient;
 }
 
 } // namespace layers
 } // namespace mozilla
--- a/gfx/layers/IMFYCbCrImage.h
+++ b/gfx/layers/IMFYCbCrImage.h
@@ -15,21 +15,21 @@ namespace layers {
 
 class IMFYCbCrImage : public RecyclingPlanarYCbCrImage
 {
 public:
   IMFYCbCrImage(IMFMediaBuffer* aBuffer, IMF2DBuffer* a2DBuffer);
 
   virtual bool IsValid() { return true; }
 
-  virtual TextureClient* GetTextureClient(TextureForwarder* aForwarder) override;
+  virtual TextureClient* GetTextureClient(KnowsCompositor* aForwarder) override;
 
 protected:
 
-  TextureClient* GetD3D9TextureClient(TextureForwarder* aForwarder);
+  TextureClient* GetD3D9TextureClient(KnowsCompositor* aForwarder);
 
   ~IMFYCbCrImage();
 
   RefPtr<IMFMediaBuffer> mBuffer;
   RefPtr<IMF2DBuffer> m2DBuffer;
   RefPtr<TextureClient> mTextureClient;
 };
 
--- a/gfx/layers/ImageContainer.cpp
+++ b/gfx/layers/ImageContainer.cpp
@@ -734,17 +734,17 @@ SourceSurfaceImage::SourceSurfaceImage(g
     mTextureFlags(TextureFlags::DEFAULT)
 {}
 
 SourceSurfaceImage::~SourceSurfaceImage()
 {
 }
 
 TextureClient*
-SourceSurfaceImage::GetTextureClient(TextureForwarder* aForwarder)
+SourceSurfaceImage::GetTextureClient(KnowsCompositor* aForwarder)
 {
   if (!aForwarder) {
     return nullptr;
   }
 
   RefPtr<TextureClient> textureClient = mTextureClients.Get(aForwarder->GetSerial());
   if (textureClient) {
     return textureClient;
@@ -755,17 +755,16 @@ SourceSurfaceImage::GetTextureClient(Tex
   if (!surface) {
     return nullptr;
   }
 
   if (!textureClient) {
     // gfx::BackendType::NONE means default to content backend
     textureClient = TextureClient::CreateFromSurface(aForwarder,
                                                      surface,
-                                                     aForwarder->GetCompositorBackendType(),
                                                      BackendSelector::Content,
                                                      mTextureFlags,
                                                      ALLOC_DEFAULT);
   }
   if (!textureClient) {
     return nullptr;
   }
 
--- a/gfx/layers/ImageContainer.h
+++ b/gfx/layers/ImageContainer.h
@@ -146,17 +146,17 @@ namespace layers {
 
 class ImageClient;
 class ImageCompositeNotification;
 class ImageContainerChild;
 class PImageContainerChild;
 class SharedPlanarYCbCrImage;
 class PlanarYCbCrImage;
 class TextureClient;
-class TextureForwarder;
+class KnowsCompositor;
 class GrallocImage;
 class NVImage;
 
 struct ImageBackendData
 {
   virtual ~ImageBackendData() {}
 
 protected:
@@ -223,17 +223,17 @@ public:
   virtual bool IsValid() { return true; }
 
   virtual uint8_t* GetBuffer() { return nullptr; }
 
   /**
    * For use with the TextureForwarder only (so that the later can
    * synchronize the TextureClient with the TextureHost).
    */
-  virtual TextureClient* GetTextureClient(TextureForwarder* aForwarder) { return nullptr; }
+  virtual TextureClient* GetTextureClient(KnowsCompositor* aForwarder) { return nullptr; }
 
   /* Access to derived classes. */
   virtual EGLImageImage* AsEGLImageImage() { return nullptr; }
   virtual GLImage* AsGLImage() { return nullptr; }
 #ifdef MOZ_WIDGET_ANDROID
   virtual SurfaceTextureImage* AsSurfaceTextureImage() { return nullptr; }
 #endif
 #ifdef XP_MACOSX
@@ -885,17 +885,17 @@ class SourceSurfaceImage final : public 
 public:
   virtual already_AddRefed<gfx::SourceSurface> GetAsSourceSurface() override
   {
     RefPtr<gfx::SourceSurface> surface(mSourceSurface);
     return surface.forget();
   }
 
   void SetTextureFlags(TextureFlags aTextureFlags) { mTextureFlags = aTextureFlags; }
-  virtual TextureClient* GetTextureClient(TextureForwarder* aForwarder) override;
+  virtual TextureClient* GetTextureClient(KnowsCompositor* aForwarder) override;
 
   virtual gfx::IntSize GetSize() override { return mSize; }
 
   SourceSurfaceImage(const gfx::IntSize& aSize, gfx::SourceSurface* aSourceSurface);
   explicit SourceSurfaceImage(gfx::SourceSurface* aSourceSurface);
   ~SourceSurfaceImage();
 
 private:
--- a/gfx/layers/MacIOSurfaceImage.cpp
+++ b/gfx/layers/MacIOSurfaceImage.cpp
@@ -11,24 +11,24 @@
 #include "mozilla/layers/MacIOSurfaceTextureClientOGL.h"
 #include "mozilla/UniquePtr.h"
 
 using namespace mozilla;
 using namespace mozilla::layers;
 using namespace mozilla::gfx;
 
 TextureClient*
-MacIOSurfaceImage::GetTextureClient(TextureForwarder* aForwarder)
+MacIOSurfaceImage::GetTextureClient(KnowsCompositor* aForwarder)
 {
   if (!mTextureClient) {
     BackendType backend = BackendType::NONE;
     mTextureClient = TextureClient::CreateWithData(
       MacIOSurfaceTextureData::Create(mSurface, backend),
       TextureFlags::DEFAULT,
-      aForwarder
+      aForwarder->GetTextureForwarder()
     );
   }
   return mTextureClient;
 }
 
 already_AddRefed<SourceSurface>
 MacIOSurfaceImage::GetAsSourceSurface()
 {
--- a/gfx/layers/MacIOSurfaceImage.h
+++ b/gfx/layers/MacIOSurfaceImage.h
@@ -26,17 +26,17 @@ public:
 
   gfx::IntSize GetSize() override {
     return gfx::IntSize::Truncate(mSurface->GetDevicePixelWidth(),
                                   mSurface->GetDevicePixelHeight());
   }
 
   virtual already_AddRefed<gfx::SourceSurface> GetAsSourceSurface() override;
 
-  virtual TextureClient* GetTextureClient(TextureForwarder* aForwarder) override;
+  virtual TextureClient* GetTextureClient(KnowsCompositor* aForwarder) override;
 
   virtual MacIOSurfaceImage* AsMacIOSurfaceImage() override {
     return this;
   }
 
 private:
   RefPtr<MacIOSurface> mSurface;
   RefPtr<TextureClient> mTextureClient;
--- a/gfx/layers/PersistentBufferProvider.cpp
+++ b/gfx/layers/PersistentBufferProvider.cpp
@@ -81,19 +81,19 @@ PersistentBufferProviderBasic::Create(gf
   return provider.forget();
 }
 
 
 //static
 already_AddRefed<PersistentBufferProviderShared>
 PersistentBufferProviderShared::Create(gfx::IntSize aSize,
                                        gfx::SurfaceFormat aFormat,
-                                       CompositableForwarder* aFwd)
+                                       KnowsCompositor* aFwd)
 {
-  if (!aFwd || !aFwd->IPCOpen()) {
+  if (!aFwd || !aFwd->GetTextureForwarder()->IPCOpen()) {
     return nullptr;
   }
 
   RefPtr<TextureClient> texture = TextureClient::CreateForDrawing(
     aFwd, aFormat, aSize,
     BackendSelector::Canvas,
     TextureFlags::DEFAULT,
     TextureAllocationFlags::ALLOC_DEFAULT
@@ -105,17 +105,17 @@ PersistentBufferProviderShared::Create(g
 
   RefPtr<PersistentBufferProviderShared> provider =
     new PersistentBufferProviderShared(aSize, aFormat, aFwd, texture);
   return provider.forget();
 }
 
 PersistentBufferProviderShared::PersistentBufferProviderShared(gfx::IntSize aSize,
                                                                gfx::SurfaceFormat aFormat,
-                                                               CompositableForwarder* aFwd,
+                                                               KnowsCompositor* aFwd,
                                                                RefPtr<TextureClient>& aTexture)
 
 : mSize(aSize)
 , mFormat(aFormat)
 , mFwd(aFwd)
 , mFront(Nothing())
 {
   if (mTextures.append(aTexture)) {
@@ -131,33 +131,33 @@ PersistentBufferProviderShared::~Persist
   if (IsActivityTracked()) {
     mFwd->GetActiveResourceTracker().RemoveObject(this);
   }
 
   Destroy();
 }
 
 bool
-PersistentBufferProviderShared::SetForwarder(CompositableForwarder* aFwd)
+PersistentBufferProviderShared::SetForwarder(KnowsCompositor* aFwd)
 {
   MOZ_ASSERT(aFwd);
   if (!aFwd) {
     return false;
   }
 
   if (mFwd == aFwd) {
     // The forwarder should not change most of the time.
     return true;
   }
 
   if (IsActivityTracked()) {
     mFwd->GetActiveResourceTracker().RemoveObject(this);
   }
 
-  if (mFwd->AsTextureForwarder() != aFwd->AsTextureForwarder() ||
+  if (mFwd->GetTextureForwarder() != aFwd->GetTextureForwarder() ||
       mFwd->GetCompositorBackendType() != aFwd->GetCompositorBackendType()) {
     // We are going to be used with an different and/or incompatible forwarder.
     // This should be extremely rare. We have to copy the front buffer into a
     // texture that is compatible with the new forwarder.
 
     // Grab the current front buffer.
     RefPtr<TextureClient> prevTexture = GetTexture(mFront);
 
@@ -220,17 +220,17 @@ PersistentBufferProviderShared::GetTextu
     return nullptr;
   }
   return mTextures[aIndex.value()];
 }
 
 already_AddRefed<gfx::DrawTarget>
 PersistentBufferProviderShared::BorrowDrawTarget(const gfx::IntRect& aPersistedRect)
 {
-  if (!mFwd->IPCOpen()) {
+  if (!mFwd->GetTextureForwarder()->IPCOpen()) {
     return nullptr;
   }
 
   MOZ_ASSERT(!mSnapshot);
 
   if (IsActivityTracked()) {
     mFwd->GetActiveResourceTracker().MarkUsed(this);
   } else {
@@ -437,9 +437,9 @@ PersistentBufferProviderShared::Destroy(
       texture->Unlock();
     }
   }
 
   mTextures.clear();
 }
 
 } // namespace layers
-} // namespace mozilla
\ No newline at end of file
+} // namespace mozilla
--- a/gfx/layers/PersistentBufferProvider.h
+++ b/gfx/layers/PersistentBufferProvider.h
@@ -4,17 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef MOZILLA_GFX_PersistentBUFFERPROVIDER_H
 #define MOZILLA_GFX_PersistentBUFFERPROVIDER_H
 
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/RefPtr.h"             // for RefPtr, already_AddRefed, etc
 #include "mozilla/layers/LayersTypes.h"
-#include "mozilla/layers/CompositableForwarder.h"
+#include "mozilla/layers/TextureForwarder.h"
 #include "mozilla/gfx/Types.h"
 #include "mozilla/Vector.h"
 
 namespace mozilla {
 
 namespace gfx {
   class SourceSurface;
   class DrawTarget;
@@ -59,17 +59,17 @@ public:
   virtual already_AddRefed<gfx::SourceSurface> BorrowSnapshot() = 0;
 
   virtual void ReturnSnapshot(already_AddRefed<gfx::SourceSurface> aSnapshot) = 0;
 
   virtual TextureClient* GetTextureClient() { return nullptr; }
 
   virtual void OnShutdown() {}
 
-  virtual bool SetForwarder(CompositableForwarder* aFwd) { return true; }
+  virtual bool SetForwarder(KnowsCompositor* aFwd) { return true; }
 
   /**
    * Return true if this provider preserves the drawing state (clips, transforms,
    * etc.) across frames. In practice this means users of the provider can skip
    * popping all of the clips at the end of the frames and pushing them back at
    * the beginning of the following frames, which can be costly (cf. bug 1294351).
    */
   virtual bool PreservesDrawingState() const = 0;
@@ -112,17 +112,17 @@ private:
 class PersistentBufferProviderShared : public PersistentBufferProvider
                                      , public ActiveResource
 {
 public:
   MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(PersistentBufferProviderShared, override)
 
   static already_AddRefed<PersistentBufferProviderShared>
   Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
-         CompositableForwarder* aFwd);
+         KnowsCompositor* aFwd);
 
   virtual LayersBackend GetType() override { return LayersBackend::LAYERS_CLIENT; }
 
   virtual already_AddRefed<gfx::DrawTarget> BorrowDrawTarget(const gfx::IntRect& aPersistedRect) override;
 
   virtual bool ReturnDrawTarget(already_AddRefed<gfx::DrawTarget> aDT) override;
 
   virtual already_AddRefed<gfx::SourceSurface> BorrowSnapshot() override;
@@ -130,34 +130,34 @@ public:
   virtual void ReturnSnapshot(already_AddRefed<gfx::SourceSurface> aSnapshot) override;
 
   virtual TextureClient* GetTextureClient() override;
 
   virtual void NotifyInactive() override;
 
   virtual void OnShutdown() override { Destroy(); }
 
-  virtual bool SetForwarder(CompositableForwarder* aFwd) override;
+  virtual bool SetForwarder(KnowsCompositor* aFwd) override;
 
   virtual bool PreservesDrawingState() const override { return false; }
 protected:
   PersistentBufferProviderShared(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
-                                 CompositableForwarder* aFwd,
+                                 KnowsCompositor* aFwd,
                                  RefPtr<TextureClient>& aTexture);
 
   ~PersistentBufferProviderShared();
 
   TextureClient* GetTexture(Maybe<uint32_t> aIndex);
   bool CheckIndex(uint32_t aIndex) { return aIndex < mTextures.length(); }
 
   void Destroy();
 
   gfx::IntSize mSize;
   gfx::SurfaceFormat mFormat;
-  RefPtr<CompositableForwarder> mFwd;
+  RefPtr<KnowsCompositor> mFwd;
   Vector<RefPtr<TextureClient>, 4> mTextures;
   // Offset of the texture in mTextures that the canvas uses.
   Maybe<uint32_t> mBack;
   // Offset of the texture in mTextures that is presented to the compositor.
   Maybe<uint32_t> mFront;
 
   RefPtr<gfx::DrawTarget> mDrawTarget;
   RefPtr<gfx::SourceSurface > mSnapshot;
--- a/gfx/layers/TextureDIB.cpp
+++ b/gfx/layers/TextureDIB.cpp
@@ -20,26 +20,27 @@ namespace layers {
   * The coresponding TextureHost depends on the compositor
   */
 class MemoryDIBTextureData : public DIBTextureData
 {
 public:
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
   virtual TextureData*
-  CreateSimilar(ClientIPCAllocator* aAllocator,
+  CreateSimilar(LayersIPCChannel* aAllocator,
+                LayersBackend aLayersBackend,
                 TextureFlags aFlags = TextureFlags::DEFAULT,
                 TextureAllocationFlags aAllocFlags = ALLOC_DEFAULT) const override;
 
   virtual bool UpdateFromSurface(gfx::SourceSurface* aSurface) override;
 
   static
   DIBTextureData* Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat);
 
-  virtual void Deallocate(ClientIPCAllocator* aAllocator) override
+  virtual void Deallocate(LayersIPCChannel* aAllocator) override
   {
     mSurface = nullptr;
   }
 
   MemoryDIBTextureData(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                        gfxWindowsSurface* aSurface)
   : DIBTextureData(aSize, aFormat, aSurface)
   {
@@ -57,40 +58,41 @@ public:
   * The coresponding TextureHost depends on the compositor
   */
 class ShmemDIBTextureData : public DIBTextureData
 {
 public:
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
   virtual TextureData*
-  CreateSimilar(ClientIPCAllocator* aAllocator,
+  CreateSimilar(LayersIPCChannel* aAllocator,
+                LayersBackend aLayersBackend,
                 TextureFlags aFlags = TextureFlags::DEFAULT,
                 TextureAllocationFlags aAllocFlags = ALLOC_DEFAULT) const override;
 
   virtual bool UpdateFromSurface(gfx::SourceSurface* aSurface) override;
 
   static
   DIBTextureData* Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
-                         ClientIPCAllocator* aAllocator);
+                         LayersIPCChannel* aAllocator);
 
   void DeallocateData()
   {
     if (mSurface) {
       ::DeleteObject(mBitmap);
       ::DeleteDC(mDC);
       ::CloseHandle(mFileMapping);
       mBitmap = NULL;
       mDC = NULL;
       mFileMapping = NULL;
       mSurface = nullptr;
     }
   }
 
-  virtual void Deallocate(ClientIPCAllocator* aAllocator) override
+  virtual void Deallocate(LayersIPCChannel* aAllocator) override
   {
     DeallocateData();
   }
 
   ShmemDIBTextureData(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                       gfxWindowsSurface* aSurface,
                       HANDLE aFileMapping, HANDLE aHostHandle,
                       HDC aDC, HBITMAP aBitmap)
@@ -132,33 +134,34 @@ DIBTextureData::FillInfo(TextureData::In
 already_AddRefed<gfx::DrawTarget>
 DIBTextureData::BorrowDrawTarget()
 {
   return gfxPlatform::GetPlatform()->CreateDrawTargetForSurface(mSurface, mSize);
 }
 
 DIBTextureData*
 DIBTextureData::Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
-                       ClientIPCAllocator* aAllocator)
+                       LayersIPCChannel* aAllocator)
 {
   if (!aAllocator) {
     return nullptr;
   }
   if (aFormat == gfx::SurfaceFormat::UNKNOWN) {
     return nullptr;
   }
   if (aAllocator->IsSameProcess()) {
     return MemoryDIBTextureData::Create(aSize, aFormat);
   } else {
     return ShmemDIBTextureData::Create(aSize, aFormat, aAllocator);
   }
 }
 
 TextureData*
-MemoryDIBTextureData::CreateSimilar(ClientIPCAllocator* aAllocator,
+MemoryDIBTextureData::CreateSimilar(LayersIPCChannel* aAllocator,
+                                    LayersBackend aLayersBackend,
                                     TextureFlags aFlags,
                                     TextureAllocationFlags aAllocFlags) const
 {
   if (!aAllocator) {
     return nullptr;
   }
   return MemoryDIBTextureData::Create(mSize, mFormat);
 }
@@ -211,17 +214,18 @@ MemoryDIBTextureData::UpdateFromSurface(
            srcSurf->GetSize().width * BytesPerPixel(srcSurf->GetFormat()));
   }
 
   srcSurf->Unmap();
   return true;
 }
 
 TextureData*
-ShmemDIBTextureData::CreateSimilar(ClientIPCAllocator* aAllocator,
+ShmemDIBTextureData::CreateSimilar(LayersIPCChannel* aAllocator,
+                                   LayersBackend aLayersBackend,
                                    TextureFlags aFlags,
                                    TextureAllocationFlags aAllocFlags) const
 {
   if (!aAllocator) {
     return nullptr;
   }
   return ShmemDIBTextureData::Create(mSize, mFormat, aAllocator);
 }
@@ -275,17 +279,17 @@ ShmemDIBTextureData::Serialize(SurfaceDe
 
   ::GdiFlush();
   aOutDescriptor = SurfaceDescriptorFileMapping((WindowsHandle)mHostHandle, mFormat, mSize);
   return true;
 }
 
 DIBTextureData*
 ShmemDIBTextureData::Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
-                            ClientIPCAllocator* aAllocator)
+                            LayersIPCChannel* aAllocator)
 {
   MOZ_ASSERT(aAllocator->GetParentPid() != base::ProcessId());
 
   DWORD mapSize = aSize.width * aSize.height * BytesPerPixel(aFormat);
   HANDLE fileMapping = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, mapSize, NULL);
 
   if (!fileMapping) {
     gfxCriticalError() << "Failed to create memory file mapping for " << mapSize << " bytes.";
--- a/gfx/layers/TextureDIB.h
+++ b/gfx/layers/TextureDIB.h
@@ -23,17 +23,17 @@ public:
   virtual void Unlock() override {}
 
   virtual void FillInfo(TextureData::Info& aInfo) const override;
 
   virtual already_AddRefed<gfx::DrawTarget> BorrowDrawTarget() override;
 
   static
   DIBTextureData* Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
-                         ClientIPCAllocator* aAllocator);
+                         LayersIPCChannel* aAllocator);
 
 protected:
   DIBTextureData(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                  gfxWindowsSurface* aSurface)
   : mSurface(aSurface)
   , mSize(aSize)
   , mFormat(aFormat)
   {
--- a/gfx/layers/TextureWrapperImage.cpp
+++ b/gfx/layers/TextureWrapperImage.cpp
@@ -44,15 +44,15 @@ TextureWrapperImage::GetAsSourceSurface(
   if (!dt) {
     return nullptr;
   }
 
   return dt->Snapshot();
 }
 
 TextureClient*
-TextureWrapperImage::GetTextureClient(TextureForwarder* aForwarder)
+TextureWrapperImage::GetTextureClient(KnowsCompositor* aForwarder)
 {
   return mTextureClient;
 }
 
 } // namespace layers
 } // namespace mozilla
--- a/gfx/layers/TextureWrapperImage.h
+++ b/gfx/layers/TextureWrapperImage.h
@@ -19,17 +19,17 @@ class TextureWrapperImage final : public
 {
 public:
   TextureWrapperImage(TextureClient* aClient, const gfx::IntRect& aPictureRect);
   ~TextureWrapperImage() override;
 
   gfx::IntSize GetSize() override;
   gfx::IntRect GetPictureRect() override;
   already_AddRefed<gfx::SourceSurface> GetAsSourceSurface() override;
-  TextureClient* GetTextureClient(TextureForwarder* aForwarder) override;
+  TextureClient* GetTextureClient(KnowsCompositor* aForwarder) override;
 
 private:
   gfx::IntRect mPictureRect;
   RefPtr<TextureClient> mTextureClient;
 };
 
 } // namespace layers
 } // namespace mozilla
--- a/gfx/layers/basic/TextureClientX11.cpp
+++ b/gfx/layers/basic/TextureClientX11.cpp
@@ -101,32 +101,33 @@ X11TextureData::UpdateFromSurface(gfx::S
   }
 
   dt->CopySurface(aSurface, IntRect(IntPoint(), aSurface->GetSize()), IntPoint());
 
   return true;
 }
 
 void
-X11TextureData::Deallocate(ClientIPCAllocator*)
+X11TextureData::Deallocate(LayersIPCChannel*)
 {
   mSurface = nullptr;
 }
 
 TextureData*
-X11TextureData::CreateSimilar(ClientIPCAllocator* aAllocator,
+X11TextureData::CreateSimilar(LayersIPCChannel* aAllocator,
+                              LayersBackend aLayersBackend,
                               TextureFlags aFlags,
                               TextureAllocationFlags aAllocFlags) const
 {
   return X11TextureData::Create(mSize, mFormat, aFlags, aAllocator);
 }
 
 X11TextureData*
 X11TextureData::Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
-                       TextureFlags aFlags, ClientIPCAllocator* aAllocator)
+                       TextureFlags aFlags, LayersIPCChannel* aAllocator)
 {
   MOZ_ASSERT(aSize.width >= 0 && aSize.height >= 0);
   if (aSize.width <= 0 || aSize.height <= 0 ||
       aSize.width > XLIB_IMAGE_SIDE_SIZE_LIMIT ||
       aSize.height > XLIB_IMAGE_SIDE_SIZE_LIMIT) {
     gfxDebug() << "Asking for X11 surface of invalid size " << aSize.width << "x" << aSize.height;
     return nullptr;
   }
--- a/gfx/layers/basic/TextureClientX11.h
+++ b/gfx/layers/basic/TextureClientX11.h
@@ -12,32 +12,33 @@
 
 namespace mozilla {
 namespace layers {
 
 class X11TextureData : public TextureData
 {
 public:
   static X11TextureData* Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
-                                TextureFlags aFlags, ClientIPCAllocator* aAllocator);
+                                TextureFlags aFlags, LayersIPCChannel* aAllocator);
 
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
   virtual bool Lock(OpenMode aMode, FenceHandle*) override;
 
   virtual void Unlock() override;
 
   virtual void FillInfo(TextureData::Info& aInfo) const override;
 
   virtual already_AddRefed<gfx::DrawTarget> BorrowDrawTarget() override;
 
-  virtual void Deallocate(ClientIPCAllocator*) override;
+  virtual void Deallocate(LayersIPCChannel*) override;
 
   virtual TextureData*
-  CreateSimilar(ClientIPCAllocator* aAllocator,
+  CreateSimilar(LayersIPCChannel* aAllocator,
+                LayersBackend aLayersBackend,
                 TextureFlags aFlags = TextureFlags::DEFAULT,
                 TextureAllocationFlags aAllocFlags = ALLOC_DEFAULT) const override;
 
   virtual bool UpdateFromSurface(gfx::SourceSurface* aSurface) override;
 
 protected:
   X11TextureData(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                  bool aClientDeallocation, bool aIsCrossProcess,
--- a/gfx/layers/client/CanvasClient.cpp
+++ b/gfx/layers/client/CanvasClient.cpp
@@ -206,25 +206,25 @@ CanvasClientSharedSurface::~CanvasClient
 // For formats compatible with R8G8B8A8.
 static inline void SwapRB_R8G8B8A8(uint8_t* pixel) {
   // [RR, GG, BB, AA]
   Swap(pixel[0], pixel[2]);
 }
 
 class TexClientFactory
 {
-  ClientIPCAllocator* const mAllocator;
+  CompositableForwarder* const mAllocator;
   const bool mHasAlpha;
   const gfx::IntSize mSize;
   const gfx::BackendType mBackendType;
   const TextureFlags mBaseTexFlags;
   const LayersBackend mLayersBackend;
 
 public:
-  TexClientFactory(ClientIPCAllocator* allocator, bool hasAlpha,
+  TexClientFactory(CompositableForwarder* allocator, bool hasAlpha,
                    const gfx::IntSize& size, gfx::BackendType backendType,
                    TextureFlags baseTexFlags, LayersBackend layersBackend)
     : mAllocator(allocator)
     , mHasAlpha(hasAlpha)
     , mSize(size)
     , mBackendType(backendType)
     , mBaseTexFlags(baseTexFlags)
     , mLayersBackend(layersBackend)
@@ -262,17 +262,17 @@ public:
       }
     }
 
     return ret.forget();
   }
 };
 
 static already_AddRefed<TextureClient>
-TexClientFromReadback(SharedSurface* src, ClientIPCAllocator* allocator,
+TexClientFromReadback(SharedSurface* src, CompositableForwarder* allocator,
                       TextureFlags baseFlags, LayersBackend layersBackend)
 {
   auto backendType = gfx::BackendType::CAIRO;
   TexClientFactory factory(allocator, src->mHasAlpha, src->mSize, backendType,
                            baseFlags, layersBackend);
 
   RefPtr<TextureClient> texClient;
 
@@ -418,17 +418,17 @@ CanvasClientSharedSurface::UpdateRendere
   } else if (layer && layer->mIsMirror) {
     mShSurfClient = CloneSurface(gl->Screen()->Front()->Surf(), layer->mFactory.get());
     if (!mShSurfClient) {
       return;
     }
   } else {
     mShSurfClient = gl->Screen()->Front();
     if (mShSurfClient && mShSurfClient->GetAllocator() &&
-        mShSurfClient->GetAllocator()->AsCompositableForwarder() != GetForwarder()) {
+        mShSurfClient->GetAllocator() != GetForwarder()->GetTextureForwarder()) {
       mShSurfClient = CloneSurface(mShSurfClient->Surf(), gl->Screen()->Factory());
     }
     if (!mShSurfClient) {
       return;
     }
   }
   MOZ_ASSERT(mShSurfClient);
 
--- a/gfx/layers/client/ClientLayerManager.h
+++ b/gfx/layers/client/ClientLayerManager.h
@@ -87,17 +87,17 @@ public:
   virtual already_AddRefed<CanvasLayer> CreateCanvasLayer() override;
   virtual already_AddRefed<ReadbackLayer> CreateReadbackLayer() override;
   virtual already_AddRefed<ColorLayer> CreateColorLayer() override;
   virtual already_AddRefed<RefLayer> CreateRefLayer() override;
 
   void UpdateTextureFactoryIdentifier(const TextureFactoryIdentifier& aNewIdentifier);
   TextureFactoryIdentifier GetTextureFactoryIdentifier()
   {
-    return mForwarder->GetTextureFactoryIdentifier();
+    return AsShadowForwarder()->GetTextureFactoryIdentifier();
   }
 
   virtual void FlushRendering() override;
   void SendInvalidRegion(const nsIntRegion& aRegion);
 
   virtual uint32_t StartFrameTimeRecording(int32_t aBufferSize) override;
 
   virtual void StopFrameTimeRecording(uint32_t         aStartIndex,
--- a/gfx/layers/client/CompositableClient.cpp
+++ b/gfx/layers/client/CompositableClient.cpp
@@ -30,19 +30,19 @@ using namespace mozilla::gfx;
 void
 RemoveTextureFromCompositableTracker::ReleaseTextureClient()
 {
   if (mTextureClient &&
       mTextureClient->GetAllocator() &&
       !mTextureClient->GetAllocator()->UsesImageBridge())
   {
     RefPtr<TextureClientReleaseTask> task = new TextureClientReleaseTask(mTextureClient);
-    RefPtr<ClientIPCAllocator> allocator = mTextureClient->GetAllocator();
+    RefPtr<LayersIPCChannel> allocator = mTextureClient->GetAllocator();
     mTextureClient = nullptr;
-    allocator->AsClientAllocator()->GetMessageLoop()->PostTask(task.forget());
+    allocator->GetMessageLoop()->PostTask(task.forget());
   } else {
     mTextureClient = nullptr;
   }
 }
 
 void
 CompositableClient::InitIPDLActor(PCompositableChild* aActor, uint64_t aAsyncID)
 {
@@ -168,19 +168,18 @@ CompositableClient::CreateTextureClientF
 }
 
 already_AddRefed<TextureClient>
 CompositableClient::CreateTextureClientFromSurface(gfx::SourceSurface* aSurface,
                                                    BackendSelector aSelector,
                                                    TextureFlags aTextureFlags,
                                                    TextureAllocationFlags aAllocFlags)
 {
-  return TextureClient::CreateFromSurface(GetForwarder()->AsTextureForwarder(),
+  return TextureClient::CreateFromSurface(GetForwarder(),
                                           aSurface,
-                                          GetForwarder()->GetCompositorBackendType(),
                                           aSelector,
                                           aTextureFlags | mTextureFlags,
                                           aAllocFlags);
 }
 
 bool
 CompositableClient::AddTextureClient(TextureClient* aClient)
 {
@@ -219,17 +218,17 @@ CompositableClient::GetTextureClientRecy
   if (mTextureClientRecycler) {
     return mTextureClientRecycler;
   }
 
   if (!mForwarder) {
     return nullptr;
   }
 
-  if(!mForwarder->UsesImageBridge()) {
+  if(!mForwarder->GetTextureForwarder()->UsesImageBridge()) {
     MOZ_ASSERT(NS_IsMainThread());
     mTextureClientRecycler = new layers::TextureClientRecycleAllocator(mForwarder);
     return mTextureClientRecycler;
   }
 
   // Handle a case that mForwarder is ImageBridge
 
   if (InImageBridgeChildThread()) {
--- a/gfx/layers/client/ContentClient.cpp
+++ b/gfx/layers/client/ContentClient.cpp
@@ -305,16 +305,17 @@ ContentClientRemoteBuffer::CreateBackBuf
   );
   if (!mTextureClient || !AddTextureClient(mTextureClient)) {
     AbortTextureClientCreation();
     return;
   }
 
   if (mTextureFlags & TextureFlags::COMPONENT_ALPHA) {
     mTextureClientOnWhite = mTextureClient->CreateSimilar(
+      mForwarder->GetCompositorBackendType(),
       mTextureFlags | ExtraTextureFlags(),
       TextureAllocationFlags::ALLOC_CLEAR_BUFFER_WHITE
     );
     if (!mTextureClientOnWhite || !AddTextureClient(mTextureClientOnWhite)) {
       AbortTextureClientCreation();
       return;
     }
   }
--- a/gfx/layers/client/GPUVideoTextureClient.cpp
+++ b/gfx/layers/client/GPUVideoTextureClient.cpp
@@ -28,24 +28,24 @@ GPUVideoTextureData::FillInfo(TextureDat
   aInfo.format = SurfaceFormat::B8G8R8X8;
   aInfo.hasIntermediateBuffer = false;
   aInfo.hasSynchronization = false;
   aInfo.supportsMoz2D = false;
   aInfo.canExposeMappedData = false;
 }
 
 void
-GPUVideoTextureData::Deallocate(ClientIPCAllocator* aAllocator)
+GPUVideoTextureData::Deallocate(LayersIPCChannel* aAllocator)
 {
   dom::VideoDecoderManagerChild::GetSingleton()->DeallocateSurfaceDescriptorGPUVideo(mSD);
   mSD = SurfaceDescriptorGPUVideo();
 }
 
 void
-GPUVideoTextureData::Forget(ClientIPCAllocator* aAllocator)
+GPUVideoTextureData::Forget(LayersIPCChannel* aAllocator)
 {
   // We always need to manually deallocate on the client side.
   // Ideally we'd set up our TextureClient with the DEALLOCATE_CLIENT
   // flag, but that forces texture destruction to be synchronous.
   // Instead let's just deallocate from here as well.
   Deallocate(aAllocator);
 }
 
--- a/gfx/layers/client/GPUVideoTextureClient.h
+++ b/gfx/layers/client/GPUVideoTextureClient.h
@@ -25,19 +25,19 @@ public:
   virtual void FillInfo(TextureData::Info& aInfo) const override;
 
   virtual bool Lock(OpenMode, FenceHandle*) override { return true; };
 
   virtual void Unlock() override {};
 
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
-  virtual void Deallocate(ClientIPCAllocator* aAllocator) override;
+  virtual void Deallocate(LayersIPCChannel* aAllocator) override;
 
-  virtual void Forget(ClientIPCAllocator* aAllocator) override;
+  virtual void Forget(LayersIPCChannel* aAllocator) override;
 
 protected:
   SurfaceDescriptorGPUVideo mSD;
   gfx::IntSize mSize;
 };
 
 } // namespace layers
 } // namespace mozilla
--- a/gfx/layers/client/ImageClient.cpp
+++ b/gfx/layers/client/ImageClient.cpp
@@ -73,17 +73,17 @@ ImageClient::RemoveTexture(TextureClient
   RemoveTextureWithWaiter(aTexture);
 }
 
 void
 ImageClient::RemoveTextureWithWaiter(TextureClient* aTexture,
                                      AsyncTransactionWaiter* aAsyncTransactionWaiter)
 {
   if (aAsyncTransactionWaiter &&
-      GetForwarder()->UsesImageBridge()) {
+      GetForwarder()->GetTextureForwarder()->UsesImageBridge()) {
     RefPtr<AsyncTransactionTracker> request =
       new RemoveTextureFromCompositableTracker(aAsyncTransactionWaiter);
     GetForwarder()->RemoveTextureFromCompositableAsync(request, this, aTexture);
     return;
   }
   MOZ_ASSERT(!aAsyncTransactionWaiter);
   GetForwarder()->RemoveTextureFromCompositable(this, aTexture);
 }
@@ -98,17 +98,17 @@ ImageClientSingle::ImageClientSingle(Com
 TextureInfo ImageClientSingle::GetTextureInfo() const
 {
   return TextureInfo(CompositableType::IMAGE);
 }
 
 void
 ImageClientSingle::FlushAllImages(AsyncTransactionWaiter* aAsyncTransactionWaiter)
 {
-  MOZ_ASSERT(GetForwarder()->UsesImageBridge());
+  MOZ_ASSERT(GetForwarder()->GetTextureForwarder()->UsesImageBridge());
 
   for (auto& b : mBuffers) {
     RemoveTextureWithWaiter(b.mTextureClient, aAsyncTransactionWaiter);
   }
   mBuffers.Clear();
 }
 
 bool
@@ -214,23 +214,23 @@ ImageClientSingle::UpdateImage(ImageCont
         }
       } else if (image->GetFormat() == ImageFormat::SURFACE_TEXTURE ||
                  image->GetFormat() == ImageFormat::EGLIMAGE) {
         gfx::IntSize size = image->GetSize();
 
         if (image->GetFormat() == ImageFormat::EGLIMAGE) {
           EGLImageImage* typedImage = image->AsEGLImageImage();
           texture = EGLImageTextureData::CreateTextureClient(
-            typedImage, size, GetForwarder(), mTextureFlags);
+            typedImage, size, GetForwarder()->GetTextureForwarder(), mTextureFlags);
 #ifdef MOZ_WIDGET_ANDROID
         } else if (image->GetFormat() == ImageFormat::SURFACE_TEXTURE) {
           SurfaceTextureImage* typedImage = image->AsSurfaceTextureImage();
           texture = AndroidSurfaceTextureData::CreateTextureClient(
             typedImage->GetSurfaceTexture(), size, typedImage->GetOriginPos(),
-            GetForwarder(), mTextureFlags
+            GetForwarder()->GetTextureForwarder(), mTextureFlags
           );
 #endif
         } else {
           MOZ_ASSERT(false, "Bad ImageFormat.");
         }
       } else {
         RefPtr<gfx::SourceSurface> surface = image->GetAsSourceSurface();
         MOZ_ASSERT(surface);
--- a/gfx/layers/client/TextureClient.cpp
+++ b/gfx/layers/client/TextureClient.cpp
@@ -70,17 +70,17 @@ namespace layers {
 using namespace mozilla::ipc;
 using namespace mozilla::gl;
 using namespace mozilla::gfx;
 
 struct TextureDeallocParams
 {
   TextureData* data;
   RefPtr<TextureChild> actor;
-  RefPtr<ClientIPCAllocator> allocator;
+  RefPtr<LayersIPCChannel> allocator;
   bool clientDeallocation;
   bool syncDeallocation;
   bool workAroundSharedSurfaceOwnershipIssue;
 };
 
 void DeallocateTextureClient(TextureDeallocParams params);
 
 /**
@@ -114,25 +114,25 @@ public:
   , mMainThreadOnly(false)
   , mIPCOpen(false)
   , mOwnsTextureData(false)
   , mOwnerCalledDestroy(false)
   {}
 
   bool Recv__delete__() override { return true; }
 
-  ClientIPCAllocator* GetAllocator() { return mTextureForwarder; }
+  LayersIPCChannel* GetAllocator() { return mTextureForwarder; }
 
   void ActorDestroy(ActorDestroyReason why) override;
 
   bool IPCOpen() const { return mIPCOpen; }
 
-  void Lock() const { if (mCompositableForwarder && mCompositableForwarder->UsesImageBridge()) { mLock.Enter(); } }
+  void Lock() const { if (mCompositableForwarder && mCompositableForwarder->GetTextureForwarder()->UsesImageBridge()) { mLock.Enter(); } }
 
-  void Unlock() const { if (mCompositableForwarder && mCompositableForwarder->UsesImageBridge()) { mLock.Leave(); } }
+  void Unlock() const { if (mCompositableForwarder && mCompositableForwarder->GetTextureForwarder()->UsesImageBridge()) { mLock.Leave(); } }
 
 private:
 
   // AddIPDLReference and ReleaseIPDLReference are only to be called by CreateIPDLActor
   // and DestroyIPDLActor, respectively. We intentionally make them private to prevent misuse.
   // The purpose of these methods is to be aware of when the IPC system around this
   // actor goes down: mIPCOpen is then set to false.
   void AddIPDLReference() {
@@ -235,25 +235,25 @@ private:
   bool mOwnsTextureData;
   bool mOwnerCalledDestroy;
 
   friend class TextureClient;
   friend void DeallocateTextureClient(TextureDeallocParams params);
 };
 
 
-static void DestroyTextureData(TextureData* aTextureData, ClientIPCAllocator* aAllocator,
+static void DestroyTextureData(TextureData* aTextureData, LayersIPCChannel* aAllocator,
                                bool aDeallocate, bool aMainThreadOnly)
 {
   if (!aTextureData) {
     return;
   }
 
   if (aMainThreadOnly && !NS_IsMainThread()) {
-    RefPtr<ClientIPCAllocator> allocatorRef = aAllocator;
+    RefPtr<LayersIPCChannel> allocatorRef = aAllocator;
     NS_DispatchToMainThread(NS_NewRunnableFunction([aTextureData, allocatorRef, aDeallocate]() -> void {
       DestroyTextureData(aTextureData, allocatorRef, aDeallocate, true);
     }));
     return;
   }
 
   if (aDeallocate) {
     aTextureData->Deallocate(aAllocator);
@@ -347,17 +347,17 @@ DeallocateTextureClient(TextureDeallocPa
     // Nothing to do
     return;
   }
 
   TextureChild* actor = params.actor;
   MessageLoop* ipdlMsgLoop = nullptr;
 
   if (params.allocator) {
-    ipdlMsgLoop = params.allocator->AsClientAllocator()->GetMessageLoop();
+    ipdlMsgLoop = params.allocator->GetMessageLoop();
     if (!ipdlMsgLoop) {
       // An allocator with no message loop means we are too late in the shutdown
       // sequence.
       gfxCriticalError() << "Texture deallocated too late during shutdown";
       return;
     }
   }
 
@@ -380,17 +380,17 @@ DeallocateTextureClient(TextureDeallocPa
     return;
   }
 
   // Below this line, we are either in the IPDL thread or ther is no IPDL
   // thread anymore.
 
   if (!ipdlMsgLoop) {
     // If we don't have a message loop we can't know for sure that we are in
-    // the IPDL thread and use the ClientIPCAllocator.
+    // the IPDL thread and use the LayersIPCChannel.
     // This should ideally not happen outside of gtest, but some shutdown raciness
     // could put us in this situation.
     params.allocator = nullptr;
   }
 
   if (!actor) {
     // We don't have an IPDL actor, probably because we destroyed the TextureClient
     // before sharing it with the compositor. It means the data cannot be owned by
@@ -636,27 +636,27 @@ TextureClient::UpdateFromSurface(gfx::So
       return;
     }
   }
   NS_WARNING("TextureClient::UpdateFromSurface failed");
 }
 
 
 already_AddRefed<TextureClient>
-TextureClient::CreateSimilar(TextureFlags aFlags, TextureAllocationFlags aAllocFlags) const
+TextureClient::CreateSimilar(LayersBackend aLayersBackend, TextureFlags aFlags, TextureAllocationFlags aAllocFlags) const
 {
   MOZ_ASSERT(IsValid());
 
   MOZ_ASSERT(!mIsLocked);
   if (mIsLocked) {
     return nullptr;
   }
 
   LockActor();
-  TextureData* data = mData->CreateSimilar(mAllocator, aFlags, aAllocFlags);
+  TextureData* data = mData->CreateSimilar(mAllocator, aLayersBackend, aFlags, aAllocFlags);
   UnlockActor();
 
   if (!data) {
     return nullptr;
   }
 
   return MakeAndAddRef<TextureClient>(data, aFlags, mAllocator);
 }
@@ -864,17 +864,17 @@ void
 TextureClient::CancelWaitFenceHandleOnImageBridge()
 {
   if (!NeedsFenceHandle() || GetFlags() & TextureFlags::RECYCLE) {
     return;
   }
   ImageBridgeChild::GetSingleton()->CancelWaitFenceHandle(this);
 }
 
-void CancelTextureClientRecycle(uint64_t aTextureId, ClientIPCAllocator* aAllocator)
+void CancelTextureClientRecycle(uint64_t aTextureId, LayersIPCChannel* aAllocator)
 {
   if (!aAllocator) {
     return;
   }
   MessageLoop* msgLoop = nullptr;
   msgLoop = aAllocator->GetMessageLoop();
   if (!msgLoop) {
     return;
@@ -913,27 +913,27 @@ TextureClient::SetRecycleAllocator(IText
   } else {
     ClearRecycleCallback();
   }
 }
 
 bool
 TextureClient::InitIPDLActor(CompositableForwarder* aForwarder)
 {
-  MOZ_ASSERT(aForwarder && aForwarder->GetMessageLoop() == mAllocator->AsClientAllocator()->GetMessageLoop());
+  MOZ_ASSERT(aForwarder && aForwarder->GetTextureForwarder()->GetMessageLoop() == mAllocator->GetMessageLoop());
   if (mActor && !mActor->mDestroyed) {
     CompositableForwarder* currentFwd = mActor->mCompositableForwarder;
     TextureForwarder* currentTexFwd = mActor->mTextureForwarder;
     if (currentFwd != aForwarder) {
       // It's a bit iffy but right now ShadowLayerForwarder inherits TextureForwarder
-      // even though it should not. ShadowLayerForwarder::AsTextureForwarder actually
+      // even though it should not. ShadowLayerForwarder::GetTextureForwarder actually
       // returns a pointer to the CompositorBridgeChild.
       // It's Ok for a texture to move from a ShadowLayerForwarder to another, but
       // not form a CompositorBridgeChild to another (they use different channels).
-      if (currentTexFwd && currentTexFwd != aForwarder->AsTextureForwarder()) {
+      if (currentTexFwd && currentTexFwd != aForwarder->GetTextureForwarder()) {
         gfxCriticalError() << "Attempt to move a texture to a different channel CF.";
         return false;
       }
       if (currentFwd && currentFwd->GetCompositorBackendType() != aForwarder->GetCompositorBackendType()) {
         gfxCriticalError() << "Attempt to move a texture to different compositor backend.";
         return false;
       }
       mActor->mCompositableForwarder = aForwarder;
@@ -942,74 +942,75 @@ TextureClient::InitIPDLActor(Compositabl
   }
   MOZ_ASSERT(!mActor || mActor->mDestroyed, "Cannot use a texture on several IPC channels.");
 
   SurfaceDescriptor desc;
   if (!ToSurfaceDescriptor(desc)) {
     return false;
   }
 
-  mActor = static_cast<TextureChild*>(aForwarder->CreateTexture(desc,
-                                                                aForwarder->GetCompositorBackendType(),
-                                                                GetFlags(),
-                                                                mSerial));
+  mActor = static_cast<TextureChild*>(aForwarder->GetTextureForwarder()->CreateTexture(desc,
+                                                                                      aForwarder->GetCompositorBackendType(),
+                                                                                      GetFlags(),
+                                                                                      mSerial));
   if (!mActor) {
     gfxCriticalError() << static_cast<int32_t>(desc.type()) << ", "
                        << static_cast<int32_t>(aForwarder->GetCompositorBackendType()) << ", "
                        << static_cast<uint32_t>(GetFlags())
                        << ", " << mSerial;
     MOZ_CRASH("GFX: Invalid actor");
   }
   mActor->mCompositableForwarder = aForwarder;
-  mActor->mTextureForwarder = aForwarder->AsTextureForwarder();
+  mActor->mTextureForwarder = aForwarder->GetTextureForwarder();
   mActor->mTextureClient = this;
   mActor->mMainThreadOnly = !!(mFlags & TextureFlags::DEALLOCATE_MAIN_THREAD);
 
   // If the TextureClient is already locked, we have to lock TextureChild's mutex
   // since it will be unlocked in TextureClient::Unlock.
   if (mIsLocked) {
     LockActor();
   }
 
   return mActor->IPCOpen();
 }
 
 bool
-TextureClient::InitIPDLActor(TextureForwarder* aForwarder)
+TextureClient::InitIPDLActor(KnowsCompositor* aForwarder)
 {
-  MOZ_ASSERT(aForwarder && aForwarder->GetMessageLoop() == mAllocator->AsClientAllocator()->GetMessageLoop());
+  MOZ_ASSERT(aForwarder && aForwarder->GetTextureForwarder()->GetMessageLoop() == mAllocator->GetMessageLoop());
+  TextureForwarder* fwd = aForwarder->GetTextureForwarder();
   if (mActor && !mActor->mDestroyed) {
     CompositableForwarder* currentFwd = mActor->mCompositableForwarder;
     TextureForwarder* currentTexFwd = mActor->mTextureForwarder;
 
     if (currentFwd) {
       gfxCriticalError() << "Attempt to remove a texture from a CompositableForwarder.";
       return false;
     }
 
-    if (currentTexFwd && currentTexFwd != aForwarder) {
+    if (currentTexFwd && currentTexFwd != fwd) {
       gfxCriticalError() << "Attempt to move a texture to a different channel TF.";
       return false;
     }
-    mActor->mTextureForwarder = aForwarder;
+    mActor->mTextureForwarder = fwd;
     return true;
   }
   MOZ_ASSERT(!mActor || mActor->mDestroyed, "Cannot use a texture on several IPC channels.");
 
   SurfaceDescriptor desc;
   if (!ToSurfaceDescriptor(desc)) {
     return false;
   }
 
-  mActor = static_cast<TextureChild*>(aForwarder->CreateTexture(desc,
-    aForwarder->GetCompositorBackendType(),
-    GetFlags(),
-    mSerial));
+  mActor = static_cast<TextureChild*>(fwd->CreateTexture(desc,
+                                      aForwarder->GetCompositorBackendType(),
+                                      GetFlags(),
+                                      mSerial));
   MOZ_ASSERT(mActor);
-  mActor->mTextureForwarder = aForwarder;
+  mActor->mTextureForwarder = fwd;
   mActor->mTextureClient = this;
   mActor->mMainThreadOnly = !!(mFlags & TextureFlags::DEALLOCATE_MAIN_THREAD);
 
   // If the TextureClient is already locked, we have to lock TextureChild's mutex
   // since it will be unlocked in TextureClient::Unlock.
   if (mIsLocked) {
     LockActor();
   }
@@ -1034,84 +1035,74 @@ BackendTypeForBackendSelector(LayersBack
     default:
       MOZ_ASSERT_UNREACHABLE("Unknown backend selector");
       return gfx::BackendType::NONE;
   }
 };
 
 // static
 already_AddRefed<TextureClient>
-TextureClient::CreateForDrawing(CompositableForwarder* aAllocator,
+TextureClient::CreateForDrawing(KnowsCompositor* aAllocator,
                                 gfx::SurfaceFormat aFormat,
                                 gfx::IntSize aSize,
                                 BackendSelector aSelector,
                                 TextureFlags aTextureFlags,
                                 TextureAllocationFlags aAllocFlags)
 {
   LayersBackend layersBackend = aAllocator->GetCompositorBackendType();
-  return TextureClient::CreateForDrawing(aAllocator->AsTextureForwarder(),
+  return TextureClient::CreateForDrawing(aAllocator->GetTextureForwarder(),
                                          aFormat, aSize,
                                          layersBackend,
+                                         aAllocator->GetMaxTextureSize(),
                                          aSelector,
                                          aTextureFlags,
                                          aAllocFlags);
 }
 
 // static
 already_AddRefed<TextureClient>
 TextureClient::CreateForDrawing(TextureForwarder* aAllocator,
                                 gfx::SurfaceFormat aFormat,
                                 gfx::IntSize aSize,
                                 LayersBackend aLayersBackend,
+                                int32_t aMaxTextureSize,
                                 BackendSelector aSelector,
                                 TextureFlags aTextureFlags,
                                 TextureAllocationFlags aAllocFlags)
 {
-  // What we want here is the "real" TextureForwarder. ShadowLayerForwarder,
-  // while inheriting TextureForwarder, actually forwards all of its TF methods
-  // to CompositorBridgeChild. In order to avoid odd situations where some
-  // textures point to a ShadowLayerForwarder and some point directly to the
-  // CompositorBridgeChild, we just get the actual TextureForwarder which is
-  // returned by AsTextureForwarder...
-  aAllocator = aAllocator->AsTextureForwarder();
-
   gfx::BackendType moz2DBackend = BackendTypeForBackendSelector(aLayersBackend, aSelector);
 
   // also test the validity of aAllocator
   MOZ_ASSERT(aAllocator && aAllocator->IPCOpen());
   if (!aAllocator || !aAllocator->IPCOpen()) {
     return nullptr;
   }
 
   if (!gfx::Factory::AllowedSurfaceSize(aSize)) {
     return nullptr;
   }
 
   TextureData* data = nullptr;
 
-#if defined(XP_WIN)
-  int32_t maxTextureSize = aAllocator->GetMaxTextureSize();
-#endif
-
 #ifdef XP_WIN
   if (aLayersBackend == LayersBackend::LAYERS_D3D11 &&
       (moz2DBackend == gfx::BackendType::DIRECT2D ||
        moz2DBackend == gfx::BackendType::DIRECT2D1_1 ||
        (!!(aAllocFlags & ALLOC_FOR_OUT_OF_BAND_CONTENT) &&
         DeviceManagerDx::Get()->GetContentDevice())) &&
-      aSize.width <= maxTextureSize &&
-      aSize.height <= maxTextureSize)
+      aSize.width <= aMaxTextureSize &&
+      aSize.height <= aMaxTextureSize)
   {
     data = DXGITextureData::Create(aSize, aFormat, aAllocFlags);
   }
   if (aLayersBackend == LayersBackend::LAYERS_D3D9 &&
       moz2DBackend == gfx::BackendType::CAIRO &&
       aAllocator->IsSameProcess() &&
-      aSize.width <= maxTextureSize &&
-      aSize.height <= maxTextureSize &&
+      aSize.width <= aMaxTextureSize &&
+      aSize.height <= aMaxTextureSize &&
       NS_IsMainThread() &&
       DeviceManagerD3D9::GetDevice()) {
     data = D3D9TextureData::Create(aSize, aFormat, aAllocFlags);
   }
 
   if (!data && aFormat == SurfaceFormat::B8G8R8X8 &&
       moz2DBackend == gfx::BackendType::CAIRO &&
       NS_IsMainThread()) {
@@ -1165,94 +1156,92 @@ TextureClient::CreateForDrawing(TextureF
   // Can't do any better than a buffer texture client.
   return TextureClient::CreateForRawBufferAccess(aAllocator, aFormat, aSize,
                                                  moz2DBackend, aLayersBackend,
                                                  aTextureFlags, aAllocFlags);
 }
 
 // static
 already_AddRefed<TextureClient>
-TextureClient::CreateFromSurface(TextureForwarder* aAllocator,
+TextureClient::CreateFromSurface(KnowsCompositor* aAllocator,
                                  gfx::SourceSurface* aSurface,
-                                 LayersBackend aLayersBackend,
                                  BackendSelector aSelector,
                                  TextureFlags aTextureFlags,
                                  TextureAllocationFlags aAllocFlags)
 {
-  aAllocator = aAllocator->AsTextureForwarder();
-
   // also test the validity of aAllocator
-  MOZ_ASSERT(aAllocator && aAllocator->IPCOpen());
-  if (!aAllocator || !aAllocator->IPCOpen()) {
+  MOZ_ASSERT(aAllocator && aAllocator->GetTextureForwarder()->IPCOpen());
+  if (!aAllocator || !aAllocator->GetTextureForwarder()->IPCOpen()) {
     return nullptr;
   }
 
   gfx::IntSize size = aSurface->GetSize();
 
   if (!gfx::Factory::AllowedSurfaceSize(size)) {
     return nullptr;
   }
 
   TextureData* data = nullptr;
 #if defined(XP_WIN)
-  gfx::BackendType moz2DBackend = BackendTypeForBackendSelector(aLayersBackend, aSelector);
+  LayersBackend layersBackend = aAllocator->GetCompositorBackendType();
+  gfx::BackendType moz2DBackend = BackendTypeForBackendSelector(layersBackend, aSelector);
 
   int32_t maxTextureSize = aAllocator->GetMaxTextureSize();
 
-  if (aLayersBackend == LayersBackend::LAYERS_D3D11 &&
+  if (layersBackend == LayersBackend::LAYERS_D3D11 &&
     (moz2DBackend == gfx::BackendType::DIRECT2D ||
       moz2DBackend == gfx::BackendType::DIRECT2D1_1 ||
       (!!(aAllocFlags & ALLOC_FOR_OUT_OF_BAND_CONTENT) &&
        DeviceManagerDx::Get()->GetContentDevice())) &&
     size.width <= maxTextureSize &&
     size.height <= maxTextureSize)
   {
     data = D3D11TextureData::Create(aSurface, aAllocFlags);
   }
 #endif
 
   if (data) {
-    return MakeAndAddRef<TextureClient>(data, aTextureFlags, aAllocator);
+    return MakeAndAddRef<TextureClient>(data, aTextureFlags, aAllocator->GetTextureForwarder());
   }
 
   // Fall back to using UpdateFromSurface
 
   RefPtr<TextureClient> client = CreateForDrawing(aAllocator, aSurface->GetFormat(), size,
-                                                  aLayersBackend, aSelector, aTextureFlags, aAllocFlags);
+                                                  aSelector, aTextureFlags, aAllocFlags);
   if (!client) {
     return nullptr;
   }
 
   TextureClientAutoLock autoLock(client, OpenMode::OPEN_WRITE_ONLY);
   if (!autoLock.Succeeded()) {
     return nullptr;
   }
 
   client->UpdateFromSurface(aSurface);
   return client.forget();
 }
 
 // static
 already_AddRefed<TextureClient>
-TextureClient::CreateForRawBufferAccess(ClientIPCAllocator* aAllocator,
+TextureClient::CreateForRawBufferAccess(KnowsCompositor* aAllocator,
                                         gfx::SurfaceFormat aFormat,
                                         gfx::IntSize aSize,
                                         gfx::BackendType aMoz2DBackend,
                                         TextureFlags aTextureFlags,
                                         TextureAllocationFlags aAllocFlags)
 {
-  auto fwd = aAllocator->AsCompositableForwarder();
-  auto backend = fwd ? fwd->GetCompositorBackendType() : LayersBackend::LAYERS_NONE;
-  return CreateForRawBufferAccess(aAllocator, aFormat, aSize, aMoz2DBackend,
-                                  backend, aTextureFlags, aAllocFlags);
+  return CreateForRawBufferAccess(aAllocator->GetTextureForwarder(),
+                                  aFormat, aSize, aMoz2DBackend,
+                                  aAllocator->GetCompositorBackendType(),
+                                  aTextureFlags, aAllocFlags);
 }
 
 // static
 already_AddRefed<TextureClient>
-TextureClient::CreateForRawBufferAccess(ClientIPCAllocator* aAllocator,
+TextureClient::CreateForRawBufferAccess(LayersIPCChannel* aAllocator,
                                         gfx::SurfaceFormat aFormat,
                                         gfx::IntSize aSize,
                                         gfx::BackendType aMoz2DBackend,
                                         LayersBackend aLayersBackend,
                                         TextureFlags aTextureFlags,
                                         TextureAllocationFlags aAllocFlags)
 {
   // also test the validity of aAllocator
@@ -1282,64 +1271,66 @@ TextureClient::CreateForRawBufferAccess(
     return nullptr;
   }
 
   return MakeAndAddRef<TextureClient>(texData, aTextureFlags, aAllocator);
 }
 
 // static
 already_AddRefed<TextureClient>
-TextureClient::CreateForYCbCr(ClientIPCAllocator* aAllocator,
+TextureClient::CreateForYCbCr(KnowsCompositor* aAllocator,
                               gfx::IntSize aYSize,
                               gfx::IntSize aCbCrSize,
                               StereoMode aStereoMode,
                               TextureFlags aTextureFlags)
 {
   // The only reason we allow aAllocator to be null is for gtests
-  MOZ_ASSERT(!aAllocator || aAllocator->IPCOpen());
-  if (aAllocator && !aAllocator->IPCOpen()) {
+  MOZ_ASSERT(!aAllocator || aAllocator->GetLayersIPCActor()->IPCOpen());
+  if (aAllocator && !aAllocator->GetLayersIPCActor()->IPCOpen()) {
     return nullptr;
   }
 
   if (!gfx::Factory::AllowedSurfaceSize(aYSize)) {
     return nullptr;
   }
 
   TextureData* data = BufferTextureData::CreateForYCbCr(aAllocator, aYSize, aCbCrSize,
                                                         aStereoMode, aTextureFlags);
   if (!data) {
     return nullptr;
   }
 
-  return MakeAndAddRef<TextureClient>(data, aTextureFlags, aAllocator);
+  return MakeAndAddRef<TextureClient>(data, aTextureFlags,
+                                      aAllocator ? aAllocator->GetTextureForwarder() : nullptr);
 }
 
 // static
 already_AddRefed<TextureClient>
-TextureClient::CreateForYCbCrWithBufferSize(ClientIPCAllocator* aAllocator,
+TextureClient::CreateForYCbCrWithBufferSize(KnowsCompositor* aAllocator,
                                             size_t aSize,
                                             TextureFlags aTextureFlags)
 {
   // also test the validity of aAllocator
-  MOZ_ASSERT(aAllocator && aAllocator->IPCOpen());
-  if (!aAllocator || !aAllocator->IPCOpen()) {
+  MOZ_ASSERT(!aAllocator || aAllocator->GetLayersIPCActor()->IPCOpen());
+  if (aAllocator && !aAllocator->GetLayersIPCActor()->IPCOpen()) {
     return nullptr;
   }
 
   TextureData* data =
     BufferTextureData::CreateForYCbCrWithBufferSize(aAllocator, aSize,
                                                     aTextureFlags);
   if (!data) {
     return nullptr;
   }
 
-  return MakeAndAddRef<TextureClient>(data, aTextureFlags, aAllocator);
+  return MakeAndAddRef<TextureClient>(data, aTextureFlags,
+                                      aAllocator ? aAllocator->GetTextureForwarder() : 0);
 }
 
-TextureClient::TextureClient(TextureData* aData, TextureFlags aFlags, ClientIPCAllocator* aAllocator)
+TextureClient::TextureClient(TextureData* aData, TextureFlags aFlags, LayersIPCChannel* aAllocator)
 : AtomicRefCountedWithFinalize("TextureClient")
 , mAllocator(aAllocator)
 , mActor(nullptr)
 , mData(aData)
 , mFlags(aFlags)
 , mOpenMode(OpenMode::OPEN_NONE)
 #ifdef DEBUG
 , mExpectedDtRefs(0)
@@ -1462,17 +1453,17 @@ public:
 // it means that we can safely deallocate the shmem section without causing a race
 // condition with the other process.
 class ShmemTextureReadLock : public TextureReadLock {
 public:
   struct ShmReadLockInfo {
     int32_t readCount;
   };
 
-  explicit ShmemTextureReadLock(ClientIPCAllocator* aAllocator);
+  explicit ShmemTextureReadLock(LayersIPCChannel* aAllocator);
 
   ~ShmemTextureReadLock();
 
   virtual int32_t ReadLock() override;
 
   virtual int32_t ReadUnlock() override;
 
   virtual int32_t GetReadCount() override;
@@ -1480,44 +1471,43 @@ public:
   virtual bool IsValid() const override { return mAllocSuccess; };
 
   virtual LockType GetType() override { return TYPE_SHMEM; }
 
   virtual bool Serialize(ReadLockDescriptor& aOutput) override;
 
   mozilla::layers::ShmemSection& GetShmemSection() { return mShmemSection; }
 
-  ShmemTextureReadLock(ISurfaceAllocator* aAllocator, const mozilla::layers::ShmemSection& aShmemSection)
-    : mAllocator(aAllocator)
-    , mShmemSection(aShmemSection)
+  explicit ShmemTextureReadLock(const mozilla::layers::ShmemSection& aShmemSection)
+    : mShmemSection(aShmemSection)
     , mAllocSuccess(true)
   {
     MOZ_COUNT_CTOR(ShmemTextureReadLock);
   }
 
   ShmReadLockInfo* GetShmReadLockInfoPtr()
   {
     return reinterpret_cast<ShmReadLockInfo*>
       (mShmemSection.shmem().get<char>() + mShmemSection.offset());
   }
 
-  RefPtr<ISurfaceAllocator> mAllocator;
+  RefPtr<LayersIPCChannel> mClientAllocator;
   mozilla::layers::ShmemSection mShmemSection;
   bool mAllocSuccess;
 };
 
 // static
 already_AddRefed<TextureReadLock>
 TextureReadLock::Deserialize(const ReadLockDescriptor& aDescriptor, ISurfaceAllocator* aAllocator)
 {
   switch (aDescriptor.type()) {
     case ReadLockDescriptor::TShmemSection: {
       const ShmemSection& section = aDescriptor.get_ShmemSection();
       MOZ_RELEASE_ASSERT(section.shmem().IsReadable());
-      return MakeAndAddRef<ShmemTextureReadLock>(aAllocator, section);
+      return MakeAndAddRef<ShmemTextureReadLock>(section);
     }
     case ReadLockDescriptor::Tuintptr_t: {
       if (!aAllocator->IsSameProcess()) {
         // Trying to use a memory based lock instead of a shmem based one in
         // the cross-process case is a bad security violation.
         NS_ERROR("A client process may be trying to peek at the host's address space!");
         return nullptr;
       }
@@ -1540,17 +1530,17 @@ TextureReadLock::Deserialize(const ReadL
       // Invalid descriptor.
       MOZ_DIAGNOSTIC_ASSERT(false);
     }
   }
   return nullptr;
 }
 // static
 already_AddRefed<TextureReadLock>
-TextureReadLock::Create(ClientIPCAllocator* aAllocator)
+TextureReadLock::Create(LayersIPCChannel* aAllocator)
 {
   if (aAllocator->IsSameProcess()) {
     // If our compositor is in the same process, we can save some cycles by not
     // using shared memory.
     return MakeAndAddRef<MemoryTextureReadLock>();
   }
 
   return MakeAndAddRef<ShmemTextureReadLock>(aAllocator);
@@ -1599,36 +1589,34 @@ MemoryTextureReadLock::ReadUnlock()
 
 int32_t
 MemoryTextureReadLock::GetReadCount()
 {
   NS_ASSERT_OWNINGTHREAD(MemoryTextureReadLock);
   return mReadCount;
 }
 
-ShmemTextureReadLock::ShmemTextureReadLock(ClientIPCAllocator* aAllocator)
-  : mAllocator(aAllocator)
+ShmemTextureReadLock::ShmemTextureReadLock(LayersIPCChannel* aAllocator)
+  : mClientAllocator(aAllocator)
   , mAllocSuccess(false)
 {
   MOZ_COUNT_CTOR(ShmemTextureReadLock);
-  MOZ_ASSERT(mAllocator);
-  MOZ_ASSERT(mAllocator->AsTextureForwarder());
+  MOZ_ASSERT(mClientAllocator);
 #define MOZ_ALIGN_WORD(x) (((x) + 3) & ~3)
-  if (mAllocator->AsTextureForwarder()->GetTileLockAllocator()->AllocShmemSection(
+  if (mClientAllocator->GetTileLockAllocator()->AllocShmemSection(
       MOZ_ALIGN_WORD(sizeof(ShmReadLockInfo)), &mShmemSection)) {
     ShmReadLockInfo* info = GetShmReadLockInfoPtr();
     info->readCount = 1;
     mAllocSuccess = true;
   }
 }
 
 ShmemTextureReadLock::~ShmemTextureReadLock()
 {
-  auto fwd = mAllocator->AsTextureForwarder();
-  if (fwd) {
+  if (mClientAllocator) {
     // Release one read count that is added in constructor.
     // The count is kept for calling GetReadCount() by TextureClientPool.
     ReadUnlock();
   }
   MOZ_COUNT_DTOR(ShmemTextureReadLock);
 }
 
 bool
@@ -1652,19 +1640,18 @@ int32_t
 ShmemTextureReadLock::ReadUnlock() {
   if (!mAllocSuccess) {
     return 0;
   }
   ShmReadLockInfo* info = GetShmReadLockInfoPtr();
   int32_t readCount = PR_ATOMIC_DECREMENT(&info->readCount);
   MOZ_ASSERT(readCount >= 0);
   if (readCount <= 0) {
-    auto fwd = mAllocator->AsTextureForwarder();
-    if (fwd) {
-      fwd->GetTileLockAllocator()->DeallocShmemSection(mShmemSection);
+    if (mClientAllocator) {
+      mClientAllocator->GetTileLockAllocator()->DeallocShmemSection(mShmemSection);
     } else {
       // we are on the compositor process
       FixedSizeSmallShmemSectionAllocator::FreeShmemSection(mShmemSection);
     }
   }
   return readCount;
 }
 
@@ -1733,17 +1720,17 @@ SyncObject::CreateSyncObject(SyncHandle 
   return MakeAndAddRef<SyncObjectD3D11>(aHandle);
 #else
   MOZ_ASSERT_UNREACHABLE();
   return nullptr;
 #endif
 }
 
 already_AddRefed<TextureClient>
-TextureClient::CreateWithData(TextureData* aData, TextureFlags aFlags, ClientIPCAllocator* aAllocator)
+TextureClient::CreateWithData(TextureData* aData, TextureFlags aFlags, LayersIPCChannel* aAllocator)
 {
   if (!aData) {
     return nullptr;
   }
   return MakeAndAddRef<TextureClient>(aData, aFlags, aAllocator);
 }
 
 bool
--- a/gfx/layers/client/TextureClient.h
+++ b/gfx/layers/client/TextureClient.h
@@ -45,18 +45,19 @@ namespace gl {
 class SharedSurface_Gralloc;
 }
 
 namespace layers {
 
 class AsyncTransactionWaiter;
 class BufferTextureData;
 class CompositableForwarder;
+class KnowsCompositor;
 class GrallocTextureData;
-class ClientIPCAllocator;
+class LayersIPCChannel;
 class CompositableClient;
 struct PlanarYCbCrData;
 class Image;
 class PTextureChild;
 class TextureChild;
 class TextureData;
 struct RawTextureBuffer;
 class RawYCbCrTextureBuffer;
@@ -208,17 +209,17 @@ public:
   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(TextureReadLock)
 
   virtual int32_t ReadLock() = 0;
   virtual int32_t ReadUnlock() = 0;
   virtual int32_t GetReadCount() = 0;
   virtual bool IsValid() const = 0;
 
   static already_AddRefed<TextureReadLock>
-  Create(ClientIPCAllocator* aAllocator);
+  Create(LayersIPCChannel* aAllocator);
 
   static already_AddRefed<TextureReadLock>
   Deserialize(const ReadLockDescriptor& aDescriptor, ISurfaceAllocator* aAllocator);
 
   virtual bool Serialize(ReadLockDescriptor& aOutput) = 0;
 
   enum LockType {
     TYPE_MEMORY,
@@ -264,25 +265,26 @@ public:
   virtual void Unlock() = 0;
 
   virtual already_AddRefed<gfx::DrawTarget> BorrowDrawTarget() { return nullptr; }
 
   virtual bool BorrowMappedData(MappedTextureData&) { return false; }
 
   virtual bool BorrowMappedYCbCrData(MappedYCbCrTextureData&) { return false; }
 
-  virtual void Deallocate(ClientIPCAllocator* aAllocator) = 0;
+  virtual void Deallocate(LayersIPCChannel* aAllocator) = 0;
 
   /// Depending on the texture's flags either Deallocate or Forget is called.
-  virtual void Forget(ClientIPCAllocator* aAllocator) {}
+  virtual void Forget(LayersIPCChannel* aAllocator) {}
 
   virtual bool Serialize(SurfaceDescriptor& aDescriptor) = 0;
 
   virtual TextureData*
-  CreateSimilar(ClientIPCAllocator* aAllocator,
+  CreateSimilar(LayersIPCChannel* aAllocator,
+                LayersBackend aLayersBackend,
                 TextureFlags aFlags = TextureFlags::DEFAULT,
                 TextureAllocationFlags aAllocFlags = ALLOC_DEFAULT) const { return nullptr; }
 
   virtual bool UpdateFromSurface(gfx::SourceSurface* aSurface) { return false; };
 
   virtual bool ReadBack(TextureReadbackSink* aReadbackSink) { return false; }
 
   /// Ideally this should not be exposed and users of TextureClient would use Lock/Unlock
@@ -326,89 +328,69 @@ public:
  * responsibility of the compositable (which would use two Texture pairs).
  * In order to send several different buffers to the compositor side, use
  * several TextureClients.
  */
 class TextureClient
   : public AtomicRefCountedWithFinalize<TextureClient>
 {
 public:
-  explicit TextureClient(TextureData* aData, TextureFlags aFlags, ClientIPCAllocator* aAllocator);
+  explicit TextureClient(TextureData* aData, TextureFlags aFlags, LayersIPCChannel* aAllocator);
 
   virtual ~TextureClient();
 
   static already_AddRefed<TextureClient>
-  CreateWithData(TextureData* aData, TextureFlags aFlags, ClientIPCAllocator* aAllocator);
+  CreateWithData(TextureData* aData, TextureFlags aFlags, LayersIPCChannel* aAllocator);
 
   // Creates and allocates a TextureClient usable with Moz2D.
   static already_AddRefed<TextureClient>
-  CreateForDrawing(TextureForwarder* aAllocator,
-                   gfx::SurfaceFormat aFormat,
-                   gfx::IntSize aSize,
-                   LayersBackend aLayersBackend,
-                   BackendSelector aSelector,
-                   TextureFlags aTextureFlags,
-                   TextureAllocationFlags aAllocFlags = ALLOC_DEFAULT);
-
-  // TODO: remove this one and use the one above instead.
-  static already_AddRefed<TextureClient>
-  CreateForDrawing(CompositableForwarder* aAllocator,
+  CreateForDrawing(KnowsCompositor* aAllocator,
                    gfx::SurfaceFormat aFormat,
                    gfx::IntSize aSize,
                    BackendSelector aSelector,
                    TextureFlags aTextureFlags,
                    TextureAllocationFlags flags = ALLOC_DEFAULT);
 
   static already_AddRefed<TextureClient>
-  CreateFromSurface(TextureForwarder* aAllocator,
+  CreateFromSurface(KnowsCompositor* aAllocator,
                     gfx::SourceSurface* aSurface,
-                    LayersBackend aLayersBackend,
                     BackendSelector aSelector,
                     TextureFlags aTextureFlags,
                     TextureAllocationFlags aAllocFlags);
 
   // Creates and allocates a TextureClient supporting the YCbCr format.
   static already_AddRefed<TextureClient>
-  CreateForYCbCr(ClientIPCAllocator* aAllocator,
+  CreateForYCbCr(KnowsCompositor* aAllocator,
                  gfx::IntSize aYSize,
                  gfx::IntSize aCbCrSize,
                  StereoMode aStereoMode,
                  TextureFlags aTextureFlags);
 
   // Creates and allocates a TextureClient (can be accessed through raw
   // pointers).
   static already_AddRefed<TextureClient>
-  CreateForRawBufferAccess(ClientIPCAllocator* aAllocator,
-                           gfx::SurfaceFormat aFormat,
-                           gfx::IntSize aSize,
-                           gfx::BackendType aMoz2dBackend,
-                           LayersBackend aLayersBackend,
-                           TextureFlags aTextureFlags,
-                           TextureAllocationFlags flags = ALLOC_DEFAULT);
-
-  // TODO: remove this one and use the one above instead.
-  static already_AddRefed<TextureClient>
-  CreateForRawBufferAccess(ClientIPCAllocator* aAllocator,
+  CreateForRawBufferAccess(KnowsCompositor* aAllocator,
                            gfx::SurfaceFormat aFormat,
                            gfx::IntSize aSize,
                            gfx::BackendType aMoz2dBackend,
                            TextureFlags aTextureFlags,
                            TextureAllocationFlags flags = ALLOC_DEFAULT);
 
   // Creates and allocates a TextureClient (can beaccessed through raw
   // pointers) with a certain buffer size. It's unfortunate that we need this.
   // providing format and sizes could let us do more optimization.
   static already_AddRefed<TextureClient>
-  CreateForYCbCrWithBufferSize(ClientIPCAllocator* aAllocator,
+  CreateForYCbCrWithBufferSize(KnowsCompositor* aAllocator,
                                size_t aSize,
                                TextureFlags aTextureFlags);
 
   // Creates and allocates a TextureClient of the same type.
   already_AddRefed<TextureClient>
-  CreateSimilar(TextureFlags aFlags = TextureFlags::DEFAULT,
+  CreateSimilar(LayersBackend aLayersBackend = LayersBackend::LAYERS_NONE,
+                TextureFlags aFlags = TextureFlags::DEFAULT,
                 TextureAllocationFlags aAllocFlags = ALLOC_DEFAULT) const;
 
   /**
    * Locks the shared data, allowing the caller to get access to it.
    *
    * Please always lock/unlock when accessing the shared data.
    * If Lock() returns false, you should not attempt to access the shared data.
    */
@@ -575,17 +557,17 @@ public:
 
   /**
    * Create and init the TextureChild/Parent IPDL actor pair
    * with a TextureForwarder.
    *
    * Should be called only once per TextureClient.
    * The TextureClient must not be locked when calling this method.
    */
-  bool InitIPDLActor(TextureForwarder* aForwarder);
+  bool InitIPDLActor(KnowsCompositor* aForwarder);
 
   /**
    * Return a pointer to the IPDLActor.
    *
    * This is to be used with IPDL messages only. Do not store the returned
    * pointer.
    */
   PTextureChild* GetIPDLActor();
@@ -645,17 +627,17 @@ public:
    * texture unlock.
    */
   virtual void SetReadbackSink(TextureReadbackSink* aReadbackSink) {
     mReadbackSink = aReadbackSink;
   }
 
   void SyncWithObject(SyncObject* aFence) { mData->SyncWithObject(aFence); }
 
-  ClientIPCAllocator* GetAllocator() { return mAllocator; }
+  LayersIPCChannel* GetAllocator() { return mAllocator; }
 
   ITextureClientRecycleAllocator* GetRecycleAllocator() { return mRecycleAllocator; }
   void SetRecycleAllocator(ITextureClientRecycleAllocator* aAllocator);
 
   /// If you add new code that uses this method, you are probably doing something wrong.
   TextureData* GetInternalData() { return mData; }
   const TextureData* GetInternalData() const { return mData; }
 
@@ -702,16 +684,40 @@ public:
   TextureReadLock* GetReadLock() { return mReadLock; }
 
   bool IsReadLocked() const;
 
   void SerializeReadLock(ReadLockDescriptor& aDescriptor);
 
 private:
   static void TextureClientRecycleCallback(TextureClient* aClient, void* aClosure);
+ 
+  // Internal helpers for creating texture clients using the actual forwarder instead
+  // of KnowsCompositor. TextureClientPool uses these to let it cache texture clients
+  // per-process instead of per ShadowLayerForwarder, but everyone else should
+  // use the public functions instead.
+  friend class TextureClientPool;
+  static already_AddRefed<TextureClient>
+  CreateForDrawing(TextureForwarder* aAllocator,
+                   gfx::SurfaceFormat aFormat,
+                   gfx::IntSize aSize,
+                   LayersBackend aLayersBackend,
+                   int32_t aMaxTextureSize,
+                   BackendSelector aSelector,
+                   TextureFlags aTextureFlags,
+                   TextureAllocationFlags aAllocFlags = ALLOC_DEFAULT);
+  
+  static already_AddRefed<TextureClient>
+  CreateForRawBufferAccess(LayersIPCChannel* aAllocator,
+                           gfx::SurfaceFormat aFormat,
+                           gfx::IntSize aSize,
+                           gfx::BackendType aMoz2dBackend,
+                           LayersBackend aLayersBackend,
+                           TextureFlags aTextureFlags,
+                           TextureAllocationFlags flags = ALLOC_DEFAULT);
 
   /**
    * Called once, during the destruction of the Texture, on the thread in which
    * texture's reference count reaches 0 (could be any thread).
    *
    * Here goes the shut-down code that uses virtual methods.
    * Must only be called by Release().
    */
@@ -730,17 +736,17 @@ protected:
    */
   bool ToSurfaceDescriptor(SurfaceDescriptor& aDescriptor);
 
   void LockActor() const;
   void UnlockActor() const;
 
   TextureData::Info mInfo;
 
-  RefPtr<ClientIPCAllocator> mAllocator;
+  RefPtr<LayersIPCChannel> mAllocator;
   RefPtr<TextureChild> mActor;
   RefPtr<ITextureClientRecycleAllocator> mRecycleAllocator;
   RefPtr<TextureReadLock> mReadLock;
 
   TextureData* mData;
   RefPtr<gfx::DrawTarget> mBorrowedDrawTarget;
 
   TextureFlags mFlags;
--- a/gfx/layers/client/TextureClientPool.cpp
+++ b/gfx/layers/client/TextureClientPool.cpp
@@ -33,25 +33,27 @@ ShrinkCallback(nsITimer *aTimer, void *a
 // at an inopportune time (e.g. mid-animation).
 static void
 ClearCallback(nsITimer *aTimer, void *aClosure)
 {
   static_cast<TextureClientPool*>(aClosure)->Clear();
 }
 
 TextureClientPool::TextureClientPool(LayersBackend aLayersBackend,
+                                     int32_t aMaxTextureSize,
                                      gfx::SurfaceFormat aFormat,
                                      gfx::IntSize aSize,
                                      TextureFlags aFlags,
                                      uint32_t aShrinkTimeoutMsec,
                                      uint32_t aClearTimeoutMsec,
                                      uint32_t aInitialPoolSize,
                                      uint32_t aPoolUnusedSize,
                                      TextureForwarder* aAllocator)
   : mBackend(aLayersBackend)
+  , mMaxTextureSize(aMaxTextureSize)
   , mFormat(aFormat)
   , mSize(aSize)
   , mFlags(aFlags)
   , mShrinkTimeoutMsec(aShrinkTimeoutMsec)
   , mClearTimeoutMsec(aClearTimeoutMsec)
   , mInitialPoolSize(aInitialPoolSize)
   , mPoolUnusedSize(aPoolUnusedSize)
   , mOutstandingClients(0)
@@ -155,16 +157,17 @@ TextureClientPool::AllocateTextureClient
                                               gfx::BackendType::NONE,
                                               mBackend,
                                               mFlags, ALLOC_DEFAULT);
   } else {
     newClient =
       TextureClient::CreateForDrawing(mSurfaceAllocator,
                                       mFormat, mSize,
                                       mBackend,
+                                      mMaxTextureSize,
                                       BackendSelector::Content,
                                       mFlags);
   }
 
   if (newClient) {
     mTextureClients.push(newClient);
   }
 }
--- a/gfx/layers/client/TextureClientPool.h
+++ b/gfx/layers/client/TextureClientPool.h
@@ -40,16 +40,17 @@ public:
 };
 
 class TextureClientPool final : public TextureClientAllocator
 {
   ~TextureClientPool();
 
 public:
   TextureClientPool(LayersBackend aBackend,
+                    int32_t aMaxTextureSize,
                     gfx::SurfaceFormat aFormat,
                     gfx::IntSize aSize,
                     TextureFlags aFlags,
                     uint32_t aShrinkTimeoutMsec,
                     uint32_t aClearTimeoutMsec,
                     uint32_t aInitialPoolSize,
                     uint32_t aPoolUnusedSize,
                     TextureForwarder* aAllocator);
@@ -97,16 +98,17 @@ public:
 
   /**
    * Calling this will cause the pool to attempt to relinquish any unused
    * clients.
    */
   void Clear();
 
   LayersBackend GetBackend() const { return mBackend; }
+  int32_t GetMaxTextureSize() const { return mMaxTextureSize; }
   gfx::SurfaceFormat GetFormat() { return mFormat; }
   TextureFlags GetFlags() const { return mFlags; }
 
   /**
    * Clear the pool and put it in a state where it won't recycle any new texture.
    */
   void Destroy();
 
@@ -117,16 +119,19 @@ private:
   void AllocateTextureClient();
 
   /// Reset and/or initialise timers for shrinking/clearing the pool.
   void ResetTimers();
 
   /// Backend passed to the TextureClient for buffer creation.
   LayersBackend mBackend;
 
+  // Max texture size passed to the TextureClient for buffer creation.
+  int32_t mMaxTextureSize;
+
   /// Format is passed to the TextureClient for buffer creation.
   gfx::SurfaceFormat mFormat;
 
   /// The width and height of the tiles to be used.
   gfx::IntSize mSize;
 
   /// Flags passed to the TextureClient for buffer creation.
   const TextureFlags mFlags;
--- a/gfx/layers/client/TextureClientRecycleAllocator.cpp
+++ b/gfx/layers/client/TextureClientRecycleAllocator.cpp
@@ -67,17 +67,17 @@ public:
   {
     if (aTextureClient->GetFormat() != mFormat ||
         aTextureClient->GetSize() != mSize) {
       return false;
     }
     return true;
   }
 
-  already_AddRefed<TextureClient> Allocate(TextureForwarder* aAllocator) override
+  already_AddRefed<TextureClient> Allocate(KnowsCompositor* aAllocator) override
   {
     return mAllocator->Allocate(mFormat,
                                 mSize,
                                 mSelector,
                                 mTextureFlags,
                                 mAllocationFlags);
   }
 
@@ -109,25 +109,25 @@ YCbCrTextureClientAllocationHelper::IsCo
       bufferData->GetStereoMode().isNothing() ||
       bufferData->GetStereoMode().ref() != mData.mStereoMode) {
     return false;
   }
   return true;
 }
 
 already_AddRefed<TextureClient>
-YCbCrTextureClientAllocationHelper::Allocate(TextureForwarder* aAllocator)
+YCbCrTextureClientAllocationHelper::Allocate(KnowsCompositor* aAllocator)
 {
   return TextureClient::CreateForYCbCr(aAllocator,
                                        mData.mYSize, mData.mCbCrSize,
                                        mData.mStereoMode,
                                        mTextureFlags);
 }
 
-TextureClientRecycleAllocator::TextureClientRecycleAllocator(TextureForwarder* aAllocator)
+TextureClientRecycleAllocator::TextureClientRecycleAllocator(KnowsCompositor* aAllocator)
   : mSurfaceAllocator(aAllocator)
   , mMaxPooledSize(kMaxPooledSized)
   , mLock("TextureClientRecycleAllocatorImp.mLock")
   , mIsDestroyed(false)
 {
 }
 
 TextureClientRecycleAllocator::~TextureClientRecycleAllocator()
@@ -184,17 +184,17 @@ TextureClientRecycleAllocator::CreateOrR
       textureHolder = mPooledClients.top();
       mPooledClients.pop();
       // If a pooled TextureClient is not compatible, release it.
       if (!aHelper.IsCompatible(textureHolder->GetTextureClient())) {
         // Release TextureClient.
         RefPtr<Runnable> task = new TextureClientReleaseTask(textureHolder->GetTextureClient());
         textureHolder->ClearTextureClient();
         textureHolder = nullptr;
-        mSurfaceAllocator->GetMessageLoop()->PostTask(task.forget());
+        mSurfaceAllocator->GetTextureForwarder()->GetMessageLoop()->PostTask(task.forget());
       } else {
         textureHolder->GetTextureClient()->RecycleTexture(aHelper.mTextureFlags);
       }
     }
   }
 
   if (!textureHolder) {
     // Allocate new TextureClient
@@ -222,17 +222,16 @@ TextureClientRecycleAllocator::CreateOrR
 already_AddRefed<TextureClient>
 TextureClientRecycleAllocator::Allocate(gfx::SurfaceFormat aFormat,
                                         gfx::IntSize aSize,
                                         BackendSelector aSelector,
                                         TextureFlags aTextureFlags,
                                         TextureAllocationFlags aAllocFlags)
 {
   return TextureClient::CreateForDrawing(mSurfaceAllocator, aFormat, aSize,
-                                         mSurfaceAllocator->GetCompositorBackendType(),
                                          aSelector, aTextureFlags, aAllocFlags);
 }
 
 void
 TextureClientRecycleAllocator::ShrinkToMinimumSize()
 {
   MutexAutoLock lock(mLock);
   while (!mPooledClients.empty()) {
--- a/gfx/layers/client/TextureClientRecycleAllocator.h
+++ b/gfx/layers/client/TextureClientRecycleAllocator.h
@@ -43,17 +43,17 @@ public:
                                  TextureAllocationFlags aAllocationFlags)
     : mFormat(aFormat)
     , mSize(aSize)
     , mSelector(aSelector)
     , mTextureFlags(aTextureFlags | TextureFlags::RECYCLE) // Set recycle flag
     , mAllocationFlags(aAllocationFlags)
   {}
 
-  virtual already_AddRefed<TextureClient> Allocate(TextureForwarder* aAllocator) = 0;
+  virtual already_AddRefed<TextureClient> Allocate(KnowsCompositor* aAllocator) = 0;
   virtual bool IsCompatible(TextureClient* aTextureClient) = 0;
 
   const gfx::SurfaceFormat mFormat;
   const gfx::IntSize mSize;
   const BackendSelector mSelector;
   const TextureFlags mTextureFlags;
   const TextureAllocationFlags mAllocationFlags;
 };
@@ -61,17 +61,17 @@ public:
 class YCbCrTextureClientAllocationHelper : public ITextureClientAllocationHelper
 {
 public:
   YCbCrTextureClientAllocationHelper(const PlanarYCbCrData& aData,
                                      TextureFlags aTextureFlags);
 
   bool IsCompatible(TextureClient* aTextureClient) override;
 
-  already_AddRefed<TextureClient> Allocate(TextureForwarder* aAllocator) override;
+  already_AddRefed<TextureClient> Allocate(KnowsCompositor* aAllocator) override;
 
 protected:
   const PlanarYCbCrData& mData;
 };
 
 
 /**
  * TextureClientRecycleAllocator provides TextureClients allocation and
@@ -83,17 +83,17 @@ protected:
  * clients.
  */
 class TextureClientRecycleAllocator : public ITextureClientRecycleAllocator
 {
 protected:
   virtual ~TextureClientRecycleAllocator();
 
 public:
-  explicit TextureClientRecycleAllocator(TextureForwarder* aAllocator);
+  explicit TextureClientRecycleAllocator(KnowsCompositor* aAllocator);
 
   void SetMaxPoolSize(uint32_t aMax);
 
   // Creates and allocates a TextureClient.
   already_AddRefed<TextureClient>
   CreateOrRecycle(gfx::SurfaceFormat aFormat,
                   gfx::IntSize aSize,
                   BackendSelector aSelector,
@@ -110,17 +110,17 @@ public:
 protected:
   virtual already_AddRefed<TextureClient>
   Allocate(gfx::SurfaceFormat aFormat,
            gfx::IntSize aSize,
            BackendSelector aSelector,
            TextureFlags aTextureFlags,
            TextureAllocationFlags aAllocFlags);
 
-  RefPtr<TextureForwarder> mSurfaceAllocator;
+  RefPtr<KnowsCompositor> mSurfaceAllocator;
 
   friend class DefaultTextureClientAllocationHelper;
   void RecycleTextureClient(TextureClient* aClient) override;
 
   static const uint32_t kMaxPooledSized = 2;
   uint32_t mMaxPooledSize;
 
   std::map<TextureClient*, RefPtr<TextureClientHolder> > mInUseClients;
--- a/gfx/layers/client/TextureClientSharedSurface.cpp
+++ b/gfx/layers/client/TextureClientSharedSurface.cpp
@@ -27,17 +27,17 @@ namespace layers {
 SharedSurfaceTextureData::SharedSurfaceTextureData(UniquePtr<gl::SharedSurface> surf)
   : mSurf(Move(surf))
 {}
 
 SharedSurfaceTextureData::~SharedSurfaceTextureData()
 {}
 
 void
-SharedSurfaceTextureData::Deallocate(ClientIPCAllocator*)
+SharedSurfaceTextureData::Deallocate(LayersIPCChannel*)
 {}
 
 void
 SharedSurfaceTextureData::FillInfo(TextureData::Info& aInfo) const
 {
   aInfo.size = mSurf->mSize;
   aInfo.format = gfx::SurfaceFormat::UNKNOWN;
   aInfo.hasIntermediateBuffer = false;
@@ -50,25 +50,25 @@ bool
 SharedSurfaceTextureData::Serialize(SurfaceDescriptor& aOutDescriptor)
 {
   return mSurf->ToSurfaceDescriptor(&aOutDescriptor);
 }
 
 
 SharedSurfaceTextureClient::SharedSurfaceTextureClient(SharedSurfaceTextureData* aData,
                                                        TextureFlags aFlags,
-                                                       ClientIPCAllocator* aAllocator)
+                                                       LayersIPCChannel* aAllocator)
 : TextureClient(aData, aFlags, aAllocator)
 {
   mWorkaroundAnnoyingSharedSurfaceLifetimeIssues = true;
 }
 
 already_AddRefed<SharedSurfaceTextureClient>
 SharedSurfaceTextureClient::Create(UniquePtr<gl::SharedSurface> surf, gl::SurfaceFactory* factory,
-                                   ClientIPCAllocator* aAllocator, TextureFlags aFlags)
+                                   LayersIPCChannel* aAllocator, TextureFlags aFlags)
 {
   if (!surf) {
     return nullptr;
   }
   TextureFlags flags = aFlags | TextureFlags::RECYCLE | surf->GetTextureFlags();
   SharedSurfaceTextureData* data = new SharedSurfaceTextureData(Move(surf));
   return MakeAndAddRef<SharedSurfaceTextureClient>(data, flags, aAllocator);
 }
--- a/gfx/layers/client/TextureClientSharedSurface.h
+++ b/gfx/layers/client/TextureClientSharedSurface.h
@@ -43,33 +43,33 @@ public:
   virtual bool Lock(OpenMode, FenceHandle*) override { return false; }
 
   virtual void Unlock() override {}
 
   virtual void FillInfo(TextureData::Info& aInfo) const override;
 
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
-  virtual void Deallocate(ClientIPCAllocator*) override;
+  virtual void Deallocate(LayersIPCChannel*) override;
 
   gl::SharedSurface* Surf() const { return mSurf.get(); }
 };
 
 class SharedSurfaceTextureClient : public TextureClient
 {
 public:
   SharedSurfaceTextureClient(SharedSurfaceTextureData* aData,
                              TextureFlags aFlags,
-                             ClientIPCAllocator* aAllocator);
+                             LayersIPCChannel* aAllocator);
 
   ~SharedSurfaceTextureClient();
 
   static already_AddRefed<SharedSurfaceTextureClient>
   Create(UniquePtr<gl::SharedSurface> surf, gl::SurfaceFactory* factory,
-         ClientIPCAllocator* aAllocator, TextureFlags aFlags);
+         LayersIPCChannel* aAllocator, TextureFlags aFlags);
 
   virtual void SetReleaseFenceHandle(const FenceHandle& aReleaseFenceHandle) override;
 
   virtual FenceHandle GetAndResetReleaseFenceHandle() override;
 
   virtual void SetAcquireFenceHandle(const FenceHandle& aAcquireFenceHandle) override;
 
   virtual const FenceHandle& GetAcquireFenceHandle() const override;
--- a/gfx/layers/client/TiledContentClient.cpp
+++ b/gfx/layers/client/TiledContentClient.cpp
@@ -1052,17 +1052,17 @@ ClientMultiTiledLayerBuffer::ValidateTil
   }
 #endif
 
   SurfaceMode mode;
   gfxContentType content = GetContentType(&mode);
 
   if (!aTile.mAllocator) {
     aTile.SetTextureAllocator(mManager->GetCompositorBridgeChild()->GetTexturePool(
-      mManager->GetCompositorBackendType(),
+      mManager->AsShadowForwarder(),
       gfxPlatform::GetPlatform()->Optimal2DFormatForContent(content),
       TextureFlags::DISALLOW_BIGIMAGE | TextureFlags::IMMEDIATE_UPLOAD));
     MOZ_ASSERT(aTile.mAllocator);
   }
 
   nsIntRegion offsetScaledDirtyRegion = aDirtyRegion.MovedBy(-aTileOrigin);
   offsetScaledDirtyRegion.ScaleRoundOut(mResolution, mResolution);
 
--- a/gfx/layers/d3d11/TextureD3D11.cpp
+++ b/gfx/layers/d3d11/TextureD3D11.cpp
@@ -452,52 +452,52 @@ D3D11TextureData::Create(SourceSurface* 
     return nullptr;
   }
 
   return D3D11TextureData::Create(aSurface->GetSize(), aSurface->GetFormat(),
                                   aSurface, aFlags, aDevice);
 }
 
 void
-D3D11TextureData::Deallocate(ClientIPCAllocator* aAllocator)
+D3D11TextureData::Deallocate(LayersIPCChannel* aAllocator)
 {
   mDrawTarget = nullptr;
   mTexture = nullptr;
 }
 
 already_AddRefed<TextureClient>
 CreateD3D11TextureClientWithDevice(IntSize aSize, SurfaceFormat aFormat,
                                    TextureFlags aTextureFlags, TextureAllocationFlags aAllocFlags,
                                    ID3D11Device* aDevice,
-                                   ClientIPCAllocator* aAllocator)
+                                   LayersIPCChannel* aAllocator)
 {
   TextureData* data = D3D11TextureData::Create(aSize, aFormat, aAllocFlags, aDevice);
   if (!data) {
     return nullptr;
   }
   return MakeAndAddRef<TextureClient>(data, aTextureFlags, aAllocator);
 }
 
 TextureData*
-D3D11TextureData::CreateSimilar(ClientIPCAllocator* aAllocator,
+D3D11TextureData::CreateSimilar(LayersIPCChannel* aAllocator,
+                                LayersBackend aLayersBackend,
                                 TextureFlags aFlags,
                                 TextureAllocationFlags aAllocFlags) const
 {
   return D3D11TextureData::Create(mSize, mFormat, aAllocFlags);
 }
 
 void
 D3D11TextureData::GetDXGIResource(IDXGIResource** aOutResource)
 {
   mTexture->QueryInterface(aOutResource);
 }
 
 DXGIYCbCrTextureData*
-DXGIYCbCrTextureData::Create(ClientIPCAllocator* aAllocator,
-                             TextureFlags aFlags,
+DXGIYCbCrTextureData::Create(TextureFlags aFlags,
                              IUnknown* aTextureY,
                              IUnknown* aTextureCb,
                              IUnknown* aTextureCr,
                              HANDLE aHandleY,
                              HANDLE aHandleCb,
                              HANDLE aHandleCr,
                              const gfx::IntSize& aSize,
                              const gfx::IntSize& aSizeY,
@@ -518,18 +518,17 @@ DXGIYCbCrTextureData::Create(ClientIPCAl
   texture->mSize = aSize;
   texture->mSizeY = aSizeY;
   texture->mSizeCbCr = aSizeCbCr;
 
   return texture;
 }
 
 DXGIYCbCrTextureData*
-DXGIYCbCrTextureData::Create(ClientIPCAllocator* aAllocator,
-                             TextureFlags aFlags,
+DXGIYCbCrTextureData::Create(TextureFlags aFlags,
                              ID3D11Texture2D* aTextureY,
                              ID3D11Texture2D* aTextureCb,
                              ID3D11Texture2D* aTextureCr,
                              const gfx::IntSize& aSize,
                              const gfx::IntSize& aSizeY,
                              const gfx::IntSize& aSizeCbCr)
 {
   if (!aTextureY || !aTextureCb || !aTextureCr) {
@@ -563,17 +562,17 @@ DXGIYCbCrTextureData::Create(ClientIPCAl
 
   aTextureCr->QueryInterface((IDXGIResource**)getter_AddRefs(resource));
   HANDLE handleCr;
   hr = resource->GetSharedHandle(&handleCr);
   if (FAILED(hr)) {
     return nullptr;
   }
 
-  return DXGIYCbCrTextureData::Create(aAllocator, aFlags,
+  return DXGIYCbCrTextureData::Create(aFlags,
                                       aTextureY, aTextureCb, aTextureCr,
                                       handleY, handleCb, handleCr,
                                       aSize, aSizeY, aSizeCbCr);
 }
 
 void
 DXGIYCbCrTextureData::FillInfo(TextureData::Info& aInfo) const
 {
@@ -590,17 +589,17 @@ DXGIYCbCrTextureData::Serialize(SurfaceD
   aOutDescriptor = SurfaceDescriptorDXGIYCbCr(
     (WindowsHandle)mHandles[0], (WindowsHandle)mHandles[1], (WindowsHandle)mHandles[2],
     mSize, mSizeY, mSizeCbCr
   );
   return true;
 }
 
 void
-DXGIYCbCrTextureData::Deallocate(ClientIPCAllocator*)
+DXGIYCbCrTextureData::Deallocate(LayersIPCChannel*)
 {
   mHoldRefs[0] = nullptr;
   mHoldRefs[1] = nullptr;
   mHoldRefs[2] = nullptr;
 }
 
 already_AddRefed<TextureHost>
 CreateTextureHostD3D11(const SurfaceDescriptor& aDesc,
--- a/gfx/layers/d3d11/TextureD3D11.h
+++ b/gfx/layers/d3d11/TextureD3D11.h
@@ -67,26 +67,27 @@ public:
 
   virtual bool Lock(OpenMode aMode, FenceHandle*) override;
 
   virtual void Unlock() override;
 
   virtual already_AddRefed<gfx::DrawTarget> BorrowDrawTarget() override;
 
   virtual TextureData*
-  CreateSimilar(ClientIPCAllocator* aAllocator,
+  CreateSimilar(LayersIPCChannel* aAllocator,
+                LayersBackend aLayersBackend,
                 TextureFlags aFlags,
                 TextureAllocationFlags aAllocFlags) const override;
 
   // TODO - merge this with the FenceHandle API!
   virtual void SyncWithObject(SyncObject* aSync) override;
 
   ID3D11Texture2D* GetD3D11Texture() { return mTexture; }
 
-  virtual void Deallocate(ClientIPCAllocator* aAllocator) override;
+  virtual void Deallocate(LayersIPCChannel* aAllocator) override;
 
   D3D11TextureData* AsD3D11TextureData() override {
     return this;
   }
 
   ~D3D11TextureData();
 protected:
   D3D11TextureData(ID3D11Texture2D* aTexture,
@@ -104,37 +105,35 @@ protected:
 
   RefPtr<ID3D11Texture2D> mTexture;
 };
 
 already_AddRefed<TextureClient>
 CreateD3D11extureClientWithDevice(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                                   TextureFlags aTextureFlags, TextureAllocationFlags aAllocFlags,
                                   ID3D11Device* aDevice,
-                                  ClientIPCAllocator* aAllocator);
+                                  LayersIPCChannel* aAllocator);
 
 class DXGIYCbCrTextureData : public TextureData
 {
 public:
   static DXGIYCbCrTextureData*
-  Create(ClientIPCAllocator* aAllocator,
-         TextureFlags aFlags,
+  Create(TextureFlags aFlags,
          IUnknown* aTextureY,
          IUnknown* aTextureCb,
          IUnknown* aTextureCr,
          HANDLE aHandleY,
          HANDLE aHandleCb,
          HANDLE aHandleCr,
          const gfx::IntSize& aSize,
          const gfx::IntSize& aSizeY,
          const gfx::IntSize& aSizeCbCr);
 
   static DXGIYCbCrTextureData*
-  Create(ClientIPCAllocator* aAllocator,
-         TextureFlags aFlags,
+  Create(TextureFlags aFlags,
          ID3D11Texture2D* aTextureCb,
          ID3D11Texture2D* aTextureY,
          ID3D11Texture2D* aTextureCr,
          const gfx::IntSize& aSize,
          const gfx::IntSize& aSizeY,
          const gfx::IntSize& aSizeCbCr);
 
   virtual bool Lock(OpenMode, FenceHandle*) override { return true; }
@@ -142,23 +141,17 @@ public:
   virtual void Unlock() override {}
 
   virtual void FillInfo(TextureData::Info& aInfo) const override;
 
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
   virtual already_AddRefed<gfx::DrawTarget> BorrowDrawTarget() override { return nullptr; }
 
-  // This TextureData should not be used in a context where we use CreateSimilar
-  // (ex. component alpha) because the underlying texture is always created by
-  // an external producer.
-  virtual DXGIYCbCrTextureData*
-  CreateSimilar(ClientIPCAllocator*, TextureFlags, TextureAllocationFlags) const override { return nullptr; }
-
-  virtual void Deallocate(ClientIPCAllocator* aAllocator) override;
+  virtual void Deallocate(LayersIPCChannel* aAllocator) override;
 
   virtual bool UpdateFromSurface(gfx::SourceSurface*) override { return false; }
 
   virtual TextureFlags GetTextureFlags() const override
   {
     return TextureFlags::DEALLOCATE_MAIN_THREAD;
   }
 
@@ -268,17 +261,17 @@ protected:
   bool mIterating;
 
 };
 
 already_AddRefed<TextureClient>
 CreateD3D11TextureClientWithDevice(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                                    TextureFlags aTextureFlags, TextureAllocationFlags aAllocFlags,
                                    ID3D11Device* aDevice,
-                                   ClientIPCAllocator* aAllocator);
+                                   LayersIPCChannel* aAllocator);
 
 
 /**
  * A TextureHost for shared D3D11 textures.
  */
 class DXGITextureHostD3D11 : public TextureHost
 {
 public:
--- a/gfx/layers/d3d9/TextureD3D9.cpp
+++ b/gfx/layers/d3d9/TextureD3D9.cpp
@@ -588,17 +588,17 @@ D3D9TextureData::Create(gfx::IntSize aSi
 
   data->mNeedsClear = aAllocFlags & ALLOC_CLEAR_BUFFER;
   data->mNeedsClearWhite = aAllocFlags & ALLOC_CLEAR_BUFFER_WHITE;
 
   return data;
 }
 
 TextureData*
-D3D9TextureData::CreateSimilar(ClientIPCAllocator*, TextureFlags aFlags, TextureAllocationFlags aAllocFlags) const
+D3D9TextureData::CreateSimilar(LayersIPCChannel*, LayersBackend, TextureFlags aFlags, TextureAllocationFlags aAllocFlags) const
 {
   return D3D9TextureData::Create(mSize, mFormat, aAllocFlags);
 }
 
 void
 D3D9TextureData::FillInfo(TextureData::Info& aInfo) const
 {
   aInfo.size = mSize;
--- a/gfx/layers/d3d9/TextureD3D9.h
+++ b/gfx/layers/d3d9/TextureD3D9.h
@@ -184,24 +184,25 @@ public:
 
   virtual void FillInfo(TextureData::Info& aInfo) const override;
 
   virtual already_AddRefed<gfx::DrawTarget> BorrowDrawTarget() override;
 
   virtual bool UpdateFromSurface(gfx::SourceSurface* aSurface) override;
 
   virtual TextureData*
-  CreateSimilar(ClientIPCAllocator* aAllocator,
+  CreateSimilar(LayersIPCChannel* aAllocator,
+                LayersBackend aLayersBackend,
                 TextureFlags aFlags,
                 TextureAllocationFlags aAllocFlags) const override;
 
   static D3D9TextureData*
   Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat, TextureAllocationFlags aFlags);
 
-  virtual void Deallocate(ClientIPCAllocator* aAllocator) override {}
+  virtual void Deallocate(LayersIPCChannel* aAllocator) override {}
 
 protected:
   D3D9TextureData(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                   IDirect3DTexture9* aTexture);
 
   RefPtr<IDirect3DTexture9> mTexture;
   RefPtr<IDirect3DSurface9> mD3D9Surface;
   gfx::IntSize mSize;
@@ -227,17 +228,17 @@ public:
   virtual void FillInfo(TextureData::Info& aInfo) const override;
 
   virtual bool Lock(OpenMode, FenceHandle*) override { return true; }
 
   virtual void Unlock() override {}
 
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
-  virtual void Deallocate(ClientIPCAllocator* aAllocator) override {}
+  virtual void Deallocate(LayersIPCChannel* aAllocator) override {}
 
   IDirect3DDevice9* GetD3D9Device() { return mDevice; }
   IDirect3DTexture9* GetD3D9Texture() { return mTexture; }
   HANDLE GetShareHandle() const { return mHandle; }
   already_AddRefed<IDirect3DSurface9> GetD3D9Surface() const;
 
   const D3DSURFACE_DESC& GetDesc() const
   {
--- a/gfx/layers/ipc/CompositableForwarder.h
+++ b/gfx/layers/ipc/CompositableForwarder.h
@@ -14,80 +14,47 @@
 #include "mozilla/layers/CompositableClient.h"  // for CompositableClient
 #include "mozilla/layers/CompositorTypes.h"
 #include "mozilla/layers/ISurfaceAllocator.h"  // for ISurfaceAllocator
 #include "mozilla/layers/LayersTypes.h"  // for LayersBackend
 #include "mozilla/layers/TextureClient.h"  // for TextureClient
 #include "mozilla/layers/TextureForwarder.h"  // for TextureForwarder
 #include "nsRegion.h"                   // for nsIntRegion
 #include "mozilla/gfx/Rect.h"
-#include "nsExpirationTracker.h"
 #include "nsHashKeys.h"
 #include "nsTHashtable.h"
 
 namespace mozilla {
 namespace layers {
 
 class CompositableClient;
 class AsyncTransactionTracker;
 class ImageContainer;
 class SurfaceDescriptor;
 class SurfaceDescriptorTiles;
 class ThebesBufferData;
 class PTextureChild;
 
 /**
- * See ActiveResourceTracker below.
- */
-class ActiveResource
-{
-public:
- virtual void NotifyInactive() = 0;
-  nsExpirationState* GetExpirationState() { return &mExpirationState; }
-  bool IsActivityTracked() { return mExpirationState.IsTracked(); }
-private:
-  nsExpirationState mExpirationState;
-};
-
-/**
- * A convenience class on top of nsExpirationTracker
- */
-class ActiveResourceTracker : public nsExpirationTracker<ActiveResource, 3>
-{
-public:
-  ActiveResourceTracker(uint32_t aExpirationCycle, const char* aName)
-  : nsExpirationTracker(aExpirationCycle, aName)
-  {}
-
-  virtual void NotifyExpired(ActiveResource* aResource) override
-  {
-    RemoveObject(aResource);
-    aResource->NotifyInactive();
-  }
-};
-
-/**
  * A transaction is a set of changes that happenned on the content side, that
  * should be sent to the compositor side.
  * CompositableForwarder is an interface to manage a transaction of
  * compositable objetcs.
  *
  * ShadowLayerForwarder is an example of a CompositableForwarder (that can
  * additionally forward modifications of the Layer tree).
  * ImageBridgeChild is another CompositableForwarder.
+ *
+ * CompositableForwarder implements KnowsCompositor for simplicity as all
+ * implementations of CompositableForwarder currently also implement KnowsCompositor.
+ * This dependency could be split if we add new use cases.
  */
-class CompositableForwarder : public TextureForwarder
+class CompositableForwarder : public KnowsCompositor
 {
 public:
-
-  CompositableForwarder()
-  {
-    mActiveResourceTracker = MakeUnique<ActiveResourceTracker>(1000, "CompositableForwarder");
-  }
-
   /**
    * Setup the IPDL actor for aCompositable to be part of layers
    * transactions.
    */
   virtual void Connect(CompositableClient* aCompositable,
                        ImageContainer* aImageContainer = nullptr) = 0;
 
   /**
@@ -158,30 +125,23 @@ public:
                            const nsTArray<TimedTextureClient>& aTextures) = 0;
   virtual void UseComponentAlphaTextures(CompositableClient* aCompositable,
                                          TextureClient* aClientOnBlack,
                                          TextureClient* aClientOnWhite) = 0;
 
   virtual void UpdateFwdTransactionId() = 0;
   virtual uint64_t GetFwdTransactionId() = 0;
 
-  virtual CompositableForwarder* AsCompositableForwarder() override { return this; }
-
   virtual bool InForwarderThread() = 0;
 
   void AssertInForwarderThread() {
     MOZ_ASSERT(InForwarderThread());
   }
 
-
-  ActiveResourceTracker& GetActiveResourceTracker() { return *mActiveResourceTracker.get(); }
-
 protected:
   nsTArray<RefPtr<TextureClient> > mTexturesToRemove;
   nsTArray<RefPtr<CompositableClient>> mCompositableClientsToRemove;
-
-  UniquePtr<ActiveResourceTracker> mActiveResourceTracker;
 };
 
 } // namespace layers
 } // namespace mozilla
 
 #endif
--- a/gfx/layers/ipc/CompositorBridgeChild.cpp
+++ b/gfx/layers/ipc/CompositorBridgeChild.cpp
@@ -47,19 +47,36 @@
 using mozilla::layers::LayerTransactionChild;
 using mozilla::dom::TabChildBase;
 using mozilla::Unused;
 using mozilla::gfx::GPUProcessManager;
 
 namespace mozilla {
 namespace layers {
 
+static int sShmemCreationCounter = 0;
+
+static void ResetShmemCounter()
+{
+  sShmemCreationCounter = 0;
+}
+
+static void ShmemAllocated(CompositorBridgeChild* aProtocol)
+{
+  sShmemCreationCounter++;
+  if (sShmemCreationCounter > 256) {
+    aProtocol->SendSyncWithCompositor();
+    ResetShmemCounter();
+    MOZ_PERFORMANCE_WARNING("gfx", "The number of shmem allocations is too damn high!");
+  }
+}
+
 static StaticRefPtr<CompositorBridgeChild> sCompositorBridge;
 
-Atomic<int32_t> TextureForwarder::sSerialCounter(0);
+Atomic<int32_t> KnowsCompositor::sSerialCounter(0);
 
 CompositorBridgeChild::CompositorBridgeChild(ClientLayerManager *aLayerManager)
   : mLayerManager(aLayerManager)
   , mCanSend(false)
   , mFwdTransactionId(0)
   , mMessageLoop(MessageLoop::current())
   , mSectionAllocator(nullptr)
 {
@@ -938,30 +955,33 @@ CompositorBridgeChild::CancelWaitForRecy
   RefPtr<TextureClient> client = mTexturesWaitingRecycled.Get(aTextureId);
   if (!client) {
     return;
   }
   mTexturesWaitingRecycled.Remove(aTextureId);
 }
 
 TextureClientPool*
-CompositorBridgeChild::GetTexturePool(LayersBackend aBackend,
+CompositorBridgeChild::GetTexturePool(KnowsCompositor* aAllocator,
                                       SurfaceFormat aFormat,
                                       TextureFlags aFlags)
 {
   for (size_t i = 0; i < mTexturePools.Length(); i++) {
-    if (mTexturePools[i]->GetBackend() == aBackend &&
+    if (mTexturePools[i]->GetBackend() == aAllocator->GetCompositorBackendType() &&
+        mTexturePools[i]->GetMaxTextureSize() == aAllocator->GetMaxTextureSize() &&
         mTexturePools[i]->GetFormat() == aFormat &&
         mTexturePools[i]->GetFlags() == aFlags) {
       return mTexturePools[i];
     }
   }
 
   mTexturePools.AppendElement(
-      new TextureClientPool(aBackend, aFormat,
+      new TextureClientPool(aAllocator->GetCompositorBackendType(),
+                            aAllocator->GetMaxTextureSize(),
+                            aFormat,
                             gfx::gfxVars::TileSize(),
                             aFlags,
                             gfxPrefs::LayersTilePoolShrinkTimeout(),
                             gfxPrefs::LayersTilePoolClearTimeout(),
                             gfxPrefs::LayersTileInitialPoolSize(),
                             gfxPrefs::LayersTilePoolUnusedSize(),
                             this));
 
@@ -1008,24 +1028,26 @@ CompositorBridgeChild::CreateTexture(con
   return PCompositorBridgeChild::SendPTextureConstructor(aSharedData, aLayersBackend, aFlags, 0 /* FIXME? */, aSerial);
 }
 
 bool
 CompositorBridgeChild::AllocUnsafeShmem(size_t aSize,
                                    ipc::SharedMemory::SharedMemoryType aType,
                                    ipc::Shmem* aShmem)
 {
+  ShmemAllocated(this);
   return PCompositorBridgeChild::AllocUnsafeShmem(aSize, aType, aShmem);
 }
 
 bool
 CompositorBridgeChild::AllocShmem(size_t aSize,
                              ipc::SharedMemory::SharedMemoryType aType,
                              ipc::Shmem* aShmem)
 {
+  ShmemAllocated(this);
   return PCompositorBridgeChild::AllocShmem(aSize, aType, aShmem);
 }
 
 void
 CompositorBridgeChild::DeallocShmem(ipc::Shmem& aShmem)
 {
     PCompositorBridgeChild::DeallocShmem(aShmem);
 }
@@ -1102,11 +1124,17 @@ CompositorBridgeChild::DeallocPAPZCTreeM
 void
 CompositorBridgeChild::ProcessingError(Result aCode, const char* aReason)
 {
   if (aCode != MsgDropped) {
     gfxDevCrash(gfx::LogReason::ProcessingError) << "Processing error in CompositorBridgeChild: " << int(aCode);
   }
 }
 
+void
+CompositorBridgeChild::WillEndTransaction()
+{
+  ResetShmemCounter();
+}
+
 } // namespace layers
 } // namespace mozilla
 
--- a/gfx/layers/ipc/CompositorBridgeChild.h
+++ b/gfx/layers/ipc/CompositorBridgeChild.h
@@ -38,22 +38,23 @@ class IAPZCTreeManager;
 class APZCTreeManagerChild;
 class ClientLayerManager;
 class CompositorBridgeParent;
 class TextureClient;
 class TextureClientPool;
 struct FrameMetrics;
 
 class CompositorBridgeChild final : public PCompositorBridgeChild,
-                                    public TextureForwarder,
-                                    public ShmemAllocator
+                                    public TextureForwarder
 {
   typedef InfallibleTArray<AsyncParentMessageData> AsyncParentMessageArray;
 
 public:
+  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(CompositorBridgeChild, override);
+
   explicit CompositorBridgeChild(ClientLayerManager *aLayerManager);
 
   void Destroy();
 
   /**
    * Lookup the FrameMetrics shared by the compositor process with the
    * associated FrameMetrics::ViewID. The returned FrameMetrics is used
    * in progressive paint calculations.
@@ -184,17 +185,17 @@ public:
    * make sure if there is no newer usage.
    */
   void NotifyNotUsed(uint64_t aTextureId, uint64_t aFwdTransactionId);
 
   void DeliverFence(uint64_t aTextureId, FenceHandle& aReleaseFenceHandle);
 
   virtual void CancelWaitForRecycle(uint64_t aTextureId) override;
 
-  TextureClientPool* GetTexturePool(LayersBackend aBackend,
+  TextureClientPool* GetTexturePool(KnowsCompositor* aAllocator,
                                     gfx::SurfaceFormat aFormat,
                                     TextureFlags aFlags);
   void ClearTexturePool();
 
   virtual FixedSizeSmallShmemSectionAllocator* GetTileLockAllocator() override;
 
   void HandleMemoryPressure();
 
@@ -216,19 +217,19 @@ public:
   RefPtr<IAPZCTreeManager> GetAPZCTreeManager(uint64_t aLayerTreeId);
 
   PAPZCTreeManagerChild* AllocPAPZCTreeManagerChild(const uint64_t& aLayersId) override;
   bool DeallocPAPZCTreeManagerChild(PAPZCTreeManagerChild* aActor) override;
 
   PAPZChild* AllocPAPZChild(const uint64_t& aLayersId) override;
   bool DeallocPAPZChild(PAPZChild* aActor) override;
 
-  virtual ShmemAllocator* AsShmemAllocator() override { return this; }
+  void ProcessingError(Result aCode, const char* aReason) override;
 
-  void ProcessingError(Result aCode, const char* aReason) override;
+  void WillEndTransaction();
 
 private:
   // Private destructor, to discourage deletion outside of Release():
   virtual ~CompositorBridgeChild();
 
   virtual PLayerTransactionChild*
     AllocPLayerTransactionChild(const nsTArray<LayersBackend>& aBackendHints,
                                 const uint64_t& aId,
--- a/gfx/layers/ipc/CompositorBridgeParent.h
+++ b/gfx/layers/ipc/CompositorBridgeParent.h
@@ -234,16 +234,19 @@ public:
   // ShmemAllocator
   virtual bool AllocShmem(size_t aSize,
                           mozilla::ipc::SharedMemory::SharedMemoryType aType,
                           mozilla::ipc::Shmem* aShmem) override;
   virtual bool AllocUnsafeShmem(size_t aSize,
                                 mozilla::ipc::SharedMemory::SharedMemoryType aType,
                                 mozilla::ipc::Shmem* aShmem) override;
   virtual void DeallocShmem(mozilla::ipc::Shmem& aShmem) override;
+
+  virtual bool RecvSyncWithCompositor() override { return true; }
+
 };
 
 class CompositorBridgeParent final : public CompositorBridgeParentBase
 {
   friend class CompositorVsyncScheduler;
   friend class CompositorThreadHolder;
   friend class InProcessCompositorSession;
   friend class gfx::GPUProcessManager;
--- a/gfx/layers/ipc/ISurfaceAllocator.cpp
+++ b/gfx/layers/ipc/ISurfaceAllocator.cpp
@@ -5,16 +5,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ISurfaceAllocator.h"
 
 #include "gfxPrefs.h"
 #include "mozilla/layers/ImageBridgeParent.h" // for ImageBridgeParent
 #include "mozilla/layers/TextureHost.h"       // for TextureHost
+#include "mozilla/layers/TextureForwarder.h"
 
 namespace mozilla {
 namespace layers {
 
 NS_IMPL_ISUPPORTS(GfxMemoryImageReporter, nsIMemoryReporter)
 
 mozilla::Atomic<ptrdiff_t> GfxMemoryImageReporter::sAmount(0);
 
@@ -90,28 +91,34 @@ HostIPCAllocator::SendPendingAsyncMessag
 // XXX - We should actually figure out the minimum shmem allocation size on
 // a certain platform and use that.
 const uint32_t sShmemPageSize = 4096;
 
 #ifdef DEBUG
 const uint32_t sSupportedBlockSize = 4;
 #endif
 
-FixedSizeSmallShmemSectionAllocator::FixedSizeSmallShmemSectionAllocator(ClientIPCAllocator* aShmProvider)
+FixedSizeSmallShmemSectionAllocator::FixedSizeSmallShmemSectionAllocator(LayersIPCChannel* aShmProvider)
 : mShmProvider(aShmProvider)
 {
-  MOZ_ASSERT(mShmProvider && mShmProvider->AsShmemAllocator());
+  MOZ_ASSERT(mShmProvider);
 }
 
 FixedSizeSmallShmemSectionAllocator::~FixedSizeSmallShmemSectionAllocator()
 {
   ShrinkShmemSectionHeap();
 }
 
 bool
+FixedSizeSmallShmemSectionAllocator::IPCOpen() const
+{
+  return mShmProvider->IPCOpen();
+}
+
+bool
 FixedSizeSmallShmemSectionAllocator::AllocShmemSection(uint32_t aSize, ShmemSection* aShmemSection)
 {
   // For now we only support sizes of 4. If we want to support different sizes
   // some more complicated bookkeeping should be added.
   MOZ_ASSERT(aSize == sSupportedBlockSize);
   MOZ_ASSERT(aShmemSection);
 
   if (!IPCOpen()) {
@@ -127,17 +134,17 @@ FixedSizeSmallShmemSectionAllocator::All
       aShmemSection->shmem() = mUsedShmems[i];
       MOZ_ASSERT(mUsedShmems[i].IsWritable());
       break;
     }
   }
 
   if (!aShmemSection->shmem().IsWritable()) {
     ipc::Shmem tmp;
-    if (!GetShmAllocator()->AllocUnsafeShmem(sShmemPageSize, OptimalShmemType(), &tmp)) {
+    if (!mShmProvider->AllocUnsafeShmem(sShmemPageSize, OptimalShmemType(), &tmp)) {
       return false;
     }
 
     ShmemSectionHeapHeader* header = tmp.get<ShmemSectionHeapHeader>();
     header->mTotalBlocks = 0;
     header->mAllocatedBlocks = 0;
 
     mUsedShmems.push_back(tmp);
@@ -228,17 +235,17 @@ FixedSizeSmallShmemSectionAllocator::Shr
   }
 
   // The loop will terminate as we either increase i, or decrease size
   // every time through.
   size_t i = 0;
   while (i < mUsedShmems.size()) {
     ShmemSectionHeapHeader* header = mUsedShmems[i].get<ShmemSectionHeapHeader>();
     if (header->mAllocatedBlocks == 0) {
-      GetShmAllocator()->DeallocShmem(mUsedShmems[i]);
+      mShmProvider->DeallocShmem(mUsedShmems[i]);
       // We don't particularly care about order, move the last one in the array
       // to this position.
       if (i < mUsedShmems.size() - 1) {
         mUsedShmems[i] = mUsedShmems[mUsedShmems.size() - 1];
       }
       mUsedShmems.pop_back();
     } else {
       i++;
--- a/gfx/layers/ipc/ISurfaceAllocator.h
+++ b/gfx/layers/ipc/ISurfaceAllocator.h
@@ -35,24 +35,24 @@ class Shmem;
 } // namespace ipc
 namespace gfx {
 class DataSourceSurface;
 } // namespace gfx
 
 namespace layers {
 
 class CompositableForwarder;
-class ShadowLayerForwarder;
 class TextureForwarder;
 
 class ShmemAllocator;
 class ShmemSectionAllocator;
 class LegacySurfaceDescriptorAllocator;
 class ClientIPCAllocator;
 class HostIPCAllocator;
+class LayersIPCChannel;
 
 enum BufferCapabilities {
   DEFAULT_BUFFER_CAPS = 0,
   /**
    * The allocated buffer must be efficiently mappable as a DataSourceSurface.
    */
   MAP_AS_IMAGE_SURFACE = 1 << 0,
   /**
@@ -86,19 +86,17 @@ public:
   // down-casting
 
   virtual ShmemAllocator* AsShmemAllocator() { return nullptr; }
 
   virtual ShmemSectionAllocator* AsShmemSectionAllocator() { return nullptr; }
 
   virtual CompositableForwarder* AsCompositableForwarder() { return nullptr; }
 
-  virtual TextureForwarder* AsTextureForwarder() { return nullptr; }
-
-  virtual ShadowLayerForwarder* AsLayerForwarder() { return nullptr; }
+  virtual TextureForwarder* GetTextureForwarder() { return nullptr; }
 
   virtual ClientIPCAllocator* AsClientAllocator() { return nullptr; }
 
   virtual HostIPCAllocator* AsHostIPCAllocator() { return nullptr; }
 
   virtual LegacySurfaceDescriptorAllocator*
   AsLegacySurfaceDescriptorAllocator() { return nullptr; }
 
@@ -294,36 +292,34 @@ public:
   };
 
   struct ShmemSectionHeapAllocation
   {
     Atomic<uint32_t> mStatus;
     uint32_t mSize;
   };
 
-  explicit FixedSizeSmallShmemSectionAllocator(ClientIPCAllocator* aShmProvider);
+  explicit FixedSizeSmallShmemSectionAllocator(LayersIPCChannel* aShmProvider);
 
   ~FixedSizeSmallShmemSectionAllocator();
 
   virtual bool AllocShmemSection(uint32_t aSize, ShmemSection* aShmemSection) override;
 
   virtual void DeallocShmemSection(ShmemSection& aShmemSection) override;
 
   virtual void MemoryPressure() override { ShrinkShmemSectionHeap(); }
 
   // can be called on the compositor process.
   static void FreeShmemSection(ShmemSection& aShmemSection);
 
   void ShrinkShmemSectionHeap();
 
-  ShmemAllocator* GetShmAllocator() { return mShmProvider->AsShmemAllocator(); }
-
-  bool IPCOpen() const { return mShmProvider->IPCOpen(); }
+  bool IPCOpen() const;
 
 protected:
   std::vector<mozilla::ipc::Shmem> mUsedShmems;
-  ClientIPCAllocator* mShmProvider;
+  LayersIPCChannel* mShmProvider;
 };
 
 } // namespace layers
 } // namespace mozilla
 
 #endif
--- a/gfx/layers/ipc/ImageBridgeChild.cpp
+++ b/gfx/layers/ipc/ImageBridgeChild.cpp
@@ -1222,17 +1222,16 @@ ImageBridgeChild::DispatchAllocShmemInte
 
   task.Wait();
 
   return params.mSuccess;
 }
 
 void
 ImageBridgeChild::ProxyDeallocShmemNow(SynchronousTask* aTask,
-                                       ISurfaceAllocator* aAllocator,
                                        ipc::Shmem* aShmem)
 {
   AutoCompleteTask complete(aTask);
 
   if (!CanSend()) {
     return;
   }
   DeallocShmem(*aShmem);
@@ -1250,17 +1249,16 @@ ImageBridgeChild::DeallocShmem(ipc::Shme
   }
 
   SynchronousTask task("AllocatorProxy Dealloc");
 
   RefPtr<Runnable> runnable = WrapRunnable(
     RefPtr<ImageBridgeChild>(this),
     &ImageBridgeChild::ProxyDeallocShmemNow,
     &task,
-    this,
     &aShmem);
   GetMessageLoop()->PostTask(runnable.forget());
 
   task.Wait();
 }
 
 PTextureChild*
 ImageBridgeChild::AllocPTextureChild(const SurfaceDescriptor&,
--- a/gfx/layers/ipc/ImageBridgeChild.h
+++ b/gfx/layers/ipc/ImageBridgeChild.h
@@ -104,24 +104,26 @@ bool InImageBridgeChildThread();
  * until the layer transaction happens. This means this scenario is not harmful.
  *
  * Since sending an image through imageBridge triggers compositing, the main thread is
  * not used at all (except for the very first transaction that provides the
  * CompositableHost with an AsyncID).
  */
 class ImageBridgeChild final : public PImageBridgeChild
                              , public CompositableForwarder
-                             , public ShmemAllocator
+                             , public TextureForwarder
 {
   friend class ImageContainer;
 
   typedef InfallibleTArray<AsyncParentMessageData> AsyncParentMessageArray;
 public:
+  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(ImageBridgeChild, override);
 
-  virtual ShmemAllocator* AsShmemAllocator() override { return this; }
+  TextureForwarder* GetTextureForwarder() override { return this; }
+  LayersIPCActor* GetLayersIPCActor() override { return this; }
 
   /**
    * Creates the image bridge with a dedicated thread for ImageBridgeChild.
    *
    * We may want to use a specifi thread in the future. In this case, use
    * CreateWithThread instead.
    */
   static void InitSameProcess();
@@ -167,22 +169,16 @@ public:
   virtual MessageLoop * GetMessageLoop() const override;
 
   virtual base::ProcessId GetParentPid() const override { return OtherPid(); }
 
   PCompositableChild* AllocPCompositableChild(const TextureInfo& aInfo,
                                               PImageContainerChild* aChild, uint64_t* aID) override;
   bool DeallocPCompositableChild(PCompositableChild* aActor) override;
 
-  /**
-   * This must be called by the static function DeleteImageBridgeSync defined
-   * in ImageBridgeChild.cpp ONLY.
-   */
-  ~ImageBridgeChild();
-
   virtual PTextureChild*
   AllocPTextureChild(const SurfaceDescriptor& aSharedData, const LayersBackend& aLayersBackend, const TextureFlags& aFlags, const uint64_t& aSerial) override;
 
   virtual bool
   DeallocPTextureChild(PTextureChild* actor) override;
 
   PMediaSystemResourceManagerChild*
   AllocPMediaSystemResourceManagerChild() override;
@@ -220,16 +216,23 @@ public:
   static void DispatchReleaseTextureClient(TextureClient* aClient);
 
   /**
    * Flush all Images sent to CompositableHost.
    */
   void FlushAllImages(ImageClient* aClient, ImageContainer* aContainer);
 
 private:
+
+  /**
+   * This must be called by the static function DeleteImageBridgeSync defined
+   * in ImageBridgeChild.cpp ONLY.
+   */
+  ~ImageBridgeChild();
+
   // Helpers for dispatching.
   already_AddRefed<CanvasClient> CreateCanvasClientNow(
     CanvasClient::CanvasClientType aType,
     TextureFlags aFlags);
   void CreateCanvasClientSync(
     SynchronousTask* aTask,
     CanvasClient::CanvasClientType aType,
     TextureFlags aFlags,
@@ -251,20 +254,17 @@ private:
 
   void FlushAllImagesSync(
     SynchronousTask* aTask,
     ImageClient* aClient,
     ImageContainer* aContainer,
     RefPtr<AsyncTransactionWaiter> aWaiter);
 
   void ProxyAllocShmemNow(SynchronousTask* aTask, AllocShmemParams* aParams);
-  void ProxyDeallocShmemNow(
-    SynchronousTask* aTask,
-    ISurfaceAllocator* aAllocator,
-    Shmem* aShmem);
+  void ProxyDeallocShmemNow(SynchronousTask* aTask, Shmem* aShmem);
 
 public:
   // CompositableForwarder
 
   virtual void Connect(CompositableClient* aCompositable,
                        ImageContainer* aImageContainer) override;
 
   virtual bool UsesImageBridge() const override { return true; }
--- a/gfx/layers/ipc/LayerTransactionParent.h
+++ b/gfx/layers/ipc/LayerTransactionParent.h
@@ -103,18 +103,16 @@ public:
     mPendingCompositorUpdates = aCount;
   }
   void AcknowledgeCompositorUpdate() {
     MOZ_ASSERT(mPendingCompositorUpdates > 0);
     mPendingCompositorUpdates--;
   }
 
 protected:
-  virtual bool RecvSyncWithCompositor() override { return true; }
-
   virtual bool RecvShutdown() override;
 
   virtual bool RecvPaintTime(const uint64_t& aTransactionId,
                              const TimeDuration& aPaintTime) override;
 
   virtual bool RecvUpdate(EditArray&& cset,
                           OpDestroyArray&& aToDestroy,
                           const uint64_t& aFwdTransactionId,
--- a/gfx/layers/ipc/PCompositorBridge.ipdl
+++ b/gfx/layers/ipc/PCompositorBridge.ipdl
@@ -215,16 +215,18 @@ parent:
 
   /**
    * Sent when the child has finished CaptureAllPlugins.
    */
   async AllPluginsCaptured();
 
   async PTexture(SurfaceDescriptor aSharedData, LayersBackend aBackend, TextureFlags aTextureFlags, uint64_t id, uint64_t aSerial);
 
+  sync SyncWithCompositor();
+
 child:
   // Send back Compositor Frame Metrics from APZCs so tiled layers can
   // update progressively.
   async SharedCompositorFrameMetrics(Handle metrics, CrossProcessMutexHandle mutex, uint64_t aLayersId, uint32_t aAPZCId);
   async ReleaseSharedCompositorFrameMetrics(ViewID aId, uint32_t aAPZCId);
 };
 
 } // layers
--- a/gfx/layers/ipc/PLayerTransaction.ipdl
+++ b/gfx/layers/ipc/PLayerTransaction.ipdl
@@ -120,16 +120,14 @@ parent:
   // Query a named property from the last frame
   sync RequestProperty(nsString property) returns (float value);
 
   // Tell the compositor to notify APZ that a layer has been confirmed for an
   // input event.
   async SetConfirmedTargetAPZC(uint64_t aInputBlockId, ScrollableLayerGuid[] aTargets);
 
   async Shutdown();
-
-  sync SyncWithCompositor();
 child:
   async __delete__();
 };
 
 } // namespace layers
 } // namespace mozilla
--- a/gfx/layers/ipc/ShadowLayers.cpp
+++ b/gfx/layers/ipc/ShadowLayers.cpp
@@ -41,33 +41,16 @@
 
 namespace mozilla {
 namespace ipc {
 class Shmem;
 } // namespace ipc
 
 namespace layers {
 
-static int sShmemCreationCounter = 0;
-
-static void ResetShmemCounter()
-{
-  sShmemCreationCounter = 0;
-}
-
-static void ShmemAllocated(LayerTransactionChild* aProtocol)
-{
-  sShmemCreationCounter++;
-  if (sShmemCreationCounter > 256) {
-    aProtocol->SendSyncWithCompositor();
-    ResetShmemCounter();
-    MOZ_PERFORMANCE_WARNING("gfx", "The number of shmem allocations is too damn high!");
-  }
-}
-
 using namespace mozilla::gfx;
 using namespace mozilla::gl;
 using namespace mozilla::ipc;
 
 class ClientTiledLayerBuffer;
 
 typedef nsTArray<SurfaceDescriptor> BufferArray;
 typedef std::vector<Edit> EditVector;
@@ -179,17 +162,17 @@ private:
 };
 struct AutoTxnEnd {
   explicit AutoTxnEnd(Transaction* aTxn) : mTxn(aTxn) {}
   ~AutoTxnEnd() { mTxn->End(); }
   Transaction* mTxn;
 };
 
 void
-TextureForwarder::IdentifyTextureHost(const TextureFactoryIdentifier& aIdentifier)
+KnowsCompositor::IdentifyTextureHost(const TextureFactoryIdentifier& aIdentifier)
 {
   mTextureFactoryIdentifier = aIdentifier;
 
   mSyncObject = SyncObject::CreateSyncObject(aIdentifier.mSyncHandle);
 }
 
 ShadowLayerForwarder::ShadowLayerForwarder(ClientLayerManager* aClientLayerManager)
  : mClientLayerManager(aClientLayerManager)
@@ -542,17 +525,17 @@ ShadowLayerForwarder::RemoveTextureFromC
                                                          TextureClient* aTexture)
 {
   NS_RUNTIMEABORT("not reached");
 }
 
 bool
 ShadowLayerForwarder::InWorkerThread()
 {
-  return MessageLoop::current() && (GetMessageLoop()->id() == MessageLoop::current()->id());
+  return MessageLoop::current() && (GetTextureForwarder()->GetMessageLoop()->id() == MessageLoop::current()->id());
 }
 
 void
 ShadowLayerForwarder::StorePluginWidgetConfigurations(const nsTArray<nsIWidget::Configuration>&
                                                       aConfigurations)
 {
   // Cache new plugin widget configs here until we call update, at which
   // point this data will get shipped over to chrome.
@@ -582,17 +565,17 @@ ShadowLayerForwarder::EndTransaction(Inf
                                      bool aScheduleComposite,
                                      uint32_t aPaintSequenceNumber,
                                      bool aIsRepeatTransaction,
                                      const mozilla::TimeStamp& aTransactionStart,
                                      bool* aSent)
 {
   *aSent = false;
 
-  ResetShmemCounter();
+  GetCompositorBridgeChild()->WillEndTransaction();
 
   MOZ_ASSERT(aId);
 
   PROFILER_LABEL("ShadowLayerForwarder", "EndTransaction",
     js::ProfileEntry::Category::GRAPHICS);
 
   RenderTraceScope rendertrace("Foward Transaction", "000091");
   MOZ_ASSERT(HasShadowManager(), "no manager to forward to");
@@ -722,17 +705,17 @@ ShadowLayerForwarder::EndTransaction(Inf
 
   mWindowOverlayChanged = false;
 
   TargetConfig targetConfig(mTxn->mTargetBounds,
                             mTxn->mTargetRotation,
                             mTxn->mTargetOrientation,
                             aRegionToClear);
 
-  if (!IsSameProcess()) {
+  if (!GetTextureForwarder()->IsSameProcess()) {
     MOZ_LAYERS_LOG(("[LayersForwarder] syncing before send..."));
     PlatformSyncBeforeUpdate();
   }
 
   profiler_tracing("Paint", "Rasterize", TRACING_INTERVAL_END);
   if (mTxn->mSwapRequired) {
     MOZ_LAYERS_LOG(("[LayersForwarder] sending transaction..."));
     RenderTraceScope rendertrace3("Forward Transaction", "000093");
@@ -777,77 +760,21 @@ ShadowLayerForwarder::SetLayerObserverEp
 {
   if (!HasShadowManager() || !mShadowManager->IPCOpen()) {
     return;
   }
   Unused << mShadowManager->SendSetLayerObserverEpoch(aLayerObserverEpoch);
 }
 
 bool
-ShadowLayerForwarder::AllocUnsafeShmem(size_t aSize,
-                                       ipc::SharedMemory::SharedMemoryType aShmType,
-                                       ipc::Shmem* aShmem)
-{
-  MOZ_ASSERT(HasShadowManager(), "no shadow manager");
-  if (!IPCOpen()) {
-    return false;
-  }
-
-  ShmemAllocated(mShadowManager);
-  return GetCompositorBridgeChild()->AllocUnsafeShmem(aSize, aShmType, aShmem);
-}
-
-bool
-ShadowLayerForwarder::AllocShmem(size_t aSize,
-                                 ipc::SharedMemory::SharedMemoryType aShmType,
-                                 ipc::Shmem* aShmem)
-{
-  MOZ_ASSERT(HasShadowManager(), "no shadow manager");
-  if (!IPCOpen()) {
-    return false;
-  }
-
-  ShmemAllocated(mShadowManager);
-  return GetCompositorBridgeChild()->AllocShmem(aSize, aShmType, aShmem);
-}
-
-void
-ShadowLayerForwarder::DeallocShmem(ipc::Shmem& aShmem)
-{
-  MOZ_ASSERT(HasShadowManager(), "no shadow manager");
-  if (HasShadowManager() && mShadowManager->IPCOpen()) {
-    GetCompositorBridgeChild()->DeallocShmem(aShmem);
-  }
-}
-
-bool
 ShadowLayerForwarder::IPCOpen() const
 {
   return HasShadowManager() && mShadowManager->IPCOpen();
 }
 
-bool
-ShadowLayerForwarder::IsSameProcess() const
-{
-  if (!HasShadowManager() || !mShadowManager->IPCOpen()) {
-    return false;
-  }
-  return mShadowManager->OtherPid() == base::GetCurrentProcId();
-}
-
-base::ProcessId
-ShadowLayerForwarder::GetParentPid() const
-{
-  if (!HasShadowManager() || !mShadowManager->IPCOpen()) {
-    return base::ProcessId();
-  }
-
-  return mShadowManager->OtherPid();
-}
-
 /**
   * We bail out when we have no shadow manager. That can happen when the
   * layer manager is created by the preallocated process.
   * See bug 914843 for details.
   */
 PLayerChild*
 ShadowLayerForwarder::ConstructShadowFor(ShadowableLayer* aLayer)
 {
@@ -900,32 +827,16 @@ void ShadowLayerForwarder::AttachAsyncCo
                                                    ShadowableLayer* aLayer)
 {
   MOZ_ASSERT(aLayer);
   MOZ_ASSERT(aCompositableID != 0); // zero is always an invalid compositable id.
   mTxn->AddEdit(OpAttachAsyncCompositable(nullptr, Shadow(aLayer),
                                           aCompositableID));
 }
 
-PTextureChild*
-ShadowLayerForwarder::CreateTexture(const SurfaceDescriptor& aSharedData,
-                                    LayersBackend aLayersBackend,
-                                    TextureFlags aFlags,
-                                    uint64_t aSerial)
-{
-  if (!HasShadowManager() ||
-      !mShadowManager->IPCOpen() ||
-      !mShadowManager->Manager()) {
-    gfxCriticalNote << "ShadowLayerForwarder::CreateTexture fails with HSM:" << HasShadowManager() << ", IPCOpen:" << mShadowManager->IPCOpen() << ", Destroyed:" << mShadowManager->IsDestroyed() << ", M:" << !!mShadowManager->Manager();
-    return nullptr;
-  }
-  return mShadowManager->Manager()->SendPTextureConstructor(aSharedData, aLayersBackend, aFlags, mShadowManager->GetId(), aSerial);
-}
-
-
 void ShadowLayerForwarder::SetShadowManager(PLayerTransactionChild* aShadowManager)
 {
   mShadowManager = static_cast<LayerTransactionChild*>(aShadowManager);
   mShadowManager->SetForwarder(this);
 }
 
 void ShadowLayerForwarder::StopReceiveAsyncParentMessge()
 {
@@ -1019,28 +930,28 @@ ShadowLayerForwarder::AllocSurfaceDescri
   gfx::SurfaceFormat format =
     gfxPlatform::GetPlatform()->Optimal2DFormatForContent(aContent);
   size_t size = ImageDataSerializer::ComputeRGBBufferSize(aSize, format);
   if (!size) {
     return false;
   }
 
   MemoryOrShmem bufferDesc;
-  if (IsSameProcess()) {
+  if (GetTextureForwarder()->IsSameProcess()) {
     uint8_t* data = new (std::nothrow) uint8_t[size];
     if (!data) {
       return false;
     }
     GfxMemoryImageReporter::DidAlloc(data);
     memset(data, 0, size);
     bufferDesc = reinterpret_cast<uintptr_t>(data);
   } else {
 
     mozilla::ipc::Shmem shmem;
-    if (!AllocUnsafeShmem(size, OptimalShmemType(), &shmem)) {
+    if (!GetTextureForwarder()->AllocUnsafeShmem(size, OptimalShmemType(), &shmem)) {
       return false;
     }
 
     bufferDesc = shmem;
   }
 
   // Use an intermediate buffer by default. Skipping the intermediate buffer is
   // only possible in certain configurations so let's keep it simple here for now.
@@ -1065,17 +976,17 @@ ShadowLayerForwarder::DestroySurfaceDesc
   MOZ_ASSERT(IPCOpen());
   if (!IPCOpen() || !aSurface) {
     return;
   }
 
   SurfaceDescriptorBuffer& desc = aSurface->get_SurfaceDescriptorBuffer();
   switch (desc.data().type()) {
     case MemoryOrShmem::TShmem: {
-      DeallocShmem(desc.data().get_Shmem());
+      GetTextureForwarder()->DeallocShmem(desc.data().get_Shmem());
       break;
     }
     case MemoryOrShmem::Tuintptr_t: {
       uint8_t* ptr = (uint8_t*)desc.data().get_uintptr_t();
       GfxMemoryImageReporter::WillFree(ptr);
       delete [] ptr;
       break;
     }
@@ -1097,38 +1008,23 @@ ShadowLayerForwarder::UpdateFwdTransacti
 uint64_t
 ShadowLayerForwarder::GetFwdTransactionId()
 {
   auto compositorBridge = GetCompositorBridgeChild();
   MOZ_DIAGNOSTIC_ASSERT(compositorBridge);
   return compositorBridge ? compositorBridge->GetFwdTransactionId() : 0;
 }
 
-void
-ShadowLayerForwarder::CancelWaitForRecycle(uint64_t aTextureId)
-{
-  auto compositorBridge = GetCompositorBridgeChild();
-  if (compositorBridge) {
-    compositorBridge->CancelWaitForRecycle(aTextureId);
-  }
-}
-
 CompositorBridgeChild*
 ShadowLayerForwarder::GetCompositorBridgeChild()
 {
   if (mCompositorBridgeChild) {
     return mCompositorBridgeChild;
   }
   if (!mShadowManager) {
     return nullptr;
   }
   mCompositorBridgeChild = static_cast<CompositorBridgeChild*>(mShadowManager->Manager());
   return mCompositorBridgeChild;
 }
 
-TextureForwarder*
-ShadowLayerForwarder::AsTextureForwarder()
-{
-  return GetCompositorBridgeChild();
-}
-
 } // namespace layers
 } // namespace mozilla
--- a/gfx/layers/ipc/ShadowLayers.h
+++ b/gfx/layers/ipc/ShadowLayers.h
@@ -12,17 +12,19 @@
 #include <stdint.h>                     // for uint64_t
 #include "gfxTypes.h"
 #include "mozilla/Attributes.h"         // for override
 #include "mozilla/gfx/Rect.h"
 #include "mozilla/WidgetUtils.h"        // for ScreenRotation
 #include "mozilla/dom/ScreenOrientation.h"  // for ScreenOrientation
 #include "mozilla/ipc/SharedMemory.h"   // for SharedMemory, etc
 #include "mozilla/layers/CompositableForwarder.h"
+#include "mozilla/layers/TextureForwarder.h"
 #include "mozilla/layers/CompositorTypes.h"  // for OpenMode, etc
+#include "mozilla/layers/CompositorBridgeChild.h"
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nsTArrayForwardDeclare.h"     // for InfallibleTArray
 #include "nsIWidget.h"
 #include <vector>
 
 namespace mozilla {
 namespace layers {
@@ -111,49 +113,31 @@ class Transaction;
  * Layer transactions maintain the shape of the shadow layer tree, and
  * synchronize the texture data held by compositables. Layer transactions
  * are always between the content thread and the compositor thread.
  * Compositable transactions are subset of a layer transaction with which only
  * compositables and textures can be manipulated, and does not always originate
  * from the content thread. (See CompositableForwarder.h and ImageBridgeChild.h)
  */
 
-class ShadowLayerForwarder final : public CompositableForwarder
-                                 , public ShmemAllocator
+class ShadowLayerForwarder final : public LayersIPCActor
+                                 , public CompositableForwarder
                                  , public LegacySurfaceDescriptorAllocator
 {
   friend class ClientLayerManager;
 
 public:
-  virtual ~ShadowLayerForwarder();
-
-  virtual ShmemAllocator* AsShmemAllocator() override { return this; }
-
-  virtual ShadowLayerForwarder* AsLayerForwarder() override { return this; }
-
-  // TODO: confusingly, this returns a pointer to the CompositorBridgeChild.
-  // Right now ShadowLayerForwarder inherits TextureForwarder but it would
-  // probably be best if it didn't, since it forwards all of the relevent
-  // methods to CompositorBridgeChild.
-  virtual TextureForwarder* AsTextureForwarder() override;
-
-  virtual LegacySurfaceDescriptorAllocator*
-  AsLegacySurfaceDescriptorAllocator() override { return this; }
+  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(ShadowLayerForwarder, override);
 
   /**
    * Setup the IPDL actor for aCompositable to be part of layers
    * transactions.
    */
-  virtual void Connect(CompositableClient* aCompositable,
-                       ImageContainer* aImageContainer) override;
-
-  virtual PTextureChild* CreateTexture(const SurfaceDescriptor& aSharedData,
-                                       LayersBackend aLayersBackend,
-                                       TextureFlags aFlags,
-                                       uint64_t aSerial) override;
+  void Connect(CompositableClient* aCompositable,
+               ImageContainer* aImageContainer) override;
 
   /**
    * Adds an edit in the layers transaction in order to attach
    * the corresponding compositable and layer on the compositor side.
    * Connect must have been called on aCompositable beforehand.
    */
   void Attach(CompositableClient* aCompositable,
               ShadowableLayer* aLayer);
@@ -225,21 +209,21 @@ public:
    * of mask layer.
    */
   void SetMask(ShadowableLayer* aLayer,
                ShadowableLayer* aMaskLayer);
 
   /**
    * See CompositableForwarder::UseTiledLayerBuffer
    */
-  virtual void UseTiledLayerBuffer(CompositableClient* aCompositable,
+  void UseTiledLayerBuffer(CompositableClient* aCompositable,
                                    const SurfaceDescriptorTiles& aTileLayerDescriptor) override;
 
-  virtual bool DestroyInTransaction(PTextureChild* aTexture, bool synchronously) override;
-  virtual bool DestroyInTransaction(PCompositableChild* aCompositable, bool synchronously) override;
+  bool DestroyInTransaction(PTextureChild* aTexture, bool synchronously) override;
+  bool DestroyInTransaction(PCompositableChild* aCompositable, bool synchronously) override;
 
   virtual void RemoveTextureFromCompositable(CompositableClient* aCompositable,
                                              TextureClient* aTexture) override;
 
   virtual void RemoveTextureFromCompositableAsync(AsyncTransactionTracker* aAsyncTransactionTracker,
                                                   CompositableClient* aCompositable,
                                                   TextureClient* aTexture) override;
 
@@ -339,35 +323,18 @@ public:
    *   calls Destroyed*Buffer(), which gives up control of the back
    *   buffer descriptor.  The actual back buffer surface is then
    *   destroyed using DestroySharedSurface() just before notifying
    *   the parent process.  When the parent process is notified, the
    *   LayerComposite also calls DestroySharedSurface() on its front
    *   buffer, and the double-buffer pair is gone.
    */
 
-
-  virtual bool AllocUnsafeShmem(size_t aSize,
-                                mozilla::ipc::SharedMemory::SharedMemoryType aType,
-                                mozilla::ipc::Shmem* aShmem) override;
-  virtual bool AllocShmem(size_t aSize,
-                          mozilla::ipc::SharedMemory::SharedMemoryType aType,
-                          mozilla::ipc::Shmem* aShmem) override;
-  virtual void DeallocShmem(mozilla::ipc::Shmem& aShmem) override;
-
   virtual bool IPCOpen() const override;
 
-  virtual bool IsSameProcess() const override;
-
-  virtual MessageLoop* GetMessageLoop() const override { return mMessageLoop; }
-
-  virtual void CancelWaitForRecycle(uint64_t aTextureId) override;
-
-  virtual base::ProcessId GetParentPid() const override;
-
   /**
    * Construct a shadow of |aLayer| on the "other side", at the
    * LayerManagerComposite.
    */
   PLayerChild* ConstructShadowFor(ShadowableLayer* aLayer);
 
   /**
    * Flag the next paint as the first for a document.
@@ -396,17 +363,22 @@ public:
 
   bool InForwarderThread() override {
     return NS_IsMainThread();
   }
 
   // Returns true if aSurface wraps a Shmem.
   static bool IsShmem(SurfaceDescriptor* aSurface);
 
+  TextureForwarder* GetTextureForwarder() override { return GetCompositorBridgeChild(); }
+  LayersIPCActor* GetLayersIPCActor() override { return this; }
+
 protected:
+  virtual ~ShadowLayerForwarder();
+
   explicit ShadowLayerForwarder(ClientLayerManager* aClientLayerManager);
 
 #ifdef DEBUG
   void CheckSurfaceDescriptor(const SurfaceDescriptor* aDescriptor) const;
 #else
   void CheckSurfaceDescriptor(const SurfaceDescriptor* aDescriptor) const {}
 #endif
 
--- a/gfx/layers/ipc/SharedPlanarYCbCrImage.cpp
+++ b/gfx/layers/ipc/SharedPlanarYCbCrImage.cpp
@@ -52,17 +52,17 @@ SharedPlanarYCbCrImage::SizeOfExcludingT
   // NB: Explicitly skipping mTextureClient, the memory is already reported
   //     at time of allocation in GfxMemoryImageReporter.
   // Not owned:
   // - mCompositable
   return 0;
 }
 
 TextureClient*
-SharedPlanarYCbCrImage::GetTextureClient(TextureForwarder* aForwarder)
+SharedPlanarYCbCrImage::GetTextureClient(KnowsCompositor* aForwarder)
 {
   return mTextureClient.get();
 }
 
 uint8_t*
 SharedPlanarYCbCrImage::GetBuffer()
 {
   // This should never be used
@@ -152,20 +152,19 @@ SharedPlanarYCbCrImage::AdoptData(const 
   mSize = aData.mPicSize;
   mOrigin = gfx::IntPoint(aData.mPicX, aData.mPicY);
 
   uint8_t *base = GetBuffer();
   uint32_t yOffset = aData.mYChannel - base;
   uint32_t cbOffset = aData.mCbChannel - base;
   uint32_t crOffset = aData.mCrChannel - base;
 
-  auto fwd = mCompositable->GetForwarder()->AsCompositableForwarder();
-  bool hasIntermediateBuffer = fwd ? ComputeHasIntermediateBuffer(gfx::SurfaceFormat::YUV,
-                                                                  fwd->GetCompositorBackendType())
-                                   : true;
+  auto fwd = mCompositable->GetForwarder();
+  bool hasIntermediateBuffer = ComputeHasIntermediateBuffer(gfx::SurfaceFormat::YUV,
+                                                            fwd->GetCompositorBackendType());
 
   static_cast<BufferTextureData*>(mTextureClient->GetInternalData())->SetDesciptor(
     YCbCrDescriptor(aData.mYSize, aData.mCbCrSize, yOffset, cbOffset, crOffset,
                     aData.mStereoMode, hasIntermediateBuffer)
   );
 
   return true;
 }
--- a/gfx/layers/ipc/SharedPlanarYCbCrImage.h
+++ b/gfx/layers/ipc/SharedPlanarYCbCrImage.h
@@ -25,17 +25,17 @@ class SharedPlanarYCbCrImage : public Pl
 {
 public:
   explicit SharedPlanarYCbCrImage(ImageClient* aCompositable);
 
 protected:
   ~SharedPlanarYCbCrImage();
 
 public:
-  virtual TextureClient* GetTextureClient(TextureForwarder* aForwarder) override;
+  virtual TextureClient* GetTextureClient(KnowsCompositor* aForwarder) override;
   virtual uint8_t* GetBuffer() override;
 
   virtual already_AddRefed<gfx::SourceSurface> GetAsSourceSurface() override;
   virtual bool CopyData(const PlanarYCbCrData& aData) override;
   virtual bool AdoptData(const Data &aData) override;
 
   virtual bool Allocate(PlanarYCbCrData& aData);
   virtual uint8_t* AllocateAndGetNewBuffer(uint32_t aSize) override;
--- a/gfx/layers/ipc/SharedRGBImage.cpp
+++ b/gfx/layers/ipc/SharedRGBImage.cpp
@@ -93,17 +93,17 @@ SharedRGBImage::GetBuffer()
 
 gfx::IntSize
 SharedRGBImage::GetSize()
 {
   return mSize;
 }
 
 TextureClient*
-SharedRGBImage::GetTextureClient(TextureForwarder* aForwarder)
+SharedRGBImage::GetTextureClient(KnowsCompositor* aForwarder)
 {
   return mTextureClient.get();
 }
 
 already_AddRefed<gfx::SourceSurface>
 SharedRGBImage::GetAsSourceSurface()
 {
   return nullptr;
--- a/gfx/layers/ipc/SharedRGBImage.h
+++ b/gfx/layers/ipc/SharedRGBImage.h
@@ -33,17 +33,17 @@ class SharedRGBImage : public Image
 {
 public:
   explicit SharedRGBImage(ImageClient* aCompositable);
 
 protected:
   ~SharedRGBImage();
 
 public:
-  virtual TextureClient* GetTextureClient(TextureForwarder* aForwarder) override;
+  virtual TextureClient* GetTextureClient(KnowsCompositor* aForwarder) override;
 
   virtual uint8_t* GetBuffer() override;
 
   gfx::IntSize GetSize() override;
 
   already_AddRefed<gfx::SourceSurface> GetAsSourceSurface() override;
 
   bool Allocate(gfx::IntSize aSize, gfx::SurfaceFormat aFormat);
--- a/gfx/layers/ipc/TextureForwarder.h
+++ b/gfx/layers/ipc/TextureForwarder.h
@@ -10,45 +10,125 @@
 #include <stdint.h>                     // for int32_t, uint64_t
 #include "gfxTypes.h"
 #include "mozilla/Attributes.h"         // for override
 #include "mozilla/layers/ISurfaceAllocator.h"  // for ISurfaceAllocator
 #include "mozilla/layers/LayersTypes.h"  // for LayersBackend
 #include "mozilla/layers/TextureClient.h"  // for TextureClient
 #include "nsRegion.h"                   // for nsIntRegion
 #include "mozilla/gfx/Rect.h"
+#include "nsExpirationTracker.h"
 
 namespace mozilla {
 namespace layers {
 
-class TextureForwarder : public ClientIPCAllocator
+
+/**
+ * See ActiveResourceTracker below.
+ */
+class ActiveResource
+{
+public:
+ virtual void NotifyInactive() = 0;
+  nsExpirationState* GetExpirationState() { return &mExpirationState; }
+  bool IsActivityTracked() { return mExpirationState.IsTracked(); }
+private:
+  nsExpirationState mExpirationState;
+};
+
+/**
+ * A convenience class on top of nsExpirationTracker
+ */
+class ActiveResourceTracker : public nsExpirationTracker<ActiveResource, 3>
 {
 public:
-  TextureForwarder()
-    : mSerial(++sSerialCounter)
+  ActiveResourceTracker(uint32_t aExpirationCycle, const char* aName)
+  : nsExpirationTracker(aExpirationCycle, aName)
   {}
 
+  virtual void NotifyExpired(ActiveResource* aResource) override
+  {
+    RemoveObject(aResource);
+    aResource->NotifyInactive();
+  }
+};
+
+/**
+ * An abstract interface for classes that implement the autogenerated
+ * IPDL actor class. Lets us check if they are still valid for IPC.
+ */
+class LayersIPCActor {
+public:
+  virtual bool IPCOpen() const { return true; }
+};
+
+/**
+ * An abstract interface for LayersIPCActors that implement a top-level
+ * IPDL protocol so also have their own channel.
+ * Has their own MessageLoop for message dispatch, and can allocate
+ * shmem.
+ */
+class LayersIPCChannel : public LayersIPCActor
+                       , public ShmemAllocator {
+public:
+  NS_IMETHOD_(MozExternalRefCountType) AddRef(void) = 0;
+  NS_IMETHOD_(MozExternalRefCountType) Release(void) = 0;
+
+  virtual bool IsSameProcess() const = 0;
+
+  virtual bool UsesImageBridge() const { return false; }
+
+  virtual base::ProcessId GetParentPid() const = 0;
+
+  virtual MessageLoop* GetMessageLoop() const = 0;
+
+  virtual FixedSizeSmallShmemSectionAllocator* GetTileLockAllocator() { return nullptr; }
+
+  virtual void CancelWaitForRecycle(uint64_t aTextureId) = 0;
+protected:
+  virtual ~LayersIPCChannel() {}
+};
+
+/**
+ * An abstract interface for classes that can allocate PTexture objects
+ * across IPDL. Currently a sub-class of LayersIPCChannel for simplicity
+ * since all our implementations use both, but could be independant if needed.
+ */
+class TextureForwarder : public LayersIPCChannel {
+public:
   /**
    * Create a TextureChild/Parent pair as as well as the TextureHost on the parent side.
    */
   virtual PTextureChild* CreateTexture(
     const SurfaceDescriptor& aSharedData,
     LayersBackend aLayersBackend,
     TextureFlags aFlags,
     uint64_t aSerial) = 0;
-
-  virtual TextureForwarder* AsTextureForwarder() override { return this; }
+};
 
-  virtual FixedSizeSmallShmemSectionAllocator* GetTileLockAllocator() { return nullptr; }
+/**
+ * An abstract interface for classes that are tied to a specific Compositor across
+ * IPDL and uses TextureFactoryIdentifier to describe this Compositor.
+ */
+class KnowsCompositor {
+public:
+  NS_IMETHOD_(MozExternalRefCountType) AddRef(void) = 0;
+  NS_IMETHOD_(MozExternalRefCountType) Release(void) = 0;
 
-  int32_t GetSerial() { return mSerial; }
+  KnowsCompositor()
+    : mSerial(++sSerialCounter)
+  {
+    mActiveResourceTracker = MakeUnique<ActiveResourceTracker>(1000, "CompositableForwarder");
+  }
 
   void IdentifyTextureHost(const TextureFactoryIdentifier& aIdentifier);
 
-  virtual int32_t GetMaxTextureSize() const override
+  SyncObject* GetSyncObject() { return mSyncObject; }
+
+  int32_t GetMaxTextureSize() const
   {
     return mTextureFactoryIdentifier.mMaxTextureSize;
   }
 
   /**
    * Returns the type of backend that is used off the main thread.
    * We only don't allow changing the backend type at runtime so this value can
    * be queried once and will not change until Gecko is restarted.
@@ -68,22 +148,33 @@ public:
     return mTextureFactoryIdentifier.mSupportsPartialUploads;
   }
 
   const TextureFactoryIdentifier& GetTextureFactoryIdentifier() const
   {
     return mTextureFactoryIdentifier;
   }
 
-  SyncObject* GetSyncObject() { return mSyncObject; }
+  int32_t GetSerial() { return mSerial; }
+
+  ActiveResourceTracker& GetActiveResourceTracker() { return *mActiveResourceTracker.get(); }
+
+  /**
+   * Helpers for finding other related interface. These are infallible.
+   */
+  virtual TextureForwarder* GetTextureForwarder() = 0;
+  virtual LayersIPCActor* GetLayersIPCActor() = 0;
 
 protected:
   TextureFactoryIdentifier mTextureFactoryIdentifier;
+
   RefPtr<SyncObject> mSyncObject;
 
+  UniquePtr<ActiveResourceTracker> mActiveResourceTracker;
+
   const int32_t mSerial;
   static mozilla::Atomic<int32_t> sSerialCounter;
 };
 
 } // namespace layers
 } // namespace mozilla
 
 #endif
--- a/gfx/layers/ipc/VideoBridgeChild.h
+++ b/gfx/layers/ipc/VideoBridgeChild.h
@@ -10,20 +10,23 @@
 #include "ISurfaceAllocator.h"
 #include "TextureForwarder.h"
 
 namespace mozilla {
 namespace layers {
 
 class VideoBridgeChild final : public PVideoBridgeChild
                              , public TextureForwarder
-                             , public ShmemAllocator
+                             , public KnowsCompositor
 {
 public:
-  ~VideoBridgeChild();
+  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(VideoBridgeChild, override);
+
+  TextureForwarder* GetTextureForwarder() override { return this; }
+  LayersIPCActor* GetLayersIPCActor() override { return this; }
 
   static void Startup();
   static void Shutdown();
 
   static VideoBridgeChild* GetSingleton();
 
   // PVideoBridgeChild
   PTextureChild* AllocPTextureChild(const SurfaceDescriptor& aSharedData,
@@ -48,23 +51,23 @@ public:
                                uint64_t aSerial) override;
 
   // ClientIPCAllocator
   base::ProcessId GetParentPid() const override { return OtherPid(); }
   MessageLoop * GetMessageLoop() const override { return mMessageLoop; }
   void CancelWaitForRecycle(uint64_t aTextureId) override { MOZ_ASSERT(false, "NO RECYCLING HERE"); }
 
   // ISurfaceAllocator
-  ShmemAllocator* AsShmemAllocator() override { return this; }
   bool IsSameProcess() const override;
 
   bool CanSend() { return true; }
 
 private:
   VideoBridgeChild();
+  ~VideoBridgeChild();
 
   MessageLoop* mMessageLoop;
 };
 
 } // namespace layers
 } // namespace mozilla
 
 #endif
--- a/gfx/layers/opengl/GrallocTextureClient.cpp
+++ b/gfx/layers/opengl/GrallocTextureClient.cpp
@@ -105,29 +105,29 @@ GrallocTextureData::GrallocTextureData(M
 }
 
 GrallocTextureData::~GrallocTextureData()
 {
   MOZ_COUNT_DTOR(GrallocTextureData);
 }
 
 void
-GrallocTextureData::Deallocate(ClientIPCAllocator* aAllocator)
+GrallocTextureData::Deallocate(LayersIPCChannel* aAllocator)
 {
   MOZ_ASSERT(aAllocator);
   if (aAllocator && aAllocator->IPCOpen()) {
     SharedBufferManagerChild::GetSingleton()->DeallocGrallocBuffer(mGrallocHandle);
   }
 
   mGrallocHandle = null_t();
   mGraphicBuffer = nullptr;
 }
 
 void
-GrallocTextureData::Forget(ClientIPCAllocator* aAllocator)
+GrallocTextureData::Forget(LayersIPCChannel* aAllocator)
 {
   MOZ_ASSERT(aAllocator);
   if (aAllocator && aAllocator->IPCOpen()) {
     SharedBufferManagerChild::GetSingleton()->DropGrallocBuffer(mGrallocHandle);
   }
 
   mGrallocHandle = null_t();
   mGraphicBuffer = nullptr;
@@ -285,17 +285,17 @@ GrallocTextureData::UpdateFromSurface(gf
 
   return true;
 }
 
 // static
 GrallocTextureData*
 GrallocTextureData::Create(gfx::IntSize aSize, AndroidFormat aAndroidFormat,
                            gfx::BackendType aMoz2dBackend, uint32_t aUsage,
-                           ClientIPCAllocator* aAllocator)
+                           LayersIPCChannel* aAllocator)
 {
   if (!aAllocator || !aAllocator->IPCOpen()) {
     return nullptr;
   }
   int32_t maxSize = aAllocator->AsClientAllocator()->GetMaxTextureSize();
   if (aSize.width > maxSize || aSize.height > maxSize) {
     return nullptr;
   }
@@ -340,17 +340,17 @@ GrallocTextureData::Create(gfx::IntSize 
 
   return new GrallocTextureData(handle, aSize, format, aMoz2dBackend);
 }
 
 // static
 GrallocTextureData*
 GrallocTextureData::CreateForDrawing(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                                      gfx::BackendType aMoz2dBackend,
-                                     ClientIPCAllocator* aAllocator)
+                                     LayersIPCChannel* aAllocator)
 {
   if (DisableGralloc(aFormat, aSize)) {
     return nullptr;
   }
 
 #if ANDROID_VERSION <= 15
   // Adreno 200 has a problem of drawing gralloc buffer width less than 64 and
   // drawing gralloc buffer with a height 9px-16px.
@@ -392,30 +392,30 @@ GrallocTextureData::GetTextureFlags() co
   }
   return TextureFlags::NO_FLAGS;
 }
 
 
 // static
 GrallocTextureData*
 GrallocTextureData::CreateForYCbCr(gfx::IntSize aYSize, gfx::IntSize aCbCrSize,
-                                   ClientIPCAllocator* aAllocator)
+                                   LayersIPCChannel* aAllocator)
 {
   MOZ_ASSERT(aYSize.width == aCbCrSize.width * 2);
   MOZ_ASSERT(aYSize.height == aCbCrSize.height * 2);
   return GrallocTextureData::Create(aYSize, HAL_PIXEL_FORMAT_YV12,
                                     gfx::BackendType::NONE,
                                     android::GraphicBuffer::USAGE_SW_READ_OFTEN,
                                     aAllocator);
 }
 
 // static
 GrallocTextureData*
 GrallocTextureData::CreateForGLRendering(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
-                                         ClientIPCAllocator* aAllocator)
+                                         LayersIPCChannel* aAllocator)
 {
   if (aFormat == gfx::SurfaceFormat::YUV) {
     return nullptr;
   }
   uint32_t usage = android::GraphicBuffer::USAGE_HW_RENDER |
                    android::GraphicBuffer::USAGE_HW_TEXTURE;
   return GrallocTextureData::Create(aSize, GetAndroidFormat(aFormat),
                                     gfx::BackendType::NONE, usage, aAllocator);
@@ -441,17 +441,17 @@ GrallocTextureData::TextureClientFromSha
                   (uint32_t)present,
                   (uint32_t)required);
     MOZ_CRASH("Flag requirement mismatch.");
   }
   return ret.forget();
 }
 
 TextureData*
-GrallocTextureData::CreateSimilar(ClientIPCAllocator* aAllocator,
+GrallocTextureData::CreateSimilar(LayersIPCChannel* aAllocator,
                                   TextureFlags aFlags,
                                   TextureAllocationFlags aAllocFlags) const
 {
   if (mFormat == gfx::SurfaceFormat::YUV) {
     return GrallocTextureData::CreateForYCbCr(mSize, mSize*2, aAllocator);
   } else {
     return GrallocTextureData::CreateForDrawing(mSize, mFormat, mMoz2DBackend, aAllocator);
   }
--- a/gfx/layers/opengl/GrallocTextureClient.h
+++ b/gfx/layers/opengl/GrallocTextureClient.h
@@ -46,40 +46,40 @@ public:
   virtual void Unlock() override;
 
   virtual void FillInfo(TextureData::Info& aInfo) const override;
 
   virtual already_AddRefed<gfx::DrawTarget> BorrowDrawTarget() override;
 
   virtual bool BorrowMappedData(MappedTextureData& aMap) override;
 
-  virtual void Deallocate(ClientIPCAllocator*) override;
+  virtual void Deallocate(LayersIPCChannel*) override;
 
-  virtual void Forget(ClientIPCAllocator*) override;
+  virtual void Forget(LayersIPCChannel*) override;
 
   static GrallocTextureData* CreateForDrawing(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
                                               gfx::BackendType aMoz2dBackend,
-                                              ClientIPCAllocator* aAllocator);
+                                              LayersIPCChannel* aAllocator);
 
   static GrallocTextureData* CreateForYCbCr(gfx::IntSize aYSize, gfx::IntSize aCbCrSize,
-                                            ClientIPCAllocator* aAllocator);
+                                            LayersIPCChannel* aAllocator);
 
   static GrallocTextureData* CreateForGLRendering(gfx::IntSize aSize, gfx::SurfaceFormat aFormat,
-                                                  ClientIPCAllocator* aAllocator);
+                                                  LayersIPCChannel* aAllocator);
 
   static GrallocTextureData* Create(gfx::IntSize aSize, AndroidFormat aFormat,
                                     gfx::BackendType aMoz2DBackend, uint32_t aUsage,
-                                    ClientIPCAllocator* aAllocator);
+                                    LayersIPCChannel* aAllocator);
 
 
   static already_AddRefed<TextureClient>
   TextureClientFromSharedSurface(gl::SharedSurface* abstractSurf, TextureFlags flags);
 
   virtual TextureData*
-  CreateSimilar(ClientIPCAllocator* aAllocator,
+  CreateSimilar(LayersIPCChannel* aAllocator,
                 TextureFlags aFlags = TextureFlags::DEFAULT,
                 TextureAllocationFlags aAllocFlags = ALLOC_DEFAULT) const override;
 
   // use TextureClient's default implementation
   virtual bool UpdateFromSurface(gfx::SourceSurface* aSurface) override;
 
   /// Hold android::MediaBuffer.
   /// MediaBuffer needs to be add refed to keep MediaBuffer alive while the texture
--- a/gfx/layers/opengl/MacIOSurfaceTextureClientOGL.cpp
+++ b/gfx/layers/opengl/MacIOSurfaceTextureClientOGL.cpp
@@ -108,23 +108,23 @@ MacIOSurfaceTextureData::BorrowDrawTarge
       (unsigned char*)mSurface->GetBaseAddress(),
       IntSize(mSurface->GetWidth(), mSurface->GetHeight()),
       mSurface->GetBytesPerRow(),
       mSurface->HasAlpha() ? SurfaceFormat::B8G8R8A8 : SurfaceFormat::B8G8R8X8,
       true);
 }
 
 void
-MacIOSurfaceTextureData::Deallocate(ClientIPCAllocator*)
+MacIOSurfaceTextureData::Deallocate(LayersIPCChannel*)
 {
   mSurface = nullptr;
 }
 
 void
-MacIOSurfaceTextureData::Forget(ClientIPCAllocator*)
+MacIOSurfaceTextureData::Forget(LayersIPCChannel*)
 {
   mSurface = nullptr;
 }
 
 bool
 MacIOSurfaceTextureData::UpdateFromSurface(gfx::SourceSurface* aSurface)
 {
   RefPtr<DrawTarget> dt = BorrowDrawTarget();
--- a/gfx/layers/opengl/MacIOSurfaceTextureClientOGL.h
+++ b/gfx/layers/opengl/MacIOSurfaceTextureClientOGL.h
@@ -30,19 +30,19 @@ public:
   virtual bool Lock(OpenMode, FenceHandle*) override;
 
   virtual void Unlock() override;
 
   virtual already_AddRefed<gfx::DrawTarget> BorrowDrawTarget() override;
 
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
-  virtual void Deallocate(ClientIPCAllocator*) override;
+  virtual void Deallocate(LayersIPCChannel*) override;
 
-  virtual void Forget(ClientIPCAllocator*) override;
+  virtual void Forget(LayersIPCChannel*) override;
 
   virtual bool UpdateFromSurface(gfx::SourceSurface* aSurface) override;
 
   // For debugging purposes only.
   already_AddRefed<gfx::DataSourceSurface> GetAsSurface();
 
 protected:
   MacIOSurfaceTextureData(MacIOSurface* aSurface,
--- a/gfx/layers/opengl/TextureClientOGL.cpp
+++ b/gfx/layers/opengl/TextureClientOGL.cpp
@@ -24,17 +24,17 @@ EGLImageTextureData::EGLImageTextureData
 : mImage(aImage)
 , mSize(aSize)
 {
   MOZ_ASSERT(aImage);
 }
 
 already_AddRefed<TextureClient>
 EGLImageTextureData::CreateTextureClient(EGLImageImage* aImage, gfx::IntSize aSize,
-                                         ClientIPCAllocator* aAllocator, TextureFlags aFlags)
+                                         LayersIPCChannel* aAllocator, TextureFlags aFlags)
 {
   MOZ_ASSERT(XRE_IsParentProcess(),
              "Can't pass an `EGLImage` between processes.");
 
   if (!aImage || !XRE_IsParentProcess()) {
     return nullptr;
   }
 
@@ -77,17 +77,17 @@ EGLImageTextureData::Serialize(SurfaceDe
 // AndroidSurface
 
 #ifdef MOZ_WIDGET_ANDROID
 
 already_AddRefed<TextureClient>
 AndroidSurfaceTextureData::CreateTextureClient(AndroidSurfaceTexture* aSurfTex,
                                                gfx::IntSize aSize,
                                                gl::OriginPos aOriginPos,
-                                               ClientIPCAllocator* aAllocator,
+                                               LayersIPCChannel* aAllocator,
                                                TextureFlags aFlags)
 {
   MOZ_ASSERT(XRE_IsParentProcess(),
              "Can't pass an android surfaces between processes.");
 
   if (!aSurfTex || !XRE_IsParentProcess()) {
     return nullptr;
   }
--- a/gfx/layers/opengl/TextureClientOGL.h
+++ b/gfx/layers/opengl/TextureClientOGL.h
@@ -21,25 +21,25 @@ namespace mozilla {
 namespace layers {
 
 class EGLImageTextureData : public TextureData
 {
 public:
 
   static already_AddRefed<TextureClient>
   CreateTextureClient(EGLImageImage* aImage, gfx::IntSize aSize,
-                      ClientIPCAllocator* aAllocator, TextureFlags aFlags);
+                      LayersIPCChannel* aAllocator, TextureFlags aFlags);
 
   virtual void FillInfo(TextureData::Info& aInfo) const override;
 
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
-  virtual void Deallocate(ClientIPCAllocator*) override { mImage = nullptr; }
+  virtual void Deallocate(LayersIPCChannel*) override { mImage = nullptr; }
 
-  virtual void Forget(ClientIPCAllocator*) override { mImage = nullptr; }
+  virtual void Forget(LayersIPCChannel*) override { mImage = nullptr; }
 
   // Unused functions.
   virtual bool Lock(OpenMode, FenceHandle*) override { return true; }
 
   virtual void Unlock() override {}
 
 protected:
   EGLImageTextureData(EGLImageImage* aImage, gfx::IntSize aSize);
@@ -52,32 +52,32 @@ protected:
 
 class AndroidSurfaceTextureData : public TextureData
 {
 public:
   static already_AddRefed<TextureClient>
   CreateTextureClient(gl::AndroidSurfaceTexture* aSurfTex,
                       gfx::IntSize aSize,
                       gl::OriginPos aOriginPos,
-                      ClientIPCAllocator* aAllocator,
+                      LayersIPCChannel* aAllocator,
                       TextureFlags aFlags);
 
   ~AndroidSurfaceTextureData();
 
   virtual void FillInfo(TextureData::Info& aInfo) const override;
 
   virtual bool Serialize(SurfaceDescriptor& aOutDescriptor) override;
 
   // Useless functions.
   virtual bool Lock(OpenMode, FenceHandle*) override { return true; }
 
   virtual void Unlock() override {}
 
   // Our data is always owned externally.
-  virtual void Deallocate(ClientIPCAllocator*) override {}
+  virtual void Deallocate(LayersIPCChannel*) override {}
 
 protected:
   AndroidSurfaceTextureData(gl::AndroidSurfaceTexture* aSurfTex, gfx::IntSize aSize);
 
   const RefPtr<gl::AndroidSurfaceTexture> mSurfTex;
   const gfx::IntSize mSize;
 };
 
--- a/gfx/skia/skia/src/ports/SkMemory_mozalloc.cpp
+++ b/gfx/skia/skia/src/ports/SkMemory_mozalloc.cpp
@@ -6,18 +6,25 @@
  * found in the LICENSE file.
  */
 
 #include "SkTypes.h"
 
 #include "mozilla/mozalloc.h"
 #include "mozilla/mozalloc_abort.h"
 #include "mozilla/mozalloc_oom.h"
+#include "prenv.h"
 
 void sk_abort_no_print() {
+#ifdef SK_DEBUG
+    const char* env = PR_GetEnv("MOZ_SKIA_DISABLE_ASSERTS");
+    if (env && *env != '0') {
+        return;
+    }
+#endif
     mozalloc_abort("Abort from sk_abort");
 }
 
 void sk_out_of_memory(void) {
     SkDEBUGFAIL("sk_out_of_memory");
     mozalloc_handle_oom(0);
 }
 
--- a/gfx/thebes/DeviceManagerDx.cpp
+++ b/gfx/thebes/DeviceManagerDx.cpp
@@ -277,17 +277,16 @@ DeviceManagerDx::CreateCompositorDeviceH
       aD3d11.SetFailed(FeatureStatus::CrashedInHandler, "Crashed trying to acquire a D3D11 device",
                        NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_DEVICE1"));
     }
     return false;
   }
 
   if (FAILED(hr) || !device) {
     if (!aAttemptVideoSupport) {
-      gfxCriticalError() << "D3D11 device creation failed: " << hexa(hr);
       aD3d11.SetFailed(FeatureStatus::Failed, "Failed to acquire a D3D11 device",
                        NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_DEVICE2"));
     }
     return false;
   }
   if (!D3D11Checks::DoesDeviceWork()) {
     if (!aAttemptVideoSupport) {
       aD3d11.SetFailed(FeatureStatus::Broken, "Direct3D11 device was determined to be broken",
--- a/gfx/thebes/gfxFont.cpp
+++ b/gfx/thebes/gfxFont.cpp
@@ -3100,16 +3100,20 @@ gfxFont::InitFakeSmallCapsRun(DrawTarget
                               uint16_t        aOrientation,
                               Script          aScript,
                               bool            aSyntheticLower,
                               bool            aSyntheticUpper)
 {
     bool ok = true;
 
     RefPtr<gfxFont> smallCapsFont = GetSmallCapsFont();
+    if (!smallCapsFont) {
+        NS_WARNING("failed to get reduced-size font for smallcaps!");
+        smallCapsFont = this;
+    }
 
     enum RunCaseAction {
         kNoChange,
         kUppercaseReduce,
         kUppercase
     };
 
     RunCaseAction runAction = kNoChange;
--- a/gfx/thebes/gfxFont.h
+++ b/gfx/thebes/gfxFont.h
@@ -298,17 +298,17 @@ public:
     // It's OK to call this even if Init() has not been called.
     static void Shutdown();
 
     // Look up a font in the cache. Returns an addrefed pointer, or null
     // if there's nothing matching in the cache
     already_AddRefed<gfxFont>
     Lookup(const gfxFontEntry* aFontEntry,
            const gfxFontStyle* aStyle,
-           const gfxCharacterMap* aUnicodeRangeMap = nullptr);
+           const gfxCharacterMap* aUnicodeRangeMap);
 
     // We created a new font (presumably because Lookup returned null);
     // put it in the cache. The font's refcount should be nonzero. It is
     // allowable to add a new font even if there is one already in the
     // cache with the same key; we'll forget about the old one.
     void AddNew(gfxFont *aFont);
 
     // The font's refcount has gone to zero; give ownership of it to
--- a/gfx/thebes/gfxFontEntry.cpp
+++ b/gfx/thebes/gfxFontEntry.cpp
@@ -275,17 +275,18 @@ gfxFontEntry::RealFaceName()
 }
 
 already_AddRefed<gfxFont>
 gfxFontEntry::FindOrMakeFont(const gfxFontStyle *aStyle,
                              bool aNeedsBold,
                              gfxCharacterMap* aUnicodeRangeMap)
 {
     // the font entry name is the psname, not the family name
-    RefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(this, aStyle);
+    RefPtr<gfxFont> font =
+        gfxFontCache::GetCache()->Lookup(this, aStyle, aUnicodeRangeMap);
 
     if (!font) {
         gfxFont *newFont = CreateFontInstance(aStyle, aNeedsBold);
         if (!newFont)
             return nullptr;
         if (!newFont->Valid()) {
             delete newFont;
             return nullptr;
--- a/gfx/thebes/gfxFontUtils.cpp
+++ b/gfx/thebes/gfxFontUtils.cpp
@@ -913,26 +913,28 @@ IsValidSFNTVersion(uint32_t version)
 {
     // normally 0x00010000, CFF-style OT fonts == 'OTTO' and Apple TT fonts = 'true'
     // 'typ1' is also possible for old Type 1 fonts in a SFNT container but not supported
     return version == 0x10000 ||
            version == TRUETYPE_TAG('O','T','T','O') ||
            version == TRUETYPE_TAG('t','r','u','e');
 }
 
-// copy and swap UTF-16 values, assume no surrogate pairs, can be in place
+// Copy and swap UTF-16 values, assume no surrogate pairs, can be in place.
+// aInBuf and aOutBuf are NOT necessarily 16-bit-aligned, so we should avoid
+// accessing them directly as uint16_t* values.
+// aLen is count of UTF-16 values, so the byte buffers are twice that.
 static void
-CopySwapUTF16(const uint16_t *aInBuf, uint16_t *aOutBuf, uint32_t aLen)
+CopySwapUTF16(const char* aInBuf, char* aOutBuf, uint32_t aLen)
 {
-    const uint16_t *end = aInBuf + aLen;
+    const char* end = aInBuf + aLen * 2;
     while (aInBuf < end) {
-        uint16_t value = *aInBuf;
-        *aOutBuf = (value >> 8) | (value & 0xff) << 8;
-        aOutBuf++;
-        aInBuf++;
+        uint8_t b0 = *aInBuf++;
+        *aOutBuf++ = *aInBuf++;
+        *aOutBuf++ = b0;
     }
 }
 
 gfxUserFontType
 gfxFontUtils::DetermineFontDataType(const uint8_t *aFontData, uint32_t aFontDataLength)
 {
     // test for OpenType font data
     // problem: EOT-Lite with 0x10000 length will look like TrueType!
@@ -1441,23 +1443,23 @@ gfxFontUtils::DecodeFontName(const char 
         NS_WARNING(warnBuf);
 #endif
         return false;
     }
 
     if (csName[0] == 0) {
         // empty charset name: data is utf16be, no need to instantiate a converter
         uint32_t strLen = aByteLen / 2;
+        aName.SetLength(strLen);
 #ifdef IS_LITTLE_ENDIAN
-        aName.SetLength(strLen);
-        CopySwapUTF16(reinterpret_cast<const uint16_t*>(aNameData),
-                      reinterpret_cast<uint16_t*>(aName.BeginWriting()), strLen);
+        CopySwapUTF16(aNameData, reinterpret_cast<char*>(aName.BeginWriting()),
+                      strLen);
 #else
-        aName.Assign(reinterpret_cast<const char16_t*>(aNameData), strLen);
-#endif    
+        memcpy(aName.BeginWriting(), aNameData, strLen * 2);
+#endif
         return true;
     }
 
     nsCOMPtr<nsIUnicodeDecoder> decoder =
         mozilla::dom::EncodingUtils::DecoderForEncoding(csName);
     if (!decoder) {
         NS_WARNING("failed to get the decoder for a font name string");
         return false;
--- a/gfx/thebes/gfxFontconfigFonts.cpp
+++ b/gfx/thebes/gfxFontconfigFonts.cpp
@@ -1681,17 +1681,18 @@ gfxFcFont::GetSubSuperscriptFont(int32_t
     style.AdjustForSubSuperscript(aAppUnitsPerDevPixel);
     return MakeScaledFont(&style, style.size / GetStyle()->size);
 }
 
 already_AddRefed<gfxFont>
 gfxFcFont::MakeScaledFont(gfxFontStyle *aFontStyle, gfxFloat aScaleFactor)
 {
     gfxFcFontEntry* fe = static_cast<gfxFcFontEntry*>(GetFontEntry());
-    RefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(fe, aFontStyle);
+    RefPtr<gfxFont> font =
+        gfxFontCache::GetCache()->Lookup(fe, aFontStyle, nullptr);
     if (font) {
         return font.forget();
     }
 
     cairo_matrix_t fontMatrix;
     cairo_scaled_font_get_font_matrix(mScaledFont, &fontMatrix);
     cairo_matrix_scale(&fontMatrix, aScaleFactor, aScaleFactor);
 
@@ -1941,17 +1942,18 @@ gfxFcFont::GetOrMakeFont(FcPattern *aReq
         }
     }
 
     gfxFontStyle style(*aFontStyle);
     style.size = GetPixelSize(renderPattern);
     style.style = gfxFontconfigUtils::GetThebesStyle(renderPattern);
     style.weight = gfxFontconfigUtils::GetThebesWeight(renderPattern);
 
-    RefPtr<gfxFont> font = gfxFontCache::GetCache()->Lookup(fe, &style);
+    RefPtr<gfxFont> font =
+        gfxFontCache::GetCache()->Lookup(fe, &style, nullptr);
     if (!font) {
         // Note that a file/index pair (or FT_Face) and the gfxFontStyle are
         // not necessarily enough to provide a key that will describe a unique
         // font.  cairoFont contains information from renderPattern, which is a
         // fully resolved pattern from FcFontRenderPrepare.
         // FcFontRenderPrepare takes the requested pattern and the face
         // pattern as input and can modify elements of the resulting pattern
         // that affect rendering but are not included in the gfxFontStyle.
--- a/gfx/vr/ipc/VRManagerChild.h
+++ b/gfx/vr/ipc/VRManagerChild.h
@@ -26,19 +26,24 @@ class PCompositableChild;
 class TextureClient;
 }
 namespace gfx {
 class VRLayerChild;
 class VRDisplayClient;
 
 class VRManagerChild : public PVRManagerChild
                      , public layers::TextureForwarder
-                     , public layers::ShmemAllocator
+                     , public layers::KnowsCompositor
 {
 public:
+  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(VRManagerChild, override);
+
+  TextureForwarder* GetTextureForwarder() override { return this; }
+  LayersIPCActor* GetLayersIPCActor() override { return this; }
+
   static VRManagerChild* Get();
 
   // Indicate that an observer wants to receive VR events.
   void AddListener(dom::VREventObserver* aObserver);
   // Indicate that an observer should no longer receive VR events.
   void RemoveListener(dom::VREventObserver* aObserver);
 
   int GetInputFrameID();
@@ -106,18 +111,16 @@ protected:
   virtual bool RecvParentAsyncMessages(InfallibleTArray<AsyncParentMessageData>&& aMessages) override;
 
   virtual bool RecvNotifyVSync() override;
   virtual bool RecvNotifyVRVSync(const uint32_t& aDisplayID) override;
 
 
   // ShmemAllocator
 
-  virtual ShmemAllocator* AsShmemAllocator() override { return this; }
-
   virtual bool AllocShmem(size_t aSize,
                           ipc::SharedMemory::SharedMemoryType aType,
                           ipc::Shmem* aShmem) override;
 
   virtual bool AllocUnsafeShmem(size_t aSize,
                                 ipc::SharedMemory::SharedMemoryType aType,
                                 ipc::Shmem* aShmem) override;
 
--- a/js/src/asmjs/WasmBaselineCompile.cpp
+++ b/js/src/asmjs/WasmBaselineCompile.cpp
@@ -2639,16 +2639,17 @@ class BaseCompiler
                 masm.jump(rejoin());
             } else {
 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
                 if (isFloat)
                     masm.outOfLineWasmTruncateFloat32ToInt32(fsrc, isUnsigned, rejoin());
                 else
                     masm.outOfLineWasmTruncateDoubleToInt32(fsrc, isUnsigned, rejoin());
 #else
+                (void)isUnsigned; // Suppress warning for unused private.
                 MOZ_CRASH("BaseCompiler platform hook: OutOfLineTruncateF32OrF64ToI32 wasm");
 #endif
             }
         }
     };
 
     MOZ_MUST_USE
     bool truncateF32ToI32(RegF32 src, RegI32 dest, bool isUnsigned) {
--- a/js/src/asmjs/WasmBinary.cpp
+++ b/js/src/asmjs/WasmBinary.cpp
@@ -35,16 +35,17 @@ Decoder::fail(const char* msg, ...) {
     if (!str)
         return false;
 
     return fail(Move(str));
 }
 
 bool
 Decoder::fail(UniqueChars msg) {
+    MOZ_ASSERT(error_);
     UniqueChars strWithOffset(JS_smprintf("at offset %zu: %s", currentOffset(), msg.get()));
     if (!strWithOffset)
         return false;
 
     *error_ = Move(strWithOffset);
     return false;
 }
 
--- a/js/src/asmjs/WasmBinary.h
+++ b/js/src/asmjs/WasmBinary.h
@@ -765,17 +765,17 @@ class Decoder
             return false;
         *out = s | SInt(byte) << shift;
         return true;
     }
 
     static const size_t ExprLimit = 2 * UINT8_MAX - 1;
 
   public:
-    Decoder(const uint8_t* begin, const uint8_t* end, UniqueChars* error = nullptr)
+    Decoder(const uint8_t* begin, const uint8_t* end, UniqueChars* error)
       : beg_(begin),
         end_(end),
         cur_(begin),
         error_(error)
     {
         MOZ_ASSERT(begin <= end);
     }
     explicit Decoder(const Bytes& bytes, UniqueChars* error = nullptr)
--- a/js/src/asmjs/WasmBinaryToAST.cpp
+++ b/js/src/asmjs/WasmBinaryToAST.cpp
@@ -41,26 +41,30 @@ enum AstDecodeTerminationKind
 
 struct AstDecodeStackItem
 {
     AstExpr* expr;
     AstDecodeTerminationKind terminationKind;
     ExprType type;
 
     explicit AstDecodeStackItem()
-        : expr(nullptr),
-          terminationKind(AstDecodeTerminationKind::Unknown),
-          type(ExprType::Limit) {}
-    explicit AstDecodeStackItem(AstDecodeTerminationKind terminationKind,
-                                ExprType type)
-        : expr(nullptr), terminationKind(terminationKind), type(type) {}
+      : expr(nullptr),
+        terminationKind(AstDecodeTerminationKind::Unknown),
+        type(ExprType::Limit)
+    {}
+    explicit AstDecodeStackItem(AstDecodeTerminationKind terminationKind, ExprType type)
+      : expr(nullptr),
+        terminationKind(terminationKind),
+        type(type)
+    {}
     explicit AstDecodeStackItem(AstExpr* expr)
-        : expr(expr),
-          terminationKind(AstDecodeTerminationKind::Unknown),
-          type(ExprType::Limit) {}
+     : expr(expr),
+       terminationKind(AstDecodeTerminationKind::Unknown),
+       type(ExprType::Limit)
+    {}
 };
 
 // We don't define a Value type because ExprIter doesn't push void values, which
 // we actually need here because we're building an AST, so we maintain our own
 // stack.
 struct AstDecodePolicy : ExprIterPolicy
 {
     // Enable validation because we can be called from wasmBinaryToText on bytes
@@ -92,17 +96,18 @@ class AstDecodeContext
     AstDecodeStack exprs_;
     DepthStack depths_;
     const ValTypeVector* locals_;
     AstNameVector blockLabels_;
     uint32_t currentLabelIndex_;
     ExprType retType_;
 
   public:
-    AstDecodeContext(JSContext* cx, LifoAlloc& lifo, Decoder& d, AstModule& module, bool generateNames)
+    AstDecodeContext(JSContext* cx, LifoAlloc& lifo, Decoder& d, AstModule& module,
+                     bool generateNames)
      : cx(cx),
        lifo(lifo),
        d(d),
        generateNames(generateNames),
        module_(module),
        funcSigs_(lifo),
        iter_(nullptr),
        exprs_(lifo),
@@ -1464,17 +1469,16 @@ AstDecodeFunctionSection(AstDecodeContex
 
     uint32_t numDecls;
     if (!c.d.readVarU32(&numDecls))
         return c.d.fail("expected number of declarations");
 
     if (numDecls > MaxFuncs)
         return c.d.fail("too many functions");
 
-
     if (!c.funcSigs().resize(numDecls))
         return false;
 
     for (uint32_t i = 0; i < numDecls; i++) {
         if (!AstDecodeSignatureIndex(c, &c.funcSigs()[i]))
             return false;
     }
 
@@ -2142,11 +2146,13 @@ wasm::BinaryToAst(JSContext* cx, const u
             JS_ReportErrorNumber(c.cx, GetErrorMessage, nullptr, JSMSG_WASM_COMPILE_ERROR,
                                  error.get());
             return false;
         }
         ReportOutOfMemory(c.cx);
         return false;
     }
 
+    MOZ_ASSERT(!error, "unreported error in decoding");
+
     *module = result;
     return true;
 }
--- a/js/src/asmjs/WasmBinaryToAST.h
+++ b/js/src/asmjs/WasmBinaryToAST.h
@@ -23,14 +23,15 @@
 #include "asmjs/WasmTypes.h"
 
 #include "ds/LifoAlloc.h"
 
 namespace js {
 namespace wasm {
 
 bool
-BinaryToAst(JSContext* cx, const uint8_t* bytes, uint32_t length, LifoAlloc& lifo, AstModule** module);
+BinaryToAst(JSContext* cx, const uint8_t* bytes, uint32_t length, LifoAlloc& lifo,
+            AstModule** module);
 
 } // end wasm namespace
 } // end js namespace
 
 #endif // namespace wasmbinarytoast_h
--- a/js/src/asmjs/WasmBinaryToExperimentalText.cpp
+++ b/js/src/asmjs/WasmBinaryToExperimentalText.cpp
@@ -124,17 +124,18 @@ struct WasmPrintContext
     WasmPrintBuffer& buffer;
     const ExperimentalTextFormatting& f;
     GeneratedSourceMap* maybeSourceMap;
     uint32_t indent;
 
     uint32_t currentFuncIndex;
     PrintOperatorPrecedence currentPrecedence;
 
-    WasmPrintContext(JSContext* cx, AstModule* module, WasmPrintBuffer& buffer, const ExperimentalTextFormatting& f, GeneratedSourceMap* wasmSourceMap_)
+    WasmPrintContext(JSContext* cx, AstModule* module, WasmPrintBuffer& buffer,
+                     const ExperimentalTextFormatting& f, GeneratedSourceMap* wasmSourceMap_)
       : cx(cx),
         module(module),
         buffer(buffer),
         f(f),
         maybeSourceMap(wasmSourceMap_),
         indent(0),
         currentFuncIndex(0),
         currentPrecedence(PrintOperatorPrecedence::ExpressionPrecedence)
--- a/js/src/asmjs/WasmTypes.cpp
+++ b/js/src/asmjs/WasmTypes.cpp
@@ -31,16 +31,18 @@
 #include "vm/Interpreter.h"
 
 #include "vm/Stack-inl.h"
 
 using namespace js;
 using namespace js::jit;
 using namespace js::wasm;
 
+using mozilla::IsNaN;
+
 void
 Val::writePayload(uint8_t* dst) const
 {
     switch (type_) {
       case ValType::I32:
       case ValType::F32:
         memcpy(dst, &u.i32_, sizeof(u.i32_));
         return;
@@ -201,33 +203,29 @@ UModI64(uint32_t x_hi, uint32_t x_lo, ui
     uint64_t y = ((uint64_t)y_hi << 32) + y_lo;
     MOZ_ASSERT(y != 0);
     return x % y;
 }
 
 static int64_t
 TruncateDoubleToInt64(double input)
 {
-    // Note: INT64_MAX is not representable in double. It is actually INT64_MAX + 1.
-    // Therefore also sending the failure value.
-    if (input >= double(INT64_MAX))
-        return 0x8000000000000000;
-    if (input < double(INT64_MIN))
+    // Note: INT64_MAX is not representable in double. It is actually
+    // INT64_MAX + 1.  Therefore also sending the failure value.
+    if (input >= double(INT64_MAX) || input < double(INT64_MIN) || IsNaN(input))
         return 0x8000000000000000;
     return int64_t(input);
 }
 
 static uint64_t
 TruncateDoubleToUint64(double input)
 {
     // Note: UINT64_MAX is not representable in double. It is actually UINT64_MAX + 1.
     // Therefore also sending the failure value.
-    if (input >= double(UINT64_MAX))
-        return 0x8000000000000000;
-    if (input <= -1.0)
+    if (input >= double(UINT64_MAX) || input <= -1.0 || IsNaN(input))
         return 0x8000000000000000;
     return uint64_t(input);
 }
 
 static double
 Int64ToFloatingPoint(int32_t x_hi, uint32_t x_lo)
 {
     int64_t x = int64_t((uint64_t(x_hi) << 32)) + int64_t(x_lo);
--- a/js/src/devtools/automation/autospider.py
+++ b/js/src/devtools/automation/autospider.py
@@ -174,16 +174,17 @@ if os.path.exists(os.path.join(compiler_
     env.setdefault('CXX', os.path.join(compiler_dir, 'bin', cxx))
     platlib = 'lib64' if word_bits == 64 else 'lib'
     env.setdefault('LD_LIBRARY_PATH', os.path.join(compiler_dir, platlib))
 else:
     env.setdefault('CC', compiler)
     env.setdefault('CXX', cxx)
 
 if platform.system() == 'Darwin':
+    os.environ['SOURCE'] = DIR.source
     set_vars_from_script(os.path.join(DIR.scripts, 'macbuildenv.sh'),
                          ['CC', 'CXX'])
 elif platform.system() == 'Windows':
     MAKE = env.get('MAKE', 'mozmake')
     os.environ['SOURCE'] = DIR.source
     if word_bits == 64:
         os.environ['USE_64BIT'] = '1'
     set_vars_from_script(posixpath.join(PDIR.scripts, 'winbuildenv.sh'),
--- a/js/src/devtools/automation/cgc-jittest-timeouts.txt
+++ b/js/src/devtools/automation/cgc-jittest-timeouts.txt
@@ -38,8 +38,10 @@ self-test/assertDeepEq.js
 sunspider/check-string-unpack-code.js
 v8-v5/check-earley-boyer.js
 v8-v5/check-raytrace.js
 v8-v5/check-regexp.js
 v8-v5/check-splay.js
 wasm/spec/f32.wast.js
 wasm/spec/f32_cmp.wast.js
 wasm/spec/f64.wast.js
+wasm/spec/f64_cmp.wast.js
+wasm/spec/float_exprs.wast.js
--- a/js/src/devtools/automation/cgc-jstests-slow.txt
+++ b/js/src/devtools/automation/cgc-jstests-slow.txt
@@ -54,8 +54,9 @@ js1_5/Regress/regress-312588.js
 js1_5/Regress/regress-321971.js
 js1_5/Regress/regress-360969-01.js
 js1_5/Regress/regress-360969-02.js
 js1_5/Regress/regress-360969-03.js
 js1_5/Regress/regress-360969-04.js
 js1_5/Regress/regress-360969-05.js
 js1_5/Regress/regress-360969-06.js
 js1_8_5/extensions/clone-complex-object.js
+js1_8_5/extensions/clone-object-deep.js
--- a/js/src/devtools/automation/macbuildenv.sh
+++ b/js/src/devtools/automation/macbuildenv.sh
@@ -5,23 +5,10 @@ mk_add_options() {
   : do nothing
 }
 ac_add_options() {
   : do nothing
 }
 
 topsrcdir="$SOURCE"
 
-if [ -n "$AUTOMATION" ]; then
-    # Download clang and some other things from tooltool server.
-    # This should be done before running mozconfig to make clang detection
-    # there work properly.
-    TT_SERVER=${TT_SERVER:-https://api.pub.build.mozilla.org/tooltool/}
-    ( cd $SOURCE/..; \
-      ./scripts/scripts/tooltool/tooltool_wrapper.sh \
-          $SOURCE/browser/config/tooltool-manifests/macosx64/releng.manifest \
-          $TT_SERVER \
-          setup.sh \
-          $TOOLTOOL_HOME/tooltool.py )
-fi
-
 # Setup CC and CXX variables
 . $topsrcdir/build/macosx/mozconfig.common
--- a/js/src/jit-test/tests/wasm/to-text-experimental.js
+++ b/js/src/jit-test/tests/wasm/to-text-experimental.js
@@ -1,11 +1,13 @@
 // |jit-test| test-also-wasm-baseline
 load(libdir + "wasm.js");
 
+assertErrorMessage(() => wasmBinaryToText(wasmTextToBinary(`(module (func (result i32) (f32.const 13.37)))`), 'experimental'), WebAssembly.CompileError, /type mismatch/);
+
 function runTest(code, expected) {
   var binary = wasmTextToBinary(code);
   var s = wasmBinaryToText(binary, "experimental");
   s = s.replace(/\s+/g, ' ');
   print("TEXT: " + s);
   assertEq(s, expected);
 }
 
--- a/js/src/jit-test/tests/wasm/to-text.js
+++ b/js/src/jit-test/tests/wasm/to-text.js
@@ -4,16 +4,18 @@ load(libdir + "wasm.js");
 var caught = false;
 try {
     wasmBinaryToText(new Int8Array(1));
 } catch (e) {
     caught = true;
 }
 assertEq(caught, true);
 
+assertErrorMessage(() => wasmBinaryToText(wasmTextToBinary(`(module (func (result i32) (f32.const 13.37)))`)), WebAssembly.CompileError, /type mismatch/);
+
 function runTest(code) {
   var expected = wasmTextToBinary(code);
   var s = wasmBinaryToText(expected);
   print("TEXT: " + s);
   var roundtrip = wasmTextToBinary(s);
   assertDeepEq(expected, roundtrip);
 }
 
--- a/js/src/jit/arm/Simulator-arm.cpp
+++ b/js/src/jit/arm/Simulator-arm.cpp
@@ -2682,27 +2682,25 @@ Simulator::softwareInterrupt(SimInstruct
         }
       }
     }
 }
 
 void
 Simulator::canonicalizeNaN(double* value)
 {
-    *value = !JitOptions.wasmTestMode && FPSCR_default_NaN_mode_
-             ? JS::CanonicalizeNaN(*value)
-             : *value;
+    if (!JitOptions.wasmTestMode && FPSCR_default_NaN_mode_)
+        *value = JS::CanonicalizeNaN(*value);
 }
 
 void
 Simulator::canonicalizeNaN(float* value)
 {
-    *value = !JitOptions.wasmTestMode && FPSCR_default_NaN_mode_
-             ? JS::CanonicalizeNaN(*value)
-             : *value;
+    if (!JitOptions.wasmTestMode && FPSCR_default_NaN_mode_)
+        *value = JS::CanonicalizeNaN(*value);
 }
 
 // Stop helper functions.
 bool
 Simulator::isStopInstruction(SimInstruction* instr)
 {
     return (instr->bits(27, 24) == 0xF) && (instr->svcValue() >= kStopCode);
 }
--- a/js/src/moz.build
+++ b/js/src/moz.build
@@ -479,17 +479,17 @@ elif CONFIG['JS_CODEGEN_ARM']:
         'jit/arm/SharedIC-arm.cpp',
         'jit/arm/Trampoline-arm.cpp',
     ]
     if CONFIG['JS_SIMULATOR_ARM']:
         UNIFIED_SOURCES += [
             'jit/arm/Simulator-arm.cpp'
         ]
         # Configuration used only for testing.
-        if CONFIG['OS_ARCH'] == 'Linux':
+        if CONFIG['OS_ARCH'] == 'Linux' or CONFIG['OS_ARCH'] == 'Darwin':
             CXXFLAGS += [ '-msse2', '-mfpmath=sse' ]
     elif CONFIG['OS_ARCH'] == 'Darwin':
         SOURCES += [
             'jit/arm/llvm-compiler-rt/arm/aeabi_idivmod.S',
             'jit/arm/llvm-compiler-rt/arm/aeabi_uidivmod.S',
         ]
 elif CONFIG['JS_CODEGEN_ARM64']:
     UNIFIED_SOURCES += [
new file mode 100644
--- /dev/null
+++ b/js/src/tests/js1_8_5/extensions/clone-object-deep.js
@@ -0,0 +1,25 @@
+// |reftest| skip-if(!xulRuntime.shell)
+// -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+// Any copyright is dedicated to the Public Domain.
+// http://creativecommons.org/licenses/publicdomain/
+
+function test() {
+    var check = clone_object_check;
+
+    // Invoke with the simple parameter to compile the function before doing
+    // deep clone, on --ion-eager case, to avoid timeout.
+    check({x: null, y: undefined});
+
+    // Try cloning a deep object. Don't fail with "too much recursion".
+    var b = {};
+    var current = b;
+    for (var i = 0; i < 10000; i++) {
+        var next = {};
+        current['x' + i] = next;
+        current = next;
+    }
+    check(b, "deepObject");  // takes 2 seconds :-\
+}
+
+test();
+reportCompare(0, 0, 'ok');
--- a/js/src/tests/js1_8_5/extensions/clone-object.js
+++ b/js/src/tests/js1_8_5/extensions/clone-object.js
@@ -1,111 +1,16 @@
 // |reftest| skip-if(!xulRuntime.shell)
 // -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 // Any copyright is dedicated to the Public Domain.
 // http://creativecommons.org/licenses/publicdomain/
 
-// Assert that cloning b does the right thing as far as we can tell.
-// Caveat: getters in b must produce the same value each time they're
-// called. We may call them several times.
-//
-// If desc is provided, then the very first thing we do to b is clone it.
-// (The self-modifying object test counts on this.)
-//
-function check(b, desc) {
-    function classOf(obj) {
-        return Object.prototype.toString.call(obj);
-    }
-
-    function ownProperties(obj) {
-        return Object.getOwnPropertyNames(obj).
-            map(function (p) { return [p, Object.getOwnPropertyDescriptor(obj, p)]; });
-    }
-
-    function isCloneable(pair) {
-        return typeof pair[0] === 'string' && pair[1].enumerable;
-    }
-
-    function notIndex(p) {
-        var u = p >>> 0;
-        return !("" + u == p && u != 0xffffffff);
-    }
-
-    function assertIsCloneOf(a, b, path) {
-        assertEq(a === b, false);
-
-        var ca = classOf(a);
-        assertEq(ca, classOf(b), path);
-
-        assertEq(Object.getPrototypeOf(a),
-                 ca == "[object Object]" ? Object.prototype : Array.prototype,
-                 path);
+function test() {
+    var check = clone_object_check;
 
-        // 'b', the original object, may have non-enumerable or XMLName
-        // properties; ignore them.  'a', the clone, should not have any
-        // non-enumerable properties (except .length, if it's an Array) or
-        // XMLName properties.
-        var pb = ownProperties(b).filter(isCloneable);
-        var pa = ownProperties(a);
-        for (var i = 0; i < pa.length; i++) {
-            assertEq(typeof pa[i][0], "string", "clone should not have E4X properties " + path);
-            if (!pa[i][1].enumerable) {
-                if (Array.isArray(a) && pa[i][0] == "length") {
-                    // remove it so that the comparisons below will work
-                    pa.splice(i, 1);
-                    i--;
-                } else {
-                    throw new Error("non-enumerable clone property " + uneval(pa[i][0]) + " " + path);
-                }
-            }
-        }
-
-        // Check that, apart from properties whose names are array indexes, 
-        // the enumerable properties appear in the same order.
-        var aNames = pa.map(function (pair) { return pair[1]; }).filter(notIndex);
-        var bNames = pa.map(function (pair) { return pair[1]; }).filter(notIndex);
-        assertEq(aNames.join(","), bNames.join(","), path);
-
-        // Check that the lists are the same when including array indexes.
-        function byName(a, b) { a = a[0]; b = b[0]; return a < b ? -1 : a === b ? 0 : 1; }
-        pa.sort(byName);
-        pb.sort(byName);
-        assertEq(pa.length, pb.length, "should see the same number of properties " + path);
-        for (var i = 0; i < pa.length; i++) {
-            var aName = pa[i][0];
-            var bName = pb[i][0];
-            assertEq(aName, bName, path);
-
-            var path2 = path + "." + aName;
-            var da = pa[i][1];
-            var db = pb[i][1];
-            assertEq(da.configurable, true, path2);
-            assertEq(da.writable, true, path2);
-            assertEq("value" in da, true, path2);
-            var va = da.value;
-            var vb = b[pb[i][0]];
-            if (typeof va === "object" && va !== null)
-                queue.push([va, vb, path2]);
-            else
-                assertEq(va, vb, path2);
-        }
-    }
-
-    var banner = "while testing clone of " + (desc || uneval(b));
-    var a = deserialize(serialize(b));
-    var queue = [[a, b, banner]];
-    while (queue.length) {
-        var triple = queue.shift();
-        assertIsCloneOf(triple[0], triple[1], triple[2]);
-    }
-
-    return a; // for further testing
-}
-
-function test() {
     check({});
     check([]);
     check({x: 0});
     check({x: 0.7, p: "forty-two", y: null, z: undefined});
     check(Array.prototype);
     check(Object.prototype);
 
     // before and after
@@ -170,26 +75,16 @@ function test() {
     b = {one: same, two: same};
     a = check(b);
     assertEq(a.one === a.two, true);
 
     b = [same, same];
     a = check(b);
     assertEq(a[0] === a[1], true);
 
-    // Try cloning a deep object. Don't fail with "too much recursion".
-    b = {};
-    var current = b;
-    for (var i = 0; i < 10000; i++) {
-        var next = {};
-        current['x' + i] = next;
-        current = next;
-    }
-    check(b, "deepObject");  // takes 2 seconds :-\
-
     /*
       XXX TODO spin this out into its own test
     // This fails quickly with an OOM error. An exception would be nicer.
     function Infinitree() {
         return { get left() { return new Infinitree; },
                  get right() { return new Infinitree; }};
     }
     var threw = false;
--- a/js/src/tests/js1_8_5/extensions/shell.js
+++ b/js/src/tests/js1_8_5/extensions/shell.js
@@ -11,8 +11,105 @@
 var workerDir = '';
 
 // explicitly turn on js185
 // XXX: The browser currently only supports up to version 1.8
 if (typeof version != 'undefined')
 {
   version(185);
 }
+
+// Assert that cloning b does the right thing as far as we can tell.
+// Caveat: getters in b must produce the same value each time they're
+// called. We may call them several times.
+//
+// If desc is provided, then the very first thing we do to b is clone it.
+// (The self-modifying object test counts on this.)
+//
+function clone_object_check(b, desc) {
+    function classOf(obj) {
+        return Object.prototype.toString.call(obj);
+    }
+
+    function ownProperties(obj) {
+        return Object.getOwnPropertyNames(obj).
+            map(function (p) { return [p, Object.getOwnPropertyDescriptor(obj, p)]; });
+    }
+
+    function isCloneable(pair) {
+        return typeof pair[0] === 'string' && pair[1].enumerable;
+    }
+
+    function notIndex(p) {
+        var u = p >>> 0;
+        return !("" + u == p && u != 0xffffffff);
+    }
+
+    function assertIsCloneOf(a, b, path) {
+        assertEq(a === b, false);
+
+        var ca = classOf(a);
+        assertEq(ca, classOf(b), path);
+
+        assertEq(Object.getPrototypeOf(a),
+                 ca == "[object Object]" ? Object.prototype : Array.prototype,
+                 path);
+
+        // 'b', the original object, may have non-enumerable or XMLName
+        // properties; ignore them.  'a', the clone, should not have any
+        // non-enumerable properties (except .length, if it's an Array) or
+        // XMLName properties.
+        var pb = ownProperties(b).filter(isCloneable);
+        var pa = ownProperties(a);
+        for (var i = 0; i < pa.length; i++) {
+            assertEq(typeof pa[i][0], "string", "clone should not have E4X properties " + path);
+            if (!pa[i][1].enumerable) {
+                if (Array.isArray(a) && pa[i][0] == "length") {
+                    // remove it so that the comparisons below will work
+                    pa.splice(i, 1);
+                    i--;
+                } else {
+                    throw new Error("non-enumerable clone property " + uneval(pa[i][0]) + " " + path);
+                }
+            }
+        }
+
+        // Check that, apart from properties whose names are array indexes, 
+        // the enumerable properties appear in the same order.
+        var aNames = pa.map(function (pair) { return pair[1]; }).filter(notIndex);
+        var bNames = pa.map(function (pair) { return pair[1]; }).filter(notIndex);
+        assertEq(aNames.join(","), bNames.join(","), path);
+
+        // Check that the lists are the same when including array indexes.
+        function byName(a, b) { a = a[0]; b = b[0]; return a < b ? -1 : a === b ? 0 : 1; }
+        pa.sort(byName);
+        pb.sort(byName);
+        assertEq(pa.length, pb.length, "should see the same number of properties " + path);
+        for (var i = 0; i < pa.length; i++) {
+            var aName = pa[i][0];
+            var bName = pb[i][0];
+            assertEq(aName, bName, path);
+
+            var path2 = path + "." + aName;
+            var da = pa[i][1];
+            var db = pb[i][1];
+            assertEq(da.configurable, true, path2);
+            assertEq(da.writable, true, path2);
+            assertEq("value" in da, true, path2);
+            var va = da.value;
+            var vb = b[pb[i][0]];
+            if (typeof va === "object" && va !== null)
+                queue.push([va, vb, path2]);
+            else
+                assertEq(va, vb, path2);
+        }
+    }
+
+    var banner = "while testing clone of " + (desc || uneval(b));
+    var a = deserialize(serialize(b));
+    var queue = [[a, b, banner]];
+    while (queue.length) {
+        var triple = queue.shift();
+        assertIsCloneOf(triple[0], triple[1], triple[2]);
+    }
+
+    return a; // for further testing
+}
--- a/layout/base/nsCSSRendering.cpp
+++ b/layout/base/nsCSSRendering.cpp
@@ -2578,18 +2578,18 @@ ClampColorStops(nsTArray<ColorStop>& aSt
                                            /* aPosition = */ 0,
                                            aStops[i].mColor);
       // Remove all of the preceding stops -- they are all negative.
       aStops.RemoveElementsAt(0, i - 1);
       break;
     }
   }
 
-  MOZ_ASSERT(aStops[0].mPosition >= 0);
-  MOZ_ASSERT(aStops.LastElement().mPosition <= 1);
+  MOZ_ASSERT(aStops[0].mPosition >= -1e6);
+  MOZ_ASSERT(aStops.LastElement().mPosition - 1 <= 1e6);
 
   // The end points won't exist yet if they don't fall in the original range of
   // |aStops|. Create them if needed.
   if (aStops[0].mPosition > 0) {
     aStops.InsertElementAt(0, ColorStop(0, false, aStops[0].mColor));
   }
   if (aStops.LastElement().mPosition < 1) {
     aStops.AppendElement(ColorStop(1, false, aStops.LastElement().mColor));
--- a/layout/base/nsDocumentViewer.cpp
+++ b/layout/base/nsDocumentViewer.cpp
@@ -37,27 +37,27 @@
 #include "nsLayoutStylesheetCache.h"
 #ifdef ACCESSIBILITY
 #include "mozilla/a11y/DocAccessible.h"
 #endif
 #include "mozilla/BasicEvents.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/WeakPtr.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 #include "nsViewManager.h"
 #include "nsView.h"
 
 #include "nsIPageSequenceFrame.h"
 #include "nsNetUtil.h"
 #include "nsIContentViewerEdit.h"
 #include "nsIContentViewerFile.h"
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/css/Loader.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsDocShell.h"
 #include "nsIBaseWindow.h"
 #include "nsILayoutHistoryState.h"
 #include "nsCharsetSource.h"
 #include "mozilla/ReflowInput.h"
@@ -2200,34 +2200,34 @@ nsDocumentViewer::CreateStyleSet(nsIDocu
 
     // Caller will handle calling EndUpdate, per contract.
     return styleSet;
   }
 
   auto cache = nsLayoutStylesheetCache::For(backendType);
 
   // Handle the user sheets.
-  StyleSheetHandle sheet = nullptr;
+  StyleSheet* sheet = nullptr;
   if (nsContentUtils::IsInChromeDocshell(aDocument)) {
     sheet = cache->UserChromeSheet();
   } else {
     sheet = cache->UserContentSheet();
   }
 
   if (sheet)
     styleSet->AppendStyleSheet(SheetType::User, sheet);
 
   // Append chrome sheets (scrollbars + forms).
   bool shouldOverride = false;
   // We don't want a docshell here for external resource docs, so just
   // look at mContainer.
   nsCOMPtr<nsIDocShell> ds(mContainer);
   nsCOMPtr<nsIDOMEventTarget> chromeHandler;
   nsCOMPtr<nsIURI> uri;
-  StyleSheetHandle::RefPtr chromeSheet;
+  RefPtr<StyleSheet> chromeSheet;
 
   if (ds) {
     ds->GetChromeEventHandler(getter_AddRefs(chromeHandler));
   }
   if (chromeHandler) {
     nsCOMPtr<nsIDOMElement> elt(do_QueryInterface(chromeHandler));
     nsCOMPtr<nsIContent> content(do_QueryInterface(elt));
     if (elt && content) {
@@ -2336,20 +2336,20 @@ nsDocumentViewer::CreateStyleSet(nsIDocu
     if (sheet) {
       styleSet->PrependStyleSheet(SheetType::Agent, sheet);
     }
   }
 
   if (styleSet->IsGecko()) {
     nsStyleSheetService* sheetService = nsStyleSheetService::GetInstance();
     if (sheetService) {
-      for (StyleSheetHandle sheet : *sheetService->AgentStyleSheets()) {
+      for (StyleSheet* sheet : *sheetService->AgentStyleSheets()) {
         styleSet->AppendStyleSheet(SheetType::Agent, sheet);
       }
-      for (StyleSheetHandle sheet : Reversed(*sheetService->UserStyleSheets())) {
+      for (StyleSheet* sheet : Reversed(*sheetService->UserStyleSheets())) {
         styleSet->PrependStyleSheet(SheetType::User, sheet);
       }
     }
   } else {
     NS_WARNING("stylo: Not yet checking nsStyleSheetService for Servo-backed "
                "documents. See bug 1290224");
   }
 
--- a/layout/base/nsIPresShell.h
+++ b/layout/base/nsIPresShell.h
@@ -20,17 +20,17 @@
 #ifndef nsIPresShell_h___
 #define nsIPresShell_h___
 
 #include "mozilla/ArenaObjectID.h"
 #include "mozilla/EventForwards.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/StaticPtr.h"
 #include "mozilla/StyleSetHandle.h"
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 #include "mozilla/WeakPtr.h"
 #include "gfxPoint.h"
 #include "nsTHashtable.h"
 #include "nsHashKeys.h"
 #include "nsISupports.h"
 #include "nsIContent.h"
 #include "nsISelectionController.h"
 #include "nsQueryFrame.h"
@@ -955,33 +955,33 @@ public:
    * Indicates whether theme support is enabled.
    */
   bool IsThemeSupportEnabled() const { return !mIsThemeSupportDisabled; }
 
   /**
    * Get the set of agent style sheets for this presentation
    */
   virtual nsresult GetAgentStyleSheets(
-      nsTArray<mozilla::StyleSheetHandle::RefPtr>& aSheets) = 0;
+      nsTArray<RefPtr<mozilla::StyleSheet>>& aSheets) = 0;
 
   /**
    * Replace the set of agent style sheets
    */
   virtual nsresult SetAgentStyleSheets(
-      const nsTArray<mozilla::StyleSheetHandle::RefPtr>& aSheets) = 0;
+      const nsTArray<RefPtr<mozilla::StyleSheet>>& aSheets) = 0;
 
   /**
    * Add an override style sheet for this presentation
    */
-  virtual nsresult AddOverrideStyleSheet(mozilla::StyleSheetHandle aSheet) = 0;
+  virtual nsresult AddOverrideStyleSheet(mozilla::StyleSheet* aSheet) = 0;
 
   /**
    * Remove an override style sheet
    */
-  virtual nsresult RemoveOverrideStyleSheet(mozilla::StyleSheetHandle aSheet) = 0;
+  virtual nsresult RemoveOverrideStyleSheet(mozilla::StyleSheet* aSheet) = 0;
 
   /**
    * Reconstruct frames for all elements in the document
    */
   virtual nsresult ReconstructFrames() = 0;
 
   /**
    * Notify that a content node's state has changed
--- a/layout/base/nsPresContext.cpp
+++ b/layout/base/nsPresContext.cpp
@@ -69,18 +69,18 @@
 #include "nsFrameLoader.h"
 #include "mozilla/dom/FontFaceSet.h"
 #include "nsContentUtils.h"
 #include "nsPIWindowRoot.h"
 #include "mozilla/Preferences.h"
 #include "gfxTextRun.h"
 #include "nsFontFaceUtils.h"
 #include "nsLayoutStylesheetCache.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 #if defined(MOZ_WIDGET_GTK)
 #include "gfxPlatformGtk.h" // xxx - for UseFcFontList
 #endif
 
 
 // Needed for Start/Stop of Image Animation
 #include "imgIContainer.h"
@@ -1151,17 +1151,17 @@ nsPresContext::CompatibilityModeChanged(
 
   bool needsQuirkSheet = CompatibilityMode() == eCompatibility_NavQuirks;
   if (mQuirkSheetAdded == needsQuirkSheet) {
     return;
   }
 
   StyleSetHandle styleSet = mShell->StyleSet();
   auto cache = nsLayoutStylesheetCache::For(styleSet->BackendType());
-  StyleSheetHandle sheet = cache->QuirkSheet();
+  StyleSheet* sheet = cache->QuirkSheet();
 
   if (needsQuirkSheet) {
     // quirk.css needs to come after html.css; we just keep it at the end.
     DebugOnly<nsresult> rv =
       styleSet->AppendStyleSheet(SheetType::Agent, sheet);
     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "failed to insert quirk.css");
   } else {
     DebugOnly<nsresult> rv =
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -16,17 +16,17 @@
  * 05/03/2000   IBM Corp.       Observer events for reflow states
  */
 
 /* a presentation of a document, part 2 */
 
 #include "mozilla/Logging.h"
 
 #include "mozilla/ArrayUtils.h"
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/EventDispatcher.h"
 #include "mozilla/EventStateManager.h"
 #include "mozilla/EventStates.h"
 #include "mozilla/IMEStateManager.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/dom/TabChild.h"
 #include "mozilla/Likely.h"
 #include "mozilla/MouseEvents.h"
@@ -188,18 +188,18 @@
 #include "nsSubDocumentFrame.h"
 #include "nsQueryObject.h"
 #include "nsLayoutStylesheetCache.h"
 #include "mozilla/layers/InputAPZContext.h"
 #include "mozilla/layers/ScrollInputMethods.h"
 #include "nsStyleSet.h"
 #include "mozilla/StyleSetHandle.h"
 #include "mozilla/StyleSetHandleInlines.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 
 #ifdef ANDROID
 #include "nsIDocShellTreeOwner.h"
 #endif
 
 #ifdef MOZ_B2G
 #include "nsIHardwareKeyHandler.h"
 #endif
@@ -1399,17 +1399,17 @@ PresShell::UpdatePreferenceStyles()
   // needs to recreate the pref style sheet, it has somewhere to get the
   // pref styling information from.  All pres contexts for
   // IsChromeOriginImage() == false will have the same pref styling information,
   // and similarly for IsChromeOriginImage() == true, so it doesn't really
   // matter which pres context we pass in when it does need to be recreated.
   // (See nsPresContext::GetDocumentColorPreferences for how whether we
   // are a chrome origin image affects some pref styling information.)
   auto cache = nsLayoutStylesheetCache::For(mStyleSet->BackendType());
-  StyleSheetHandle::RefPtr newPrefSheet =
+  RefPtr<StyleSheet> newPrefSheet =
     mPresContext->IsChromeOriginImage() ?
       cache->ChromePreferenceSheet(mPresContext) :
       cache->ContentPreferenceSheet(mPresContext);
 
   if (mPrefStyleSheet == newPrefSheet) {
     return;
   }
 
@@ -1446,26 +1446,26 @@ PresShell::AddUserSheet(nsISupports* aSh
   // for the ordering.  Just remove and readd all the nsStyleSheetService
   // sheets.
   nsCOMPtr<nsIStyleSheetService> dummy =
     do_GetService(NS_STYLESHEETSERVICE_CONTRACTID);
 
   mStyleSet->BeginUpdate();
 
   nsStyleSheetService* sheetService = nsStyleSheetService::gInstance;
-  nsTArray<StyleSheetHandle::RefPtr>& userSheets = *sheetService->UserStyleSheets();
+  nsTArray<RefPtr<StyleSheet>>& userSheets = *sheetService->UserStyleSheets();
   // Iterate forwards when removing so the searches for RemoveStyleSheet are as
   // short as possible.
-  for (StyleSheetHandle sheet : userSheets) {
+  for (StyleSheet* sheet : userSheets) {
     mStyleSet->RemoveStyleSheet(SheetType::User, sheet);
   }
 
   // Now iterate backwards, so that the order of userSheets will be the same as
   // the order of sheets from it in the style set.
-  for (StyleSheetHandle sheet : Reversed(userSheets)) {
+  for (StyleSheet* sheet : Reversed(userSheets)) {
     mStyleSet->PrependStyleSheet(SheetType::User, sheet);
   }
 
   mStyleSet->EndUpdate();
 
   RestyleForCSSRuleChanges();
 }
 
@@ -1492,17 +1492,17 @@ PresShell::AddAuthorSheet(nsISupports* a
   RefPtr<CSSStyleSheet> sheet = do_QueryObject(aSheet);
   if (!sheet) {
     NS_ERROR("stylo: AddAuthorSheet needs to support ServoStyleSheets");
     return;
   }
 
   // Document specific "additional" Author sheets should be stronger than the
   // ones added with the StyleSheetService.
-  StyleSheetHandle firstAuthorSheet =
+  StyleSheet* firstAuthorSheet =
     mDocument->GetFirstAdditionalAuthorSheet();
   if (firstAuthorSheet) {
     mStyleSet->InsertStyleSheetBefore(SheetType::Doc, sheet, firstAuthorSheet);
   } else {
     mStyleSet->AppendStyleSheet(SheetType::Doc, sheet);
   }
 
   RestyleForCSSRuleChanges();
@@ -4525,17 +4525,17 @@ nsIPresShell::RestyleForCSSRuleChanges()
     for (Element* scopeRoot : scopeRoots) {
       restyleManager->PostRestyleEvent(scopeRoot, eRestyle_Subtree,
                                        nsChangeHint(0));
     }
   }
 }
 
 void
-PresShell::RecordStyleSheetChange(StyleSheetHandle aStyleSheet)
+PresShell::RecordStyleSheetChange(StyleSheet* aStyleSheet)
 {
   // too bad we can't check that the update is UPDATE_STYLE
   NS_ASSERTION(mUpdateCount != 0, "must be in an update");
 
   if (mStylesHaveChanged)
     return;
 
   if (aStyleSheet->IsGecko()) {
@@ -4549,61 +4549,61 @@ PresShell::RecordStyleSheetChange(StyleS
     NS_WARNING("stylo: ServoStyleSheets don't support <style scoped>");
     return;
   }
 
   mStylesHaveChanged = true;
 }
 
 void
-PresShell::StyleSheetAdded(StyleSheetHandle aStyleSheet,
+PresShell::StyleSheetAdded(StyleSheet* aStyleSheet,
                            bool aDocumentSheet)
 {
   // We only care when enabled sheets are added
   NS_PRECONDITION(aStyleSheet, "Must have a style sheet!");
 
   if (aStyleSheet->IsApplicable() && aStyleSheet->HasRules()) {
     RecordStyleSheetChange(aStyleSheet);
   }
 }
 
 void
-PresShell::StyleSheetRemoved(StyleSheetHandle aStyleSheet,
+PresShell::StyleSheetRemoved(StyleSheet* aStyleSheet,
                              bool aDocumentSheet)
 {
   // We only care when enabled sheets are removed
   NS_PRECONDITION(aStyleSheet, "Must have a style sheet!");
 
   if (aStyleSheet->IsApplicable() && aStyleSheet->HasRules()) {
     RecordStyleSheetChange(aStyleSheet);
   }
 }
 
 void
-PresShell::StyleSheetApplicableStateChanged(StyleSheetHandle aStyleSheet)
+PresShell::StyleSheetApplicableStateChanged(StyleSheet* aStyleSheet)
 {
   if (aStyleSheet->HasRules()) {
     RecordStyleSheetChange(aStyleSheet);
   }
 }
 
 void
-PresShell::StyleRuleChanged(StyleSheetHandle aStyleSheet)
+PresShell::StyleRuleChanged(StyleSheet* aStyleSheet)
 {
   RecordStyleSheetChange(aStyleSheet);
 }
 
 void
-PresShell::StyleRuleAdded(StyleSheetHandle aStyleSheet)
+PresShell::StyleRuleAdded(StyleSheet* aStyleSheet)
 {
   RecordStyleSheetChange(aStyleSheet);
 }
 
 void
-PresShell::StyleRuleRemoved(StyleSheetHandle aStyleSheet)
+PresShell::StyleRuleRemoved(StyleSheet* aStyleSheet)
 {
   RecordStyleSheetChange(aStyleSheet);
 }
 
 nsIFrame*
 PresShell::GetPlaceholderFrameFor(nsIFrame* aFrame) const
 {
   return mFrameConstructor->GetPlaceholderFrameFor(aFrame);
@@ -8937,47 +8937,47 @@ PresShell::IsVisible()
   nsIFrame* frame = view->GetFrame();
   if (!frame)
     return true;
 
   return frame->IsVisibleConsideringAncestors(nsIFrame::VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY);
 }
 
 nsresult
-PresShell::GetAgentStyleSheets(nsTArray<StyleSheetHandle::RefPtr>& aSheets)
+PresShell::GetAgentStyleSheets(nsTArray<RefPtr<StyleSheet>>& aSheets)
 {
   aSheets.Clear();
   int32_t sheetCount = mStyleSet->SheetCount(SheetType::Agent);
 
   if (!aSheets.SetCapacity(sheetCount, fallible)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   for (int32_t i = 0; i < sheetCount; ++i) {
-    StyleSheetHandle sheet = mStyleSet->StyleSheetAt(SheetType::Agent, i);
+    StyleSheet* sheet = mStyleSet->StyleSheetAt(SheetType::Agent, i);
     aSheets.AppendElement(sheet);
   }
 
   return NS_OK;
 }
 
 nsresult
-PresShell::SetAgentStyleSheets(const nsTArray<StyleSheetHandle::RefPtr>& aSheets)
+PresShell::SetAgentStyleSheets(const nsTArray<RefPtr<StyleSheet>>& aSheets)
 {
   return mStyleSet->ReplaceSheets(SheetType::Agent, aSheets);
 }
 
 nsresult
-PresShell::AddOverrideStyleSheet(StyleSheetHandle aSheet)
+PresShell::AddOverrideStyleSheet(StyleSheet* aSheet)
 {
   return mStyleSet->PrependStyleSheet(SheetType::Override, aSheet);
 }
 
 nsresult
-PresShell::RemoveOverrideStyleSheet(StyleSheetHandle aSheet)
+PresShell::RemoveOverrideStyleSheet(StyleSheet* aSheet)
 {
   return mStyleSet->RemoveStyleSheet(SheetType::Override, aSheet);
 }
 
 static void
 FreezeElement(nsISupports *aSupports, void * /* unused */)
 {
   nsCOMPtr<nsIObjectLoadingContent> olc(do_QueryInterface(aSupports));
--- a/layout/base/nsPresShell.h
+++ b/layout/base/nsPresShell.h
@@ -177,22 +177,22 @@ public:
   virtual void SetIgnoreFrameDestruction(bool aIgnore) override;
   virtual void NotifyDestroyingFrame(nsIFrame* aFrame) override;
 
   virtual nsresult CaptureHistoryState(nsILayoutHistoryState** aLayoutHistoryState) override;
 
   virtual void UnsuppressPainting() override;
 
   virtual nsresult GetAgentStyleSheets(
-      nsTArray<mozilla::StyleSheetHandle::RefPtr>& aSheets) override;
+      nsTArray<RefPtr<mozilla::StyleSheet>>& aSheets) override;
   virtual nsresult SetAgentStyleSheets(
-      const nsTArray<mozilla::StyleSheetHandle::RefPtr>& aSheets) override;
+      const nsTArray<RefPtr<mozilla::StyleSheet>>& aSheets) override;
 
-  virtual nsresult AddOverrideStyleSheet(mozilla::StyleSheetHandle aSheet) override;
-  virtual nsresult RemoveOverrideStyleSheet(mozilla::StyleSheetHandle aSheet) override;
+  virtual nsresult AddOverrideStyleSheet(mozilla::StyleSheet* aSheet) override;
+  virtual nsresult RemoveOverrideStyleSheet(mozilla::StyleSheet* aSheet) override;
 
   virtual nsresult HandleEventWithTarget(
                                  mozilla::WidgetEvent* aEvent,
                                  nsIFrame* aFrame,
                                  nsIContent* aContent,
                                  nsEventStatus* aStatus) override;
   virtual nsIFrame* GetEventTargetFrame() override;
   virtual already_AddRefed<nsIContent> GetEventTargetContent(
@@ -536,17 +536,17 @@ protected:
 
 #ifdef DEBUG
   nsStyleSet* CloneStyleSet(nsStyleSet* aSet);
   bool VerifyIncrementalReflow();
   bool mInVerifyReflow;
   void ShowEventTargetDebug();
 #endif
 
-  void RecordStyleSheetChange(mozilla::StyleSheetHandle aStyleSheet);
+  void RecordStyleSheetChange(mozilla::StyleSheet* aStyleSheet);
 
   void RemovePreferenceStyles();
 
   // methods for painting a range to an offscreen buffer
 
   // given a display list, clip the items within the list to
   // the range
   nsRect ClipListToRange(nsDisplayListBuilder *aBuilder,
@@ -857,17 +857,17 @@ protected:
   // reason.
   nsPoint                   mMouseLocation;
   // This is an APZ state variable that tracks the target guid for the last
   // mouse event that was processed (corresponding to mMouseLocation). This is
   // needed for the synthetic mouse events.
   mozilla::layers::ScrollableLayerGuid mMouseEventTargetGuid;
 
   // mStyleSet owns it but we maintain a ref, may be null
-  mozilla::StyleSheetHandle::RefPtr mPrefStyleSheet;
+  RefPtr<mozilla::StyleSheet> mPrefStyleSheet;
 
   // Set of frames that we should mark with NS_FRAME_HAS_DIRTY_CHILDREN after
   // we finish reflowing mCurrentReflowRoot.
   nsTHashtable<nsPtrHashKey<nsIFrame> > mFramesToDirty;
 
   // Reflow roots that need to be reflowed.
   nsTArray<nsIFrame*>       mDirtyRoots;
 
--- a/layout/base/nsStyleSheetService.cpp
+++ b/layout/base/nsStyleSheetService.cpp
@@ -4,18 +4,18 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* implementation of interface for managing user and user-agent style sheets */
 
 #include "nsStyleSheetService.h"
 #include "mozilla/CSSStyleSheet.h"
 #include "mozilla/MemoryReporting.h"
-#include "mozilla/StyleSheetHandle.h"
-#include "mozilla/StyleSheetHandleInlines.h"
+#include "mozilla/StyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/Unused.h"
 #include "mozilla/css/Loader.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/ipc/URIUtils.h"
 #include "nsIURI.h"
 #include "nsCOMPtr.h"
 #include "nsICategoryManager.h"
 #include "nsISupportsPrimitives.h"
@@ -76,17 +76,17 @@ nsStyleSheetService::RegisterFromEnumera
     nsCOMPtr<nsIURI> uri;
     NS_NewURI(getter_AddRefs(uri), spec);
     if (uri)
       LoadAndRegisterSheetInternal(uri, aSheetType);
   }
 }
 
 int32_t
-nsStyleSheetService::FindSheetByURI(const nsTArray<StyleSheetHandle::RefPtr>& aSheets,
+nsStyleSheetService::FindSheetByURI(const nsTArray<RefPtr<StyleSheet>>& aSheets,
                                     nsIURI* aSheetURI)
 {
   for (int32_t i = aSheets.Length() - 1; i >= 0; i-- ) {
     bool bEqual;
     nsIURI* uri = aSheets[i]->GetSheetURI();
     if (uri
         && NS_SUCCEEDED(uri->Equals(aSheetURI, &bEqual))
         && bEqual) {
@@ -153,17 +153,17 @@ nsStyleSheetService::LoadAndRegisterShee
     }
     nsCOMPtr<nsIObserverService> serv = services::GetObserverService();
     if (serv) {
       // We're guaranteed that the new sheet is the last sheet in
       // mSheets[aSheetType]
 
       // XXXheycam Once the nsStyleSheetService can hold ServoStyleSheets too,
       // we'll need to include them in the notification.
-      StyleSheetHandle sheet = mSheets[aSheetType].LastElement();
+      StyleSheet* sheet = mSheets[aSheetType].LastElement();
       if (sheet->IsGecko()) {
         CSSStyleSheet* cssSheet = sheet->AsGecko();
         serv->NotifyObservers(NS_ISUPPORTS_CAST(nsIDOMCSSStyleSheet*, cssSheet),
                               message, nullptr);
       } else {
         NS_ERROR("stylo: can't notify observers of ServoStyleSheets");
       }
     }
@@ -211,17 +211,17 @@ nsStyleSheetService::LoadAndRegisterShee
       NS_WARNING("invalid sheet type argument");
       return NS_ERROR_INVALID_ARG;
   }
 
   // XXXheycam We'll need to load and register both a Gecko- and Servo-backed
   // style sheet.
   RefPtr<css::Loader> loader = new css::Loader(StyleBackendType::Gecko);
 
-  StyleSheetHandle::RefPtr sheet;
+  RefPtr<StyleSheet> sheet;
   nsresult rv = loader->LoadSheetSync(aSheetURI, parsingMode, true, &sheet);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mSheets[aSheetType].AppendElement(sheet);
 
   return rv;
 }
 
@@ -265,17 +265,17 @@ nsStyleSheetService::PreloadSheet(nsIURI
       return NS_ERROR_INVALID_ARG;
   }
 
   // XXXheycam PreloadSheet can't support ServoStyleSheets until they implement
   // nsIDOMStyleSheet.
 
   RefPtr<css::Loader> loader = new css::Loader(StyleBackendType::Gecko);
 
-  StyleSheetHandle::RefPtr sheet;
+  RefPtr<StyleSheet> sheet;
   nsresult rv = loader->LoadSheetSync(aSheetURI, parsingMode, true, &sheet);
   NS_ENSURE_SUCCESS(rv, rv);
 
   MOZ_ASSERT(sheet->IsGecko(),
              "stylo: didn't expect Loader to create a ServoStyleSheet");
 
   RefPtr<CSSStyleSheet> cssSheet = sheet->AsGecko();
   cssSheet.forget(aSheet);
@@ -288,17 +288,17 @@ nsStyleSheetService::UnregisterSheet(nsI
 {
   NS_ENSURE_ARG(aSheetType == AGENT_SHEET ||
                 aSheetType == USER_SHEET ||
                 aSheetType == AUTHOR_SHEET);
   NS_ENSURE_ARG_POINTER(aSheetURI);
 
   int32_t foundIndex = FindSheetByURI(mSheets[aSheetType], aSheetURI);
   NS_ENSURE_TRUE(foundIndex >= 0, NS_ERROR_INVALID_ARG);
-  StyleSheetHandle::RefPtr sheet = mSheets[aSheetType][foundIndex];
+  RefPtr<StyleSheet> sheet = mSheets[aSheetType][foundIndex];
   mSheets[aSheetType].RemoveElementAt(foundIndex);
 
   const char* message;
   switch (aSheetType) {
     case AGENT_SHEET:
       message = "agent-sheet-removed";
       break;
     case USER_SHEET:
@@ -371,14 +371,14 @@ nsStyleSheetService::CollectReports(nsIH
 }
 
 size_t
 nsStyleSheetService::SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const
 {
   size_t n = aMallocSizeOf(this);
   for (auto& sheetArray : mSheets) {
     n += sheetArray.ShallowSizeOfExcludingThis(aMallocSizeOf);
-    for (StyleSheetHandle sheet : sheetArray) {
+    for (StyleSheet* sheet : sheetArray) {
       n += sheet->SizeOfIncludingThis(aMallocSizeOf);
     }
   }
   return n;
 }
--- a/layout/base/nsStyleSheetService.h
+++ b/layout/base/nsStyleSheetService.h
@@ -10,17 +10,17 @@
 #define nsStyleSheetService_h_
 
 #include "nsCOMArray.h"
 #include "nsCOMPtr.h"
 #include "nsIMemoryReporter.h"
 #include "nsIStyleSheetService.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/MemoryReporting.h"
-#include "mozilla/StyleSheetHandle.h"
+#include "mozilla/StyleSheet.h"
 
 class nsICategoryManager;
 class nsIMemoryReporter;
 class nsISimpleEnumerator;
 
 #define NS_STYLESHEETSERVICE_CID \
 { 0x3b55e72e, 0xab7e, 0x431b, \
   { 0x89, 0xc0, 0x3b, 0x06, 0xa8, 0xb1, 0x40, 0x16 } }
@@ -36,25 +36,25 @@ class nsStyleSheetService final
   nsStyleSheetService();
 
   NS_DECL_ISUPPORTS
   NS_DECL_NSISTYLESHEETSERVICE
   NS_DECL_NSIMEMORYREPORTER
 
   nsresult Init();
 
-  nsTArray<mozilla::StyleSheetHandle::RefPtr>* AgentStyleSheets()
+  nsTArray<RefPtr<mozilla::StyleSheet>>* AgentStyleSheets()
   {
     return &mSheets[AGENT_SHEET];
   }
-  nsTArray<mozilla::StyleSheetHandle::RefPtr>* UserStyleSheets()
+  nsTArray<RefPtr<mozilla::StyleSheet>>* UserStyleSheets()
   {
     return &mSheets[USER_SHEET];
   }
-  nsTArray<mozilla::StyleSheetHandle::RefPtr>* AuthorStyleSheets()
+  nsTArray<RefPtr<mozilla::StyleSheet>>* AuthorStyleSheets()
   {
     return &mSheets[AUTHOR_SHEET];
   }
 
   size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
 
   static nsStyleSheetService *GetInstance();
   static nsStyleSheetService *gInstance;
@@ -62,20 +62,20 @@ class nsStyleSheetService final
  private:
   ~nsStyleSheetService();
 
   void RegisterFromEnumerator(nsICategoryManager  *aManager,
                                           const char          *aCategory,
                                           nsISimpleEnumerator *aEnumerator,
                                           uint32_t             aSheetType);
 
-  int32_t FindSheetByURI(const nsTArray<mozilla::StyleSheetHandle::RefPtr>& aSheets,
+  int32_t FindSheetByURI(const nsTArray<RefPtr<mozilla::StyleSheet>>& aSheets,
                          nsIURI* aSheetURI);
 
   // Like LoadAndRegisterSheet, but doesn't notify.  If successful, the
   // new sheet will be the last sheet in mSheets[aSheetType].
   nsresult LoadAndRegisterSheetInternal(nsIURI *aSheetURI,
                                         uint32_t aSheetType);
 
-  nsTArray<mozilla::StyleSheetHandle::RefPtr> mSheets[3];
+  nsTArray<RefPtr<mozilla::StyleSheet>> mSheets[3];
 };
 
 #endif
--- a/layout/inspector/inCSSValueSearch.cpp
+++ b/layout/inspector/inCSSValueSearch.cpp
@@ -1,15 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "inCSSValueSearch.h"
 
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/dom/StyleSheetList.h"
 #include "nsIComponentManager.h"
 #include "nsIServiceManager.h"
 #include "nsReadableUtils.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMStyleSheetList.h"
 #include "nsIDOMCSSStyleSheet.h"
 #include "nsIDOMCSSRuleList.h"
--- a/layout/inspector/inDOMUtils.cpp
+++ b/layout/inspector/inDOMUtils.cpp
@@ -30,17 +30,17 @@
 #include "nsIMutableArray.h"
 #include "nsBindingManager.h"
 #include "ChildIterator.h"
 #include "nsComputedDOMStyle.h"
 #include "mozilla/EventStateManager.h"
 #include "nsIAtom.h"
 #include "nsRange.h"
 #include "nsContentList.h"
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "mozilla/dom/Element.h"
 #include "nsRuleWalker.h"
 #include "nsRuleProcessorData.h"
 #include "nsCSSPseudoClasses.h"
 #include "nsCSSRuleProcessor.h"
 #include "mozilla/dom/CSSLexer.h"
 #include "mozilla/dom/InspectorUtilsBinding.h"
 #include "mozilla/dom/ToJSValue.h"
--- a/layout/style/CSSRuleList.h
+++ b/layout/style/CSSRuleList.h
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_CSSRuleList_h
 #define mozilla_dom_CSSRuleList_h
 
-#include "mozilla/CSSStyleSheet.h"
+#include "mozilla/StyleSheetInlines.h"
 #include "nsIDOMCSSRule.h"
 #include "nsIDOMCSSRuleList.h"
 #include "nsWrapperCache.h"
 
 namespace mozilla {
 namespace dom {
 
 // IID for the CSSRuleList interface
--- a/layout/style/CSSStyleSheet.cpp
+++ b/layout/style/CSSStyleSheet.cpp
@@ -1319,43 +1319,16 @@ CSSStyleSheet::AddStyleSet(nsStyleSet* a
 void
 CSSStyleSheet::DropStyleSet(nsStyleSet* aStyleSet)
 {
   DebugOnly<bool> found = mStyleSets.RemoveElement(aStyleSet);
   NS_ASSERTION(found, "didn't find style set");
 }
 
 void
-CSSStyleSheet::SetURIs(nsIURI* aSheetURI, nsIURI* aOriginalSheetURI,
-                       nsIURI* aBaseURI)
-{
-  NS_ASSERTION(mInner->mOrderedRules.Count() == 0 && !mInner->mComplete,
-               "Can't call SetURIs on sheets that are complete or have rules");
-  mInner->SetURIs(aSheetURI, aOriginalSheetURI, aBaseURI);
-}
-
-void
-CSSStyleSheet::SetPrincipal(nsIPrincipal* aPrincipal)
-{
-  mInner->SetPrincipal(aPrincipal);
-}
-
-nsIURI*
-CSSStyleSheet::GetSheetURI() const
-{
-  return mInner->mSheetURI;
-}
-
-nsIURI*
-CSSStyleSheet::GetBaseURI() const
-{
-  return mInner->mBaseURI;
-}
-
-void
 CSSStyleSheet::GetType(nsString& aType) const
 {
   aType.AssignLiteral("text/css");
 }
 
 bool
 CSSStyleSheet::UseForPresentation(nsPresContext* aPresContext,
                                   nsMediaQueryResultCacheKey& aKey) const
@@ -1374,22 +1347,16 @@ CSSStyleSheet::SetMedia(nsMediaList* aMe
 }
 
 bool
 CSSStyleSheet::HasRules() const
 {
   return StyleRuleCount() != 0;
 }
 
-bool
-CSSStyleSheet::IsApplicable() const
-{
-  return !mDisabled && mInner->mComplete;
-}
-
 void
 CSSStyleSheet::SetEnabled(bool aEnabled)
 {
   // Internal method, so callers must handle BeginUpdate/EndUpdate
   bool oldDisabled = mDisabled;
   mDisabled = !aEnabled;
 
   if (mInner->mComplete && oldDisabled != mDisabled) {
@@ -1402,22 +1369,16 @@ CSSStyleSheet::SetEnabled(bool aEnabled)
 }
 
 CSSStyleSheet*
 CSSStyleSheet::GetParentSheet() const
 {
   return mParent;
 }
 
-nsIDocument*
-CSSStyleSheet::GetOwningDocument() const
-{
-  return mDocument;
-}
-
 void
 CSSStyleSheet::SetOwningDocument(nsIDocument* aDocument)
 { // not ref counted
   mDocument = aDocument;
   // Now set the same document on all our child sheets....
   // XXXbz this is a little bogus; see the XXX comment where we
   // declare mFirstChild.
   for (CSSStyleSheet* child = mInner->mFirstChild;
@@ -2120,17 +2081,17 @@ CSSStyleSheet::InsertRuleIntoGroup(const
   }
 
   *_retval = aIndex;
   return NS_OK;
 }
 
 // nsICSSLoaderObserver implementation
 NS_IMETHODIMP
-CSSStyleSheet::StyleSheetLoaded(StyleSheetHandle aSheet,
+CSSStyleSheet::StyleSheetLoaded(StyleSheet* aSheet,
                                 bool aWasAlternate,
                                 nsresult aStatus)
 {
   MOZ_ASSERT(aSheet->IsGecko(),
              "why we were called back with a ServoStyleSheet?");
 
   CSSStyleSheet* sheet = aSheet->AsGecko();
 
--- a/layout/style/CSSStyleSheet.h
+++ b/layout/style/CSSStyleSheet.h
@@ -120,44 +120,33 @@ public:
                 const dom::SRIMetadata& aIntegrity);
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(CSSStyleSheet,
                                                          nsIDOMCSSStyleSheet)
 
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_CSS_STYLE_SHEET_IMPL_CID)
 
-  nsIURI* GetSheetURI() const;
-  nsIURI* GetBaseURI() const;
   void GetTitle(nsString& aTitle) const;
   void GetType(nsString& aType) const;
   bool HasRules() const;
 
   /**
-   * Whether the sheet is applicable.  A sheet that is not applicable
-   * should never be inserted into a style set.  A sheet may not be
-   * applicable for a variety of reasons including being disabled and
-   * being incomplete.
-   */
-  bool IsApplicable() const;
-
-  /**
    * Set the stylesheet to be enabled.  This may or may not make it
    * applicable.  Note that this WILL inform the sheet's document of
    * its new applicable state if the state changes but WILL NOT call
    * BeginUpdate() or EndUpdate() on the document -- calling those is
    * the caller's responsibility.  This allows use of SetEnabled when
    * batched updates are desired.  If you want updates handled for
    * you, see nsIDOMStyleSheet::SetDisabled().
    */
   void SetEnabled(bool aEnabled);
 
   // style sheet owner info
   CSSStyleSheet* GetParentSheet() const;  // may be null
-  nsIDocument* GetOwningDocument() const;  // may be null
   void SetOwningDocument(nsIDocument* aDocument);
 
   // Find the ID of the owner inner window.
   uint64_t FindOwningWindowInnerID() const;
 #ifdef DEBUG
   void List(FILE* out = stdout, int32_t aIndent = 0) const;
 #endif
 
@@ -167,33 +156,16 @@ public:
   void AppendStyleRule(css::Rule* aRule);
 
   int32_t StyleRuleCount() const;
   css::Rule* GetStyleRuleAt(int32_t aIndex) const;
 
   nsresult DeleteRuleFromGroup(css::GroupRule* aGroup, uint32_t aIndex);
   nsresult InsertRuleIntoGroup(const nsAString& aRule, css::GroupRule* aGroup, uint32_t aIndex, uint32_t* _retval);
 
-  /**
-   * SetURIs must be called on all sheets before parsing into them.