Bug 1611415 - Prefer using std::move over forget. r=froydnj
authorSimon Giesecke <sgiesecke@mozilla.com>
Thu, 13 Feb 2020 14:38:48 +0000
changeset 513762 49adcf9a70abc9df4f11a123d181aa7213a20615
parent 513761 987a7f91bc32e15bd27798e17d05ba9bc66eae90
child 513763 1ba10e349c0aa817125ce26f993272cac21cbe45
push id37120
push usercbrindusan@mozilla.com
push dateThu, 13 Feb 2020 18:21:33 +0000
treeherdermozilla-central@b47e32ff95b8 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersfroydnj
bugs1611415
milestone75.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1611415 - Prefer using std::move over forget. r=froydnj Differential Revision: https://phabricator.services.mozilla.com/D60980
accessible/base/nsAccessiblePivot.cpp
docshell/base/BrowsingContext.cpp
docshell/base/CanonicalBrowsingContext.cpp
docshell/base/WindowContext.cpp
docshell/base/nsDefaultURIFixup.cpp
docshell/base/nsDocShellEditorData.cpp
docshell/shistory/MaybeNewPSHEntry.cpp
docshell/shistory/SHistoryParent.cpp
docshell/shistory/nsSHistory.cpp
dom/animation/Animation.cpp
dom/base/BodyConsumer.cpp
dom/base/BodyStream.cpp
dom/base/ChromeUtils.cpp
dom/base/Document.cpp
dom/base/IdleRequest.cpp
dom/base/ImageEncoder.cpp
dom/base/PostMessageEvent.cpp
dom/base/ResizeObserver.cpp
dom/base/ResizeObserver.h
dom/base/SelectionChangeEventDispatcher.cpp
dom/base/WindowNamedPropertiesHandler.cpp
dom/base/WindowProxyHolder.h
dom/base/nsContentSink.cpp
dom/base/nsDOMMutationObserver.cpp
dom/base/nsDOMMutationObserver.h
dom/base/nsDOMNavigationTiming.cpp
dom/base/nsFocusManager.cpp
dom/base/nsGlobalWindowInner.cpp
dom/base/nsGlobalWindowOuter.cpp
dom/base/nsINode.cpp
dom/bindings/BindingUtils.cpp
dom/cache/CacheStreamControlChild.cpp
dom/canvas/CanvasRenderingContext2D.cpp
dom/canvas/CanvasRenderingContextHelper.cpp
dom/clients/manager/ClientHandle.cpp
dom/clients/manager/ClientManager.cpp
dom/clients/manager/ClientManagerService.cpp
dom/clients/manager/ClientNavigateOpChild.cpp
dom/clients/manager/ClientOpenWindowUtils.cpp
dom/clients/manager/ClientSource.cpp
dom/clients/manager/ClientSourceParent.cpp
dom/events/AsyncEventDispatcher.cpp
dom/events/EventListenerManager.h
dom/events/EventStateManager.cpp
dom/events/IMEContentObserver.cpp
dom/fetch/FetchDriver.cpp
dom/fetch/FetchStreamReader.cpp
dom/fetch/FetchUtil.cpp
dom/file/StreamBlobImpl.cpp
dom/filehandle/ActorsParent.cpp
dom/html/HTMLFormElement.cpp
dom/html/HTMLMediaElement.cpp
dom/html/HTMLSlotElement.cpp
dom/html/nsHTMLDocument.cpp
dom/indexedDB/ActorsParent.cpp
dom/ipc/BrowserBridgeParent.cpp
dom/ipc/BrowserChild.cpp
dom/ipc/CSPMessageUtils.cpp
dom/ipc/ClonedErrorHolder.cpp
dom/ipc/PermissionMessageUtils.h
dom/ipc/PropertyBagUtils.cpp
dom/ipc/ReferrerInfoUtils.cpp
dom/localstorage/ActorsParent.cpp
dom/media/AudioSegment.h
dom/media/CanvasCaptureMediaStream.cpp
dom/media/CanvasCaptureMediaStream.h
dom/media/MediaCache.cpp
dom/media/MediaDecoderStateMachine.cpp
dom/media/MediaFormatReader.cpp
dom/media/MediaRecorder.cpp
dom/media/MediaShutdownManager.cpp
dom/media/VideoSegment.cpp
dom/media/VideoUtils.h
dom/media/gmp/CDMStorageIdProvider.cpp
dom/media/gmp/GMPService.cpp
dom/media/gmp/GMPServiceParent.cpp
dom/media/ipc/RemoteMediaDataDecoder.cpp
dom/media/platforms/AllocationPolicy.cpp
dom/media/platforms/PDMFactory.cpp
dom/media/platforms/agnostic/eme/EMEDecoderModule.cpp
dom/media/platforms/wrappers/MediaChangeMonitor.cpp
dom/media/webaudio/AudioBlock.cpp
dom/media/webaudio/AudioBuffer.cpp
dom/media/webaudio/AudioNode.cpp
dom/media/webaudio/MediaBufferDecoder.cpp
dom/media/webm/NesteggPacketHolder.h
dom/media/webm/WebMDemuxer.h
dom/midi/MIDIAccessManager.cpp
dom/notification/Notification.cpp
dom/payments/PaymentRequestData.cpp
dom/presentation/PresentationSessionInfo.cpp
dom/promise/Promise.cpp
dom/push/PushManager.cpp
dom/push/PushSubscription.cpp
dom/script/ScriptLoader.cpp
dom/security/DOMSecurityManager.cpp
dom/security/featurepolicy/FeaturePolicyUtils.cpp
dom/serviceworkers/ServiceWorkerContainer.cpp
dom/serviceworkers/ServiceWorkerManager.cpp
dom/serviceworkers/ServiceWorkerPrivate.cpp
dom/serviceworkers/ServiceWorkerRegistration.cpp
dom/serviceworkers/ServiceWorkerRegistrationImpl.cpp
dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp
dom/serviceworkers/ServiceWorkerRegistrationProxy.cpp
dom/storage/SessionStorageManager.cpp
dom/system/OSFileConstants.cpp
dom/webauthn/WebAuthnManagerBase.cpp
dom/webbrowserpersist/nsWebBrowserPersist.cpp
dom/workers/RuntimeService.cpp
dom/workers/ScriptLoader.cpp
dom/workers/WorkerEventTarget.cpp
dom/workers/WorkerPrivate.cpp
dom/workers/WorkerRunnable.cpp
dom/workers/WorkerRunnable.h
dom/workers/WorkerScope.cpp
dom/worklet/WorkletThread.cpp
dom/xhr/XMLHttpRequestWorker.cpp
dom/xslt/xslt/txExecutionState.cpp
dom/xslt/xslt/txMozillaTextOutput.cpp
dom/xul/nsXULElement.cpp
editor/libeditor/EditorBase.cpp
editor/libeditor/EditorUtils.h
editor/libeditor/HTMLEditSubActionHandler.cpp
editor/libeditor/HTMLEditor.cpp
editor/libeditor/HTMLEditorDataTransfer.cpp
editor/libeditor/HTMLStyleEditor.cpp
editor/libeditor/ManualNAC.h
extensions/auth/nsIAuthModule.cpp
extensions/permissions/nsPermissionManager.cpp
extensions/spellcheck/src/mozInlineSpellChecker.cpp
gfx/2d/Factory.cpp
gfx/2d/SourceSurfaceCapture.cpp
gfx/ipc/GPUProcessManager.cpp
gfx/layers/apz/src/APZCTreeManager.cpp
gfx/layers/apz/src/AsyncPanZoomController.cpp
gfx/layers/apz/src/InputQueue.cpp
gfx/layers/composite/CompositorScreenshotGrabber.cpp
gfx/layers/ipc/CompositorManagerChild.cpp
gfx/layers/ipc/UiCompositorControllerChild.cpp
gfx/layers/mlgpu/MLGPUScreenshotGrabber.cpp
gfx/layers/mlgpu/MaskOperation.cpp
gfx/thebes/PrintTarget.cpp
gfx/thebes/PrintTargetSkPDF.cpp
gfx/vr/ipc/VRGPUParent.cpp
image/imgFrame.h
image/imgTools.cpp
ipc/chromium/src/base/message_loop.cc
ipc/chromium/src/base/message_loop.h
ipc/chromium/src/chrome/common/ipc_message.cc
ipc/chromium/src/chrome/common/ipc_message_utils.h
ipc/glue/IPCStreamDestination.cpp
ipc/glue/InProcessImpl.cpp
ipc/glue/TransportSecurityInfoUtils.cpp
js/xpconnect/src/XPCInlines.h
js/xpconnect/src/XPCWrappedNative.cpp
js/xpconnect/src/XPCWrappedNativeInfo.cpp
js/xpconnect/src/XPCWrappedNativeProto.cpp
js/xpconnect/src/xpcprivate.h
layout/base/PresShell.cpp
layout/base/PresShell.h
layout/base/nsDocumentViewer.cpp
layout/base/nsLayoutUtils.cpp
layout/base/nsRefreshDriver.cpp
layout/generic/nsFrameSelection.cpp
layout/generic/nsIFrame.h
layout/generic/nsTextFrame.cpp
layout/generic/nsVideoFrame.cpp
layout/ipc/RemoteLayerTreeOwner.cpp
layout/painting/FrameLayerBuilder.cpp
layout/printing/nsPrintJob.cpp
layout/style/CSSPageRule.cpp
layout/style/CSSStyleRule.cpp
layout/style/GlobalStyleSheetCache.cpp
layout/style/Loader.cpp
layout/style/StyleSheet.cpp
layout/style/nsFontFaceLoader.cpp
layout/svg/SVGImageContext.cpp
layout/svg/nsSVGImageFrame.cpp
layout/svg/nsSVGMaskFrame.cpp
layout/xul/nsImageBoxFrame.cpp
layout/xul/tree/nsTreeContentView.cpp
media/mtransport/dtlsidentity.cpp
media/mtransport/test/buffered_stun_socket_unittest.cpp
media/webrtc/signaling/src/media-conduit/WebrtcMediaDataDecoderCodec.cpp
media/webrtc/signaling/src/media-conduit/WebrtcMediaDataEncoderCodec.cpp
media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp
mfbt/RefPtr.h
modules/libjar/nsJAR.cpp
modules/libpref/Preferences.cpp
netwerk/base/NetworkConnectivityService.cpp
netwerk/base/TLSServerSocket.cpp
netwerk/base/nsFileStreams.cpp
netwerk/base/nsIURIMutator.idl
netwerk/base/nsServerSocket.cpp
netwerk/base/nsSocketTransport2.cpp
netwerk/base/nsStandardURL.h
netwerk/base/nsUDPSocket.cpp
netwerk/cache2/CacheFile.cpp
netwerk/cache2/CacheFileIOManager.cpp
netwerk/cache2/CacheFileInputStream.cpp
netwerk/cache2/CacheFileOutputStream.cpp
netwerk/cache2/CacheIndex.cpp
netwerk/cache2/OldWrappers.cpp
netwerk/dns/nsHostResolver.cpp
netwerk/protocol/file/nsFileChannel.cpp
netwerk/protocol/http/HttpBackgroundChannelChild.cpp
netwerk/protocol/http/HttpBackgroundChannelParent.cpp
netwerk/protocol/http/HttpChannelChild.cpp
netwerk/protocol/http/HttpChannelParent.cpp
netwerk/protocol/http/InterceptedHttpChannel.cpp
netwerk/protocol/http/nsCORSListenerProxy.cpp
netwerk/protocol/http/nsHttpTransaction.cpp
netwerk/protocol/res/ExtensionProtocolHandler.cpp
netwerk/url-classifier/UrlClassifierCommon.cpp
parser/html/nsHtml5AtomTable.cpp
parser/html/nsHtml5StreamParser.cpp
security/manager/ssl/nsNSSCertHelper.cpp
services/crypto/component/IdentityCryptoService.cpp
storage/mozStorageAsyncStatementExecution.cpp
storage/mozStorageService.cpp
storage/test/gtest/test_asyncStatementExecution_transaction.cpp
toolkit/components/alerts/AlertNotification.cpp
toolkit/components/alerts/AlertNotificationIPCSerializer.h
toolkit/components/places/Database.cpp
toolkit/components/places/nsAnnoProtocolHandler.cpp
toolkit/components/places/nsFaviconService.cpp
toolkit/components/places/nsNavHistory.cpp
toolkit/components/telemetry/core/TelemetryScalar.cpp
toolkit/components/telemetry/geckoview/TelemetryGeckoViewPersistence.cpp
uriloader/exthandler/nsExternalHelperAppService.cpp
uriloader/prefetch/OfflineCacheUpdateChild.cpp
uriloader/prefetch/nsPrefetchService.cpp
widget/PuppetWidget.cpp
widget/gtk/nsDragService.cpp
widget/gtk/nsWidgetFactory.cpp
widget/gtk/nsWindow.cpp
widget/nsBaseWidget.cpp
xpcom/base/CycleCollectedJSContext.cpp
xpcom/base/nsCOMPtr.h
xpcom/ds/nsAtomTable.cpp
xpcom/io/nsMultiplexInputStream.cpp
xpcom/io/nsPipe3.cpp
xpcom/tests/gtest/TestCOMPtr.cpp
xpcom/tests/gtest/TestCloneInputStream.cpp
xpcom/tests/gtest/TestNsRefPtr.cpp
xpcom/threads/MozPromise.h
xpcom/threads/SchedulerGroup.cpp
xpcom/threads/TaskQueue.cpp
xpcom/threads/ThreadEventTarget.cpp
xpcom/threads/nsThreadManager.cpp
xpcom/threads/nsThreadUtils.cpp
--- a/accessible/base/nsAccessiblePivot.cpp
+++ b/accessible/base/nsAccessiblePivot.cpp
@@ -393,17 +393,17 @@ bool nsAccessiblePivot::IsDescendantOf(A
   } while ((accessible = accessible->Parent()));
 
   return false;
 }
 
 bool nsAccessiblePivot::MovePivotInternal(Accessible* aPosition,
                                           PivotMoveReason aReason,
                                           bool aIsFromUserInput) {
-  RefPtr<Accessible> oldPosition = mPosition.forget();
+  RefPtr<Accessible> oldPosition = std::move(mPosition);
   mPosition = aPosition;
   int32_t oldStart = mStartOffset, oldEnd = mEndOffset;
   mStartOffset = mEndOffset = -1;
 
   return NotifyOfPivotChange(oldPosition, oldStart, oldEnd, aReason,
                              nsIAccessiblePivot::NO_BOUNDARY, aIsFromUserInput);
 }
 
--- a/docshell/base/BrowsingContext.cpp
+++ b/docshell/base/BrowsingContext.cpp
@@ -1557,17 +1557,17 @@ bool IPDLParamTraits<dom::BrowsingContex
     return false;
   }
 
   if (!aActor->GetIPCChannel()->IsCrossProcess()) {
     // Release the reference taken in `::Write()` for in-process actors.
     browsingContext.get()->Release();
   }
 
-  *aResult = browsingContext.forget();
+  *aResult = std::move(browsingContext);
   return true;
 }
 
 void IPDLParamTraits<dom::BrowsingContext::IPCInitializer>::Write(
     IPC::Message* aMessage, IProtocol* aActor,
     const dom::BrowsingContext::IPCInitializer& aInit) {
   // Write actor ID parameters.
   WriteIPDLParam(aMessage, aActor, aInit.mId);
--- a/docshell/base/CanonicalBrowsingContext.cpp
+++ b/docshell/base/CanonicalBrowsingContext.cpp
@@ -485,17 +485,17 @@ CanonicalBrowsingContext::ChangeFrameRem
 
   GetNewOrUsedBrowserProcessAsync(aRemoteType)
       ->Then(
           GetMainThreadSerialEventTarget(), __func__,
           [change](ContentParent* aContentParent) {
             change->Complete(aContentParent);
           },
           [change](nsresult aRv) { change->Cancel(aRv); });
-  return promise.forget();
+  return promise;
 }
 
 already_AddRefed<Promise> CanonicalBrowsingContext::ChangeFrameRemoteness(
     const nsAString& aRemoteType, uint64_t aPendingSwitchId, ErrorResult& aRv) {
   nsIGlobalObject* global = xpc::NativeGlobal(xpc::PrivilegedJunkScope());
 
   RefPtr<Promise> promise = Promise::Create(global, aRv);
   if (aRv.Failed()) {
--- a/docshell/base/WindowContext.cpp
+++ b/docshell/base/WindowContext.cpp
@@ -209,17 +209,17 @@ bool IPDLParamTraits<dom::WindowContext*
     return false;
   }
 
   if (!aActor->GetIPCChannel()->IsCrossProcess()) {
     // Release the reference taken in `::Write()` for in-process actors.
     windowContext.get()->Release();
   }
 
-  *aResult = windowContext.forget();
+  *aResult = std::move(windowContext);
   return true;
 }
 
 void IPDLParamTraits<dom::WindowContext::IPCInitializer>::Write(
     IPC::Message* aMessage, IProtocol* aActor,
     const dom::WindowContext::IPCInitializer& aInit) {
   // Write actor ID parameters.
   WriteIPDLParam(aMessage, aActor, aInit.mInnerWindowId);
--- a/docshell/base/nsDefaultURIFixup.cpp
+++ b/docshell/base/nsDefaultURIFixup.cpp
@@ -423,17 +423,17 @@ nsDefaultURIFixup::KeywordToURI(const ns
     CopyUTF8toUTF16(keyword, info->mKeywordAsSent);
     info->mKeywordProviderName = providerName;
 
     if (aPostData) {
       postData.forget(aPostData);
     }
 
     nsCOMPtr<nsIURI> temp = DeserializeURI(uri);
-    info->mPreferredURI = temp.forget();
+    info->mPreferredURI = std::move(temp);
     return NS_OK;
   }
 
   // Try falling back to the search service's default search engine
   nsCOMPtr<nsISearchService> searchSvc =
       do_GetService("@mozilla.org/browser/search-service;1");
   if (searchSvc) {
     // We must use an appropriate search engine depending on the private
--- a/docshell/base/nsDocShellEditorData.cpp
+++ b/docshell/base/nsDocShellEditorData.cpp
@@ -21,34 +21,34 @@ nsDocShellEditorData::nsDocShellEditorDa
       mDetachedMakeEditable(false) {
   NS_ASSERTION(mDocShell, "Where is my docShell?");
 }
 
 nsDocShellEditorData::~nsDocShellEditorData() { TearDownEditor(); }
 
 void nsDocShellEditorData::TearDownEditor() {
   if (mHTMLEditor) {
-    RefPtr<HTMLEditor> htmlEditor = mHTMLEditor.forget();
+    RefPtr<HTMLEditor> htmlEditor = std::move(mHTMLEditor);
     htmlEditor->PreDestroy(false);
   }
   mEditingSession = nullptr;
   mIsDetached = false;
 }
 
 nsresult nsDocShellEditorData::MakeEditable(bool aInWaitForUriLoad) {
   if (mMakeEditable) {
     return NS_OK;
   }
 
   // if we are already editable, and are getting turned off,
   // nuke the editor.
   if (mHTMLEditor) {
     NS_WARNING("Destroying existing editor on frame");
 
-    RefPtr<HTMLEditor> htmlEditor = mHTMLEditor.forget();
+    RefPtr<HTMLEditor> htmlEditor = std::move(mHTMLEditor);
     htmlEditor->PreDestroy(false);
   }
 
   if (aInWaitForUriLoad) {
     mMakeEditable = true;
   }
   return NS_OK;
 }
@@ -67,17 +67,17 @@ nsresult nsDocShellEditorData::SetHTMLEd
   // destroy any editor that we have. Checks for equality are
   // necessary to ensure that assigment into the nsCOMPtr does
   // not temporarily reduce the refCount of the editor to zero
   if (mHTMLEditor == aHTMLEditor) {
     return NS_OK;
   }
 
   if (mHTMLEditor) {
-    RefPtr<HTMLEditor> htmlEditor = mHTMLEditor.forget();
+    RefPtr<HTMLEditor> htmlEditor = std::move(mHTMLEditor);
     htmlEditor->PreDestroy(false);
     MOZ_ASSERT(!mHTMLEditor,
                "Nested call of nsDocShellEditorData::SetHTMLEditor() detected");
   }
 
   mHTMLEditor = aHTMLEditor;  // owning addref
   if (!mHTMLEditor) {
     mMakeEditable = false;
--- a/docshell/shistory/MaybeNewPSHEntry.cpp
+++ b/docshell/shistory/MaybeNewPSHEntry.cpp
@@ -83,15 +83,15 @@ bool IPDLParamTraits<dom::CrossProcessSH
         return true;
       },
       [&](dom::NewPSHEntry& newEntry) {
         RefPtr<dom::SHEntryChild> entry = new dom::SHEntryChild(
             static_cast<dom::SHistoryChild*>(newEntry.mSHistoryChild),
             newEntry.mSharedID);
         dom::ContentChild::GetSingleton()->BindPSHEntryEndpoint(
             std::move(newEntry.mEndpoint), do_AddRef(entry).take());
-        *aEntry = entry.forget();
+        *aEntry = std::move(entry);
         return true;
       });
 }
 
 }  // namespace ipc
 }  // namespace mozilla
--- a/docshell/shistory/SHistoryParent.cpp
+++ b/docshell/shistory/SHistoryParent.cpp
@@ -227,17 +227,17 @@ bool SHistoryParent::RecvFindEntryForBFC
     NS_ENSURE_SUCCESS(rv, false);
 
     RefPtr<LegacySHEntry> shEntry = entry.forget().downcast<LegacySHEntry>();
     if (shEntry->GetSharedStateID() == aSharedID) {
       if (!aIncludeCurrentEntry && i == currentIndex) {
         *aEntry = nullptr;
         *aIndex = -1;
       } else {
-        *aEntry = shEntry.forget();
+        *aEntry = std::move(shEntry);
         *aIndex = i;
       }
 
       return true;
     }
   }
   *aEntry = nullptr;
   *aIndex = -1;
--- a/docshell/shistory/nsSHistory.cpp
+++ b/docshell/shistory/nsSHistory.cpp
@@ -1575,17 +1575,17 @@ nsresult nsSHistory::InitiateLoad(nsISHE
   loadState->SetLoadFlags(nsIWebNavigation::LOAD_FLAGS_NONE);
   nsCOMPtr<nsIPrincipal> triggeringPrincipal =
       aFrameEntry->GetTriggeringPrincipal();
   loadState->SetTriggeringPrincipal(triggeringPrincipal);
   loadState->SetFirstParty(false);
   nsCOMPtr<nsIContentSecurityPolicy> csp = aFrameEntry->GetCsp();
   loadState->SetCsp(csp);
 
-  aLoadResult.mLoadState = loadState.forget();
+  aLoadResult.mLoadState = std::move(loadState);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSHistory::CreateEntry(nsISHEntry** aEntry) {
   nsCOMPtr<nsISHEntry> entry =
       new nsLegacySHEntry(this, SHEntryChildShared::CreateSharedID());
--- a/dom/animation/Animation.cpp
+++ b/dom/animation/Animation.cpp
@@ -1722,17 +1722,17 @@ class AsyncFinishNotification : public M
 void Animation::DoFinishNotification(SyncNotifyFlag aSyncNotifyFlag) {
   CycleCollectedJSContext* context = CycleCollectedJSContext::Get();
 
   if (aSyncNotifyFlag == SyncNotifyFlag::Sync) {
     DoFinishNotificationImmediately();
   } else if (!mFinishNotificationTask) {
     RefPtr<MicroTaskRunnable> runnable = new AsyncFinishNotification(this);
     context->DispatchToMicroTask(do_AddRef(runnable));
-    mFinishNotificationTask = runnable.forget();
+    mFinishNotificationTask = std::move(runnable);
   }
 }
 
 void Animation::ResetFinishedPromise() {
   mFinishedIsResolved = false;
   mFinished = nullptr;
 }
 
--- a/dom/base/BodyConsumer.cpp
+++ b/dom/base/BodyConsumer.cpp
@@ -636,17 +636,17 @@ void BodyConsumer::ContinueConsumeBody(n
   auto autoFree = mozilla::MakeScopeExit([&] { free(aResult); });
 
   if (mBodyConsumed) {
     return;
   }
   mBodyConsumed = true;
 
   MOZ_ASSERT(mConsumePromise);
-  RefPtr<Promise> localPromise = mConsumePromise.forget();
+  RefPtr<Promise> localPromise = std::move(mConsumePromise);
 
   RefPtr<BodyConsumer> self = this;
   auto autoReleaseObject =
       mozilla::MakeScopeExit([self] { self->ReleaseObject(); });
 
   if (aShuttingDown) {
     // If shutting down, we don't want to resolve any promise.
     return;
@@ -746,17 +746,17 @@ void BodyConsumer::ContinueConsumeBlobBo
   MOZ_ASSERT(mConsumeType == CONSUME_BLOB);
 
   if (mBodyConsumed) {
     return;
   }
   mBodyConsumed = true;
 
   MOZ_ASSERT(mConsumePromise);
-  RefPtr<Promise> localPromise = mConsumePromise.forget();
+  RefPtr<Promise> localPromise = std::move(mConsumePromise);
 
   if (!aShuttingDown) {
     RefPtr<dom::Blob> blob = dom::Blob::Create(mGlobal, aBlobImpl);
     if (NS_WARN_IF(!blob)) {
       localPromise->MaybeReject(NS_ERROR_FAILURE);
       return;
     }
 
--- a/dom/base/BodyStream.cpp
+++ b/dom/base/BodyStream.cpp
@@ -116,17 +116,17 @@ void BodyStream::Create(JSContext* aCx, 
     if (NS_WARN_IF(!workerRef)) {
       aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
       return;
     }
 
     // Note, this will create a ref-cycle between the holder and the stream.
     // The cycle is broken when the stream is closed or the worker begins
     // shutting down.
-    stream->mWorkerRef = workerRef.forget();
+    stream->mWorkerRef = std::move(workerRef);
   }
 
   aRv.MightThrowJSException();
   JS::Rooted<JSObject*> body(aCx, JS::NewReadableExternalSourceStreamObject(
                                       aCx, stream, aStreamHolder));
   if (!body) {
     aRv.StealExceptionFromJSContext(aCx);
     return;
--- a/dom/base/ChromeUtils.cpp
+++ b/dom/base/ChromeUtils.cpp
@@ -332,17 +332,17 @@ class IdleDispatchRunnable final : publi
       CancelTimer();
 
       auto deadline = mDeadline - TimeStamp::ProcessCreation();
 
       ErrorResult rv;
       RefPtr<IdleDeadline> idleDeadline =
           new IdleDeadline(mParent, mTimedOut, deadline.ToMilliseconds());
 
-      RefPtr<IdleRequestCallback> callback(mCallback.forget());
+      RefPtr<IdleRequestCallback> callback(std::move(mCallback));
       MOZ_ASSERT(!mCallback);
       callback->Call(*idleDeadline, "ChromeUtils::IdleDispatch handler");
       mParent = nullptr;
     }
     return NS_OK;
   }
 
   void SetDeadline(TimeStamp aDeadline) override { mDeadline = aDeadline; }
--- a/dom/base/Document.cpp
+++ b/dom/base/Document.cpp
@@ -5982,17 +5982,17 @@ void Document::SetBaseURI(nsIURI* aURI) 
   RefreshLinkHrefs();
 }
 
 Result<nsCOMPtr<nsIURI>, nsresult> Document::ResolveWithBaseURI(
     const nsAString& aURI) {
   nsCOMPtr<nsIURI> resolvedURI;
   MOZ_TRY(
       NS_NewURI(getter_AddRefs(resolvedURI), aURI, nullptr, GetDocBaseURI()));
-  return std::move(resolvedURI);
+  return resolvedURI;
 }
 
 URLExtraData* Document::DefaultStyleAttrURLData() {
   MOZ_ASSERT(NS_IsMainThread());
   nsIURI* baseURI = GetDocBaseURI();
   nsIPrincipal* principal = NodePrincipal();
   bool equals;
   if (!mCachedURLData || mCachedURLData->BaseURI() != baseURI ||
@@ -8703,17 +8703,17 @@ mozilla::dom::Nullable<mozilla::dom::Win
     return nullptr;
   }
   RefPtr<nsGlobalWindowOuter> win = nsGlobalWindowOuter::Cast(outer);
   RefPtr<BrowsingContext> newBC;
   rv = win->OpenJS(aURL, aName, aFeatures, getter_AddRefs(newBC));
   if (!newBC) {
     return nullptr;
   }
-  return WindowProxyHolder(newBC.forget());
+  return WindowProxyHolder(std::move(newBC));
 }
 
 Document* Document::Open(const Optional<nsAString>& /* unused */,
                          const Optional<nsAString>& /* unused */,
                          ErrorResult& aError) {
   // Implements
   // <https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#document-open-steps>
 
@@ -8863,17 +8863,17 @@ Document* Document::Open(const Optional<
     nsCOMPtr<nsIURI> newURI = callerDoc->GetDocumentURI();
     if (callerDoc != this) {
       nsCOMPtr<nsIURI> noFragmentURI;
       nsresult rv = NS_GetURIWithoutRef(newURI, getter_AddRefs(noFragmentURI));
       if (NS_WARN_IF(NS_FAILED(rv))) {
         aError.Throw(rv);
         return nullptr;
       }
-      newURI = noFragmentURI.forget();
+      newURI = std::move(noFragmentURI);
     }
 
     // UpdateURLAndHistory might do various member-setting, so make sure we're
     // holding strong refs to all the refcounted args on the stack.  We can
     // assume that our caller is holding on to "this" already.
     nsCOMPtr<nsIURI> currentURI = GetDocumentURI();
     bool equalURIs;
     nsresult rv = currentURI->Equals(newURI, &equalURIs);
@@ -11691,32 +11691,32 @@ static already_AddRefed<nsPIDOMWindowOut
 
   nsCOMPtr<nsPIDOMWindowOuter> window = document->GetWindow();
   if (!window) {
     return nullptr;
   }
 
   // Trying to find the top window (equivalent to window.top).
   if (nsCOMPtr<nsPIDOMWindowOuter> top = window->GetInProcessTop()) {
-    window = top.forget();
+    window = std::move(top);
   }
   return window.forget();
 }
 
 /**
  * nsAutoFocusEvent is used to dispatch a focus event for an
  * nsGenericHTMLFormElement with the autofocus attribute enabled.
  */
 class nsAutoFocusEvent : public Runnable {
  public:
-  explicit nsAutoFocusEvent(already_AddRefed<Element>&& aElement,
-                            already_AddRefed<nsPIDOMWindowOuter>&& aTopWindow)
+  explicit nsAutoFocusEvent(nsCOMPtr<Element>&& aElement,
+                            nsCOMPtr<nsPIDOMWindowOuter>&& aTopWindow)
       : mozilla::Runnable("nsAutoFocusEvent"),
-        mElement(aElement),
-        mTopWindow(aTopWindow) {}
+        mElement(std::move(aElement)),
+        mTopWindow(std::move(aTopWindow)) {}
 
   NS_IMETHOD Run() override {
     nsCOMPtr<nsPIDOMWindowOuter> currentTopWindow =
         FindTopWindowForElement(mElement);
     if (currentTopWindow != mTopWindow) {
       // The element's top window changed from when the event was queued.
       // Don't take away focus from an unrelated window.
       return NS_OK;
@@ -11779,17 +11779,17 @@ void Document::TriggerAutoFocus() {
     // allows autofocus after load.
     nsCOMPtr<Document> topDoc = topWindow->GetExtantDoc();
     if (topDoc &&
         topDoc->GetReadyStateEnum() == Document::READYSTATE_COMPLETE) {
       return;
     }
 
     nsCOMPtr<nsIRunnable> event =
-        new nsAutoFocusEvent(autoFocusElement.forget(), topWindow.forget());
+        new nsAutoFocusEvent(std::move(autoFocusElement), topWindow.forget());
     nsresult rv = NS_DispatchToCurrentThread(event.forget());
     NS_ENSURE_SUCCESS_VOID(rv);
   }
 }
 
 void Document::SetScrollToRef(nsIURI* aDocumentURI) {
   if (!aDocumentURI) {
     return;
@@ -12871,17 +12871,17 @@ class PendingFullscreenChangeList {
           mRootShellForIteration(aDoc->GetDocShell()) {
       if (mCurrent) {
         if (mRootShellForIteration && aOption == eDocumentsWithSameRoot) {
           // Use a temporary to avoid undefined behavior from passing
           // mRootShellForIteration.
           nsCOMPtr<nsIDocShellTreeItem> root;
           mRootShellForIteration->GetInProcessRootTreeItem(
               getter_AddRefs(root));
-          mRootShellForIteration = root.forget();
+          mRootShellForIteration = std::move(root);
         }
         SkipToNextMatch();
       }
     }
 
     UniquePtr<T> TakeAndNext() {
       auto thisChange = TakeAndNextInternal();
       SkipToNextMatch();
@@ -12906,17 +12906,17 @@ class PendingFullscreenChangeList {
             // from a document detached from the doc shell.
             UniquePtr<T> change = TakeAndNextInternal();
             change->MayRejectPromise(u"Document is not active");
             continue;
           }
           while (docShell && docShell != mRootShellForIteration) {
             nsCOMPtr<nsIDocShellTreeItem> parent;
             docShell->GetInProcessParent(getter_AddRefs(parent));
-            docShell = parent.forget();
+            docShell = std::move(parent);
           }
           if (docShell) {
             break;
           }
         }
         // The current one either don't have matched type, or isn't
         // inside the given subtree, so skip this item.
         mCurrent = mCurrent->getNext();
@@ -15685,17 +15685,17 @@ already_AddRefed<mozilla::dom::Promise> 
                 return;
               }
 
               sapr->RequestDelayedTask(
                   inner->EventTargetFor(TaskCategory::Other),
                   ContentPermissionRequestBase::DelayedTaskType::Request);
             });
 
-        return p.forget();
+        return std::move(p);
       };
       AntiTrackingCommon::AddFirstPartyStorageAccessGrantedFor(
           NodePrincipal(), inner, AntiTrackingCommon::eStorageAccessAPI,
           performFinalChecks)
           ->Then(
               GetCurrentThreadSerialEventTarget(), __func__,
               [outer, promise] {
                 // Step 10. Grant the document access to cookies and store
@@ -15981,17 +15981,17 @@ void Document::RecomputeLanguageFromChar
     language = service->GetLocaleLanguage();
   }
 
   if (language == mLanguageFromCharset) {
     return;
   }
 
   mMayNeedFontPrefsUpdate = true;
-  mLanguageFromCharset = language.forget();
+  mLanguageFromCharset = std::move(language);
 }
 
 nsICookieSettings* Document::CookieSettings() {
   // If we are here, this is probably a javascript: URL document. In any case,
   // we must have a nsCookieSettings. Let's create it.
   if (!mCookieSettings) {
     mCookieSettings = net::CookieSettings::Create();
   }
--- a/dom/base/IdleRequest.cpp
+++ b/dom/base/IdleRequest.cpp
@@ -52,15 +52,15 @@ uint32_t IdleRequest::GetTimeoutHandle()
 
 void IdleRequest::IdleRun(nsPIDOMWindowInner* aWindow,
                           DOMHighResTimeStamp aDeadline, bool aDidTimeout) {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_DIAGNOSTIC_ASSERT(mCallback);
 
   RefPtr<IdleDeadline> deadline =
       new IdleDeadline(aWindow, aDidTimeout, aDeadline);
-  RefPtr<IdleRequestCallback> callback(mCallback.forget());
+  RefPtr<IdleRequestCallback> callback(std::move(mCallback));
   MOZ_ASSERT(!mCallback);
   callback->Call(*deadline, "requestIdleCallback handler");
 }
 
 }  // namespace dom
 }  // namespace mozilla
--- a/dom/base/ImageEncoder.cpp
+++ b/dom/base/ImageEncoder.cpp
@@ -94,17 +94,17 @@ class EncodingCompleteEvent : public Can
 
   // MOZ_CAN_RUN_SCRIPT_BOUNDARY until Runnable::Run is MOZ_CAN_RUN_SCRIPT.  See
   // bug 1535398.
   MOZ_CAN_RUN_SCRIPT_BOUNDARY
   NS_IMETHOD Run() override {
     nsresult rv = NS_OK;
 
     // We want to null out mEncodeCompleteCallback no matter what.
-    RefPtr<EncodeCompleteCallback> callback(mEncodeCompleteCallback.forget());
+    RefPtr<EncodeCompleteCallback> callback(std::move(mEncodeCompleteCallback));
     if (!mFailed) {
       RefPtr<BlobImpl> blobImpl = new MemoryBlobImpl(mImgData, mImgSize, mType);
       rv = callback->ReceiveBlobImpl(blobImpl.forget());
     } else {
       rv = callback->ReceiveBlobImpl(nullptr);
     }
 
     return rv;
--- a/dom/base/PostMessageEvent.cpp
+++ b/dom/base/PostMessageEvent.cpp
@@ -64,17 +64,17 @@ PostMessageEvent::Run() {
   // targetWindow.
   AutoJSAPI jsapi;
   jsapi.Init();
   JSContext* cx = jsapi.cx();
 
   // The document URI is just used for the principal mismatch error message
   // below. Use a stack variable so mCallerURI is not held onto after
   // this method finishes, regardless of the method outcome.
-  nsCOMPtr<nsIURI> callerURI = mCallerURI.forget();
+  nsCOMPtr<nsIURI> callerURI = std::move(mCallerURI);
 
   // If we bailed before this point we're going to leak mMessage, but
   // that's probably better than crashing.
 
   RefPtr<nsGlobalWindowInner> targetWindow;
   if (mTargetWindow->IsClosedOrClosing() ||
       !(targetWindow = mTargetWindow->GetCurrentInnerWindowInternal()) ||
       targetWindow->IsDying())
--- a/dom/base/ResizeObserver.cpp
+++ b/dom/base/ResizeObserver.cpp
@@ -129,17 +129,17 @@ already_AddRefed<ResizeObserver> ResizeO
   }
 
   Document* doc = window->GetExtantDoc();
   if (!doc) {
     aRv.Throw(NS_ERROR_FAILURE);
     return nullptr;
   }
 
-  return do_AddRef(new ResizeObserver(window.forget(), doc, aCb));
+  return do_AddRef(new ResizeObserver(std::move(window), doc, aCb));
 }
 
 void ResizeObserver::Observe(Element& aTarget,
                              const ResizeObserverOptions& aOptions,
                              ErrorResult& aRv) {
   // NOTE(emilio): Per spec, this is supposed to happen on construction, but the
   // spec isn't particularly sane here, see
   // https://github.com/w3c/csswg-drafts/issues/4518
@@ -301,17 +301,17 @@ void ResizeObserverEntry::SetContentRect
 
   // 1. Update mContentRect.
   nsMargin padding = frame ? frame->GetUsedPadding() : nsMargin();
   // Per the spec, we need to use the top-left padding offset as the origin of
   // our contentRect.
   nsRect rect(nsPoint(padding.left, padding.top), aSize);
   RefPtr<DOMRect> contentRect = new DOMRect(this);
   contentRect->SetLayoutRect(rect);
-  mContentRect = contentRect.forget();
+  mContentRect = std::move(contentRect);
 
   // 2. Update mContentBoxSize.
   const WritingMode wm = frame ? frame->GetWritingMode() : WritingMode();
   mContentBoxSize = new ResizeObserverSize(this, aSize, wm);
 }
 
 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(ResizeObserverSize, mOwner)
 NS_IMPL_CYCLE_COLLECTING_ADDREF(ResizeObserverSize)
--- a/dom/base/ResizeObserver.h
+++ b/dom/base/ResizeObserver.h
@@ -83,19 +83,19 @@ class ResizeObservation final : public L
  * ResizeObserver interfaces and algorithms are based on
  * https://drafts.csswg.org/resize-observer/#api
  */
 class ResizeObserver final : public nsISupports, public nsWrapperCache {
  public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(ResizeObserver)
 
-  ResizeObserver(already_AddRefed<nsPIDOMWindowInner>&& aOwner,
-                 Document* aDocument, ResizeObserverCallback& aCb)
-      : mOwner(aOwner), mDocument(aDocument), mCallback(&aCb) {
+  ResizeObserver(nsCOMPtr<nsPIDOMWindowInner>&& aOwner, Document* aDocument,
+                 ResizeObserverCallback& aCb)
+      : mOwner(std::move(aOwner)), mDocument(aDocument), mCallback(&aCb) {
     MOZ_ASSERT(mOwner, "Need a non-null owner window");
     MOZ_ASSERT(mDocument, "Need a non-null doc");
     MOZ_ASSERT(mDocument == mOwner->GetExtantDoc());
   }
 
   nsISupports* GetParentObject() const { return mOwner; }
 
   JSObject* WrapObject(JSContext* aCx,
--- a/dom/base/SelectionChangeEventDispatcher.cpp
+++ b/dom/base/SelectionChangeEventDispatcher.cpp
@@ -133,17 +133,17 @@ void SelectionChangeEventDispatcher::OnS
     // climb up the parent chain to escape the native anonymous subtree, and
     // then fire the event.
     if (const nsFrameSelection* fs = aSel->GetFrameSelection()) {
       if (nsCOMPtr<nsIContent> root = fs->GetLimiter()) {
         while (root && root->IsInNativeAnonymousSubtree()) {
           root = root->GetParent();
         }
 
-        target = root.forget();
+        target = std::move(root);
       }
     }
 
     // If we didn't get a target before, we can instead fire the event at the
     // document.
     if (!target) {
       target = aDoc;
     }
--- a/dom/base/WindowNamedPropertiesHandler.cpp
+++ b/dom/base/WindowNamedPropertiesHandler.cpp
@@ -101,17 +101,17 @@ bool WindowNamedPropertiesHandler::getOw
   nsGlobalWindowInner* win = xpc::WindowGlobalOrNull(aProxy);
   if (win->Length() > 0) {
     RefPtr<BrowsingContext> child = win->GetChildWindow(str);
     if (child && ShouldExposeChildWindow(str, child)) {
       // We found a subframe of the right name. Shadowing via |var foo| in
       // global scope is still allowed, since |var| only looks up |own|
       // properties. But unqualified shadowing will fail, per-spec.
       JS::Rooted<JS::Value> v(aCx);
-      if (!ToJSValue(aCx, WindowProxyHolder(child.forget()), &v)) {
+      if (!ToJSValue(aCx, WindowProxyHolder(std::move(child)), &v)) {
         return false;
       }
       FillPropertyDescriptor(aDesc, aProxy, 0, v);
       return true;
     }
   }
 
   // The rest of this function is for HTML documents only.
--- a/dom/base/WindowProxyHolder.h
+++ b/dom/base/WindowProxyHolder.h
@@ -28,26 +28,26 @@ namespace dom {
  * Nullable<WindowProxyHolder>.
  */
 class WindowProxyHolder {
  public:
   WindowProxyHolder() = default;
   explicit WindowProxyHolder(BrowsingContext* aBC) : mBrowsingContext(aBC) {
     MOZ_ASSERT(mBrowsingContext, "Don't set WindowProxyHolder to null.");
   }
-  explicit WindowProxyHolder(already_AddRefed<BrowsingContext>&& aBC)
+  explicit WindowProxyHolder(RefPtr<BrowsingContext>&& aBC)
       : mBrowsingContext(std::move(aBC)) {
     MOZ_ASSERT(mBrowsingContext, "Don't set WindowProxyHolder to null.");
   }
   WindowProxyHolder& operator=(BrowsingContext* aBC) {
     mBrowsingContext = aBC;
     MOZ_ASSERT(mBrowsingContext, "Don't set WindowProxyHolder to null.");
     return *this;
   }
-  WindowProxyHolder& operator=(already_AddRefed<BrowsingContext>&& aBC) {
+  WindowProxyHolder& operator=(RefPtr<BrowsingContext>&& aBC) {
     mBrowsingContext = std::move(aBC);
     MOZ_ASSERT(mBrowsingContext, "Don't set WindowProxyHolder to null.");
     return *this;
   }
 
   BrowsingContext* get() const {
     MOZ_ASSERT(mBrowsingContext, "WindowProxyHolder hasn't been initialized.");
     return mBrowsingContext;
--- a/dom/base/nsContentSink.cpp
+++ b/dom/base/nsContentSink.cpp
@@ -1407,17 +1407,18 @@ void nsContentSink::DropParserAndPerfHin
 
   // Ref. Bug 49115
   // Do this hack to make sure that the parser
   // doesn't get destroyed, accidently, before
   // the circularity, between sink & parser, is
   // actually broken.
   // Drop our reference to the parser to get rid of a circular
   // reference.
-  RefPtr<nsParserBase> kungFuDeathGrip(mParser.forget());
+  RefPtr<nsParserBase> kungFuDeathGrip = std::move(mParser);
+  mozilla::Unused << kungFuDeathGrip;
 
   if (mDynamicLowerValue) {
     // Reset the performance hint which was set to FALSE
     // when mDynamicLowerValue was set.
     FavorPerformanceHint(true, 0);
   }
 
   // Call UnblockOnload only if mRunsToComletion is false and if
--- a/dom/base/nsDOMMutationObserver.cpp
+++ b/dom/base/nsDOMMutationObserver.cpp
@@ -697,17 +697,17 @@ void nsDOMMutationObserver::TakeRecords(
   aRetVal.SetCapacity(mPendingMutationCount);
   RefPtr<nsDOMMutationRecord> current;
   current.swap(mFirstPendingMutation);
   for (uint32_t i = 0; i < mPendingMutationCount; ++i) {
     RefPtr<nsDOMMutationRecord> next;
     current->mNext.swap(next);
     if (!mMergeAttributeRecords ||
         !MergeableAttributeRecord(aRetVal.SafeLastElement(nullptr), current)) {
-      *aRetVal.AppendElement() = current.forget();
+      *aRetVal.AppendElement() = std::move(current);
     }
     current.swap(next);
   }
   ClearPendingRecords();
 }
 
 void nsDOMMutationObserver::GetObservingInfo(
     nsTArray<Nullable<MutationObservingInfo>>& aResult,
@@ -750,17 +750,17 @@ already_AddRefed<nsDOMMutationObserver> 
   nsCOMPtr<nsPIDOMWindowInner> window =
       do_QueryInterface(aGlobal.GetAsSupports());
   if (!window) {
     aRv.Throw(NS_ERROR_FAILURE);
     return nullptr;
   }
   bool isChrome = nsContentUtils::IsChromeDoc(window->GetExtantDoc());
   RefPtr<nsDOMMutationObserver> observer =
-      new nsDOMMutationObserver(window.forget(), aCb, isChrome);
+      new nsDOMMutationObserver(std::move(window), aCb, isChrome);
   return observer.forget();
 }
 
 bool nsDOMMutationObserver::MergeableAttributeRecord(
     nsDOMMutationRecord* aOldRecord, nsDOMMutationRecord* aRecord) {
   MOZ_ASSERT(mMergeAttributeRecords);
   return aOldRecord && aOldRecord->mType == nsGkAtoms::attributes &&
          aOldRecord->mType == aRecord->mType &&
--- a/dom/base/nsDOMMutationObserver.h
+++ b/dom/base/nsDOMMutationObserver.h
@@ -427,19 +427,19 @@ class nsAnimationReceiver : public nsMut
   {                                                  \
     0x0c3b91f8, 0xcc3b, 0x4b08, {                    \
       0x9e, 0xab, 0x07, 0x47, 0xa9, 0xe4, 0x65, 0xb4 \
     }                                                \
   }
 
 class nsDOMMutationObserver final : public nsISupports, public nsWrapperCache {
  public:
-  nsDOMMutationObserver(already_AddRefed<nsPIDOMWindowInner>&& aOwner,
+  nsDOMMutationObserver(nsCOMPtr<nsPIDOMWindowInner>&& aOwner,
                         mozilla::dom::MutationCallback& aCb, bool aChrome)
-      : mOwner(aOwner),
+      : mOwner(std::move(aOwner)),
         mLastPendingMutation(nullptr),
         mPendingMutationCount(0),
         mCallback(&aCb),
         mWaitingForRun(false),
         mIsChrome(aChrome),
         mMergeAttributeRecords(false),
         mId(++sCount) {}
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
@@ -485,34 +485,34 @@ class nsDOMMutationObserver final : publ
   bool MergeableAttributeRecord(nsDOMMutationRecord* aOldRecord,
                                 nsDOMMutationRecord* aRecord);
 
   void AppendMutationRecord(already_AddRefed<nsDOMMutationRecord> aRecord) {
     RefPtr<nsDOMMutationRecord> record = aRecord;
     MOZ_ASSERT(record);
     if (!mLastPendingMutation) {
       MOZ_ASSERT(!mFirstPendingMutation);
-      mFirstPendingMutation = record.forget();
+      mFirstPendingMutation = std::move(record);
       mLastPendingMutation = mFirstPendingMutation;
     } else {
       MOZ_ASSERT(mFirstPendingMutation);
-      mLastPendingMutation->mNext = record.forget();
+      mLastPendingMutation->mNext = std::move(record);
       mLastPendingMutation = mLastPendingMutation->mNext;
     }
     ++mPendingMutationCount;
   }
 
   void ClearPendingRecords() {
     // Break down the pending mutation record list so that cycle collector
     // can delete the objects sooner.
-    RefPtr<nsDOMMutationRecord> current = mFirstPendingMutation.forget();
+    RefPtr<nsDOMMutationRecord> current = std::move(mFirstPendingMutation);
     mLastPendingMutation = nullptr;
     mPendingMutationCount = 0;
     while (current) {
-      current = current->mNext.forget();
+      current = std::move(current->mNext);
     }
   }
 
   // static methods
   static void QueueMutationObserverMicroTask();
 
   MOZ_CAN_RUN_SCRIPT
   static void HandleMutations(mozilla::AutoSlowOperation& aAso);
--- a/dom/base/nsDOMNavigationTiming.cpp
+++ b/dom/base/nsDOMNavigationTiming.cpp
@@ -625,16 +625,16 @@ bool mozilla::ipc::IPDLParamTraits<nsDOM
       !ReadIPDLParam(aMsg, aIter, aActor, &timing->mDOMComplete) ||
       !ReadIPDLParam(aMsg, aIter, aActor, &timing->mTTFI) ||
       !ReadIPDLParam(aMsg, aIter, aActor,
                      &timing->mDocShellHasBeenActiveSinceNavigationStart)) {
     return false;
   }
   timing->mNavigationType = nsDOMNavigationTiming::Type(type);
   if (unloadedURI) {
-    timing->mUnloadedURI = unloadedURI->forget();
+    timing->mUnloadedURI = std::move(*unloadedURI);
   }
   if (loadedURI) {
-    timing->mLoadedURI = loadedURI->forget();
+    timing->mLoadedURI = std::move(*loadedURI);
   }
-  *aResult = timing.forget();
+  *aResult = std::move(timing);
   return true;
 }
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -898,17 +898,17 @@ nsFocusManager::WindowHidden(mozIDOMWind
   }
 
   if (!IsSameOrAncestor(window, mFocusedWindow)) return NS_OK;
 
   // at this point, we know that the window being hidden is either the focused
   // window, or an ancestor of the focused window. Either way, the focus is no
   // longer valid, so it needs to be updated.
 
-  RefPtr<Element> oldFocusedElement = mFocusedElement.forget();
+  RefPtr<Element> oldFocusedElement = std::move(mFocusedElement);
 
   nsCOMPtr<nsIDocShell> focusedDocShell = mFocusedWindow->GetDocShell();
   RefPtr<PresShell> presShell = focusedDocShell->GetPresShell();
 
   if (oldFocusedElement && oldFocusedElement->IsInComposedDoc()) {
     NotifyFocusStateChange(oldFocusedElement, nullptr,
                            mFocusedWindow->ShouldShowFocusRing(), false);
     window->UpdateCommands(NS_LITERAL_STRING("focus"), nullptr, 0);
--- a/dom/base/nsGlobalWindowInner.cpp
+++ b/dom/base/nsGlobalWindowInner.cpp
@@ -5492,55 +5492,55 @@ RefPtr<ServiceWorker> nsGlobalWindowInne
   MOZ_ASSERT(NS_IsMainThread());
   RefPtr<ServiceWorker> ref;
   ForEachEventTargetObject([&](DOMEventTargetHelper* aTarget, bool* aDoneOut) {
     RefPtr<ServiceWorker> sw = do_QueryObject(aTarget);
     if (!sw || !sw->Descriptor().Matches(aDescriptor)) {
       return;
     }
 
-    ref = sw.forget();
+    ref = std::move(sw);
     *aDoneOut = true;
   });
 
   if (!ref) {
     ref = ServiceWorker::Create(this, aDescriptor);
   }
 
-  return ref.forget();
+  return ref;
 }
 
 RefPtr<mozilla::dom::ServiceWorkerRegistration>
 nsGlobalWindowInner::GetServiceWorkerRegistration(
     const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor)
     const {
   MOZ_ASSERT(NS_IsMainThread());
   RefPtr<ServiceWorkerRegistration> ref;
   ForEachEventTargetObject([&](DOMEventTargetHelper* aTarget, bool* aDoneOut) {
     RefPtr<ServiceWorkerRegistration> swr = do_QueryObject(aTarget);
     if (!swr || !swr->MatchesDescriptor(aDescriptor)) {
       return;
     }
 
-    ref = swr.forget();
+    ref = std::move(swr);
     *aDoneOut = true;
   });
-  return ref.forget();
+  return ref;
 }
 
 RefPtr<ServiceWorkerRegistration>
 nsGlobalWindowInner::GetOrCreateServiceWorkerRegistration(
     const ServiceWorkerRegistrationDescriptor& aDescriptor) {
   MOZ_ASSERT(NS_IsMainThread());
   RefPtr<ServiceWorkerRegistration> ref =
       GetServiceWorkerRegistration(aDescriptor);
   if (!ref) {
     ref = ServiceWorkerRegistration::CreateForMainThread(this, aDescriptor);
   }
-  return ref.forget();
+  return ref;
 }
 
 nsresult nsGlobalWindowInner::FireDelayedDOMEvents() {
   if (mApplicationCache) {
     static_cast<nsDOMOfflineResourceList*>(mApplicationCache.get())
         ->FirePendingEvents();
   }
 
@@ -6871,17 +6871,17 @@ External* nsGlobalWindowInner::GetExtern
 
 void nsGlobalWindowInner::GetSidebar(OwningExternalOrWindowProxy& aResult,
                                      ErrorResult& aRv) {
 #ifdef HAVE_SIDEBAR
   // First check for a named frame named "sidebar"
   RefPtr<BrowsingContext> domWindow =
       GetChildWindow(NS_LITERAL_STRING("sidebar"));
   if (domWindow) {
-    aResult.SetAsWindowProxy() = domWindow.forget();
+    aResult.SetAsWindowProxy() = std::move(domWindow);
     return;
   }
 
   RefPtr<External> external = GetExternal(aRv);
   if (external) {
     aResult.SetAsExternal() = external;
   }
 #else
--- a/dom/base/nsGlobalWindowOuter.cpp
+++ b/dom/base/nsGlobalWindowOuter.cpp
@@ -3213,17 +3213,17 @@ nsPIDOMWindowOuter* nsGlobalWindowOuter:
   if (RefPtr<BrowsingContext> opener = GetOpenerBrowsingContext()) {
     return opener->GetDOMWindow();
   }
   return nullptr;
 }
 
 Nullable<WindowProxyHolder> nsGlobalWindowOuter::GetOpenerWindowOuter() {
   if (RefPtr<BrowsingContext> opener = GetOpenerBrowsingContext()) {
-    return WindowProxyHolder(opener.forget());
+    return WindowProxyHolder(std::move(opener));
   }
   return nullptr;
 }
 
 Nullable<WindowProxyHolder> nsGlobalWindowOuter::GetOpener() {
   return GetOpenerWindowOuter();
 }
 
@@ -5437,17 +5437,17 @@ void nsGlobalWindowOuter::FireAbuseEvent
 Nullable<WindowProxyHolder> nsGlobalWindowOuter::OpenOuter(
     const nsAString& aUrl, const nsAString& aName, const nsAString& aOptions,
     ErrorResult& aError) {
   RefPtr<BrowsingContext> bc;
   aError = OpenJS(aUrl, aName, aOptions, getter_AddRefs(bc));
   if (!bc) {
     return nullptr;
   }
-  return WindowProxyHolder(bc.forget());
+  return WindowProxyHolder(std::move(bc));
 }
 
 nsresult nsGlobalWindowOuter::Open(const nsAString& aUrl,
                                    const nsAString& aName,
                                    const nsAString& aOptions,
                                    nsDocShellLoadState* aLoadState,
                                    bool aForceNoOpener,
                                    BrowsingContext** _retval) {
@@ -5535,17 +5535,17 @@ Nullable<WindowProxyHolder> nsGlobalWind
                         true,                // aNavigate
                         argvArray, nullptr,  // Arguments
                         nullptr,             // aLoadState
                         false,               // aForceNoOpener
                         getter_AddRefs(dialog));
   if (!dialog) {
     return nullptr;
   }
-  return WindowProxyHolder(dialog.forget());
+  return WindowProxyHolder(std::move(dialog));
 }
 
 WindowProxyHolder nsGlobalWindowOuter::GetFramesOuter() {
   RefPtr<nsPIDOMWindowOuter> frames(this);
   FlushPendingNotifications(FlushType::ContentAndNotify);
   return WindowProxyHolder(mBrowsingContext);
 }
 
--- a/dom/base/nsINode.cpp
+++ b/dom/base/nsINode.cpp
@@ -1623,20 +1623,20 @@ void nsINode::DisconnectChild(nsIContent
     aKid->mNextSibling->mPreviousOrLastSibling = aKid->mPreviousOrLastSibling;
   } else {
     // aKid is the last child in the list
     mFirstChild->mPreviousOrLastSibling = aKid->mPreviousOrLastSibling;
   }
   aKid->mPreviousOrLastSibling = nullptr;
 
   if (previousSibling) {
-    previousSibling->mNextSibling = aKid->mNextSibling.forget();
+    previousSibling->mNextSibling = std::move(aKid->mNextSibling);
   } else {
     // aKid is the first child in the list
-    mFirstChild = aKid->mNextSibling.forget();
+    mFirstChild = std::move(aKid->mNextSibling);
   }
 
   --mChildCount;
 }
 
 nsIContent* nsINode::GetChildAt_Deprecated(uint32_t aIndex) const {
   if (aIndex >= GetChildCount()) {
     return nullptr;
--- a/dom/bindings/BindingUtils.cpp
+++ b/dom/bindings/BindingUtils.cpp
@@ -3364,17 +3364,17 @@ nsresult UnwrapWindowProxyArg(JSContext*
   }
 
   nsCOMPtr<nsPIDOMWindowInner> inner;
   nsresult rv = UnwrapArg<nsPIDOMWindowInner>(cx, src, getter_AddRefs(inner));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsPIDOMWindowOuter> outer = inner->GetOuterWindow();
   RefPtr<BrowsingContext> bc = outer ? outer->GetBrowsingContext() : nullptr;
-  ppArg = bc.forget();
+  ppArg = std::move(bc);
   return NS_OK;
 }
 
 template <decltype(JS::NewMapObject) Method>
 bool GetMaplikeSetlikeBackingObject(JSContext* aCx, JS::Handle<JSObject*> aObj,
                                     size_t aSlotIndex,
                                     JS::MutableHandle<JSObject*> aBackingObj,
                                     bool* aBackingObjCreated) {
--- a/dom/cache/CacheStreamControlChild.cpp
+++ b/dom/cache/CacheStreamControlChild.cpp
@@ -110,17 +110,17 @@ void CacheStreamControlChild::OpenStream
   // rejection here in many cases, we must handle the case where the
   // MozPromise resolve runnable is already in the event queue when the
   // worker wants to shut down.
   RefPtr<CacheWorkerRef> holder = GetWorkerRef();
 
   SendOpenStream(aId)->Then(
       GetCurrentThreadSerialEventTarget(), __func__,
       [aResolver, holder](RefPtr<nsIInputStream>&& aOptionalStream) {
-        aResolver(nsCOMPtr<nsIInputStream>(aOptionalStream.forget()));
+        aResolver(nsCOMPtr<nsIInputStream>(std::move(aOptionalStream)));
       },
       [aResolver, holder](ResponseRejectReason&& aReason) {
         aResolver(nullptr);
       });
 }
 
 void CacheStreamControlChild::NoteClosedAfterForget(const nsID& aId) {
   NS_ASSERT_OWNINGTHREAD(CacheStreamControlChild);
--- a/dom/canvas/CanvasRenderingContext2D.cpp
+++ b/dom/canvas/CanvasRenderingContext2D.cpp
@@ -1332,18 +1332,18 @@ bool CanvasRenderingContext2D::EnsureTar
       CopyBufferProvider(*mBufferProvider, *newTarget, persistedRect)) {
     needsClear = false;
   }
 
   if (needsClear) {
     newTarget->ClearRect(canvasRect);
   }
 
-  mTarget = newTarget.forget();
-  mBufferProvider = newProvider.forget();
+  mTarget = std::move(newTarget);
+  mBufferProvider = std::move(newProvider);
 
   RegisterAllocation();
 
   RestoreClipsAndTransformToTarget();
 
   // Force a full layer transaction since we didn't have a layer before
   // and now we might need one.
   if (mCanvasElement) {
@@ -4361,18 +4361,18 @@ CanvasRenderingContext2D::CachedSurfaceF
   }
 
   int32_t corsmode = imgIRequest::CORS_NONE;
   if (NS_SUCCEEDED(imgRequest->GetCORSMode(&corsmode))) {
     res.mCORSUsed = corsmode != imgIRequest::CORS_NONE;
   }
 
   res.mSize = res.mIntrinsicSize = res.mSourceSurface->GetSize();
-  res.mPrincipal = principal.forget();
-  res.mImageRequest = imgRequest.forget();
+  res.mPrincipal = std::move(principal);
+  res.mImageRequest = std::move(imgRequest);
   res.mIsWriteOnly = CheckWriteOnlySecurity(res.mCORSUsed, res.mPrincipal,
                                             res.mHadCrossOriginRedirects);
 
   return res;
 }
 
 // drawImage(in HTMLImageElement image, in float dx, in float dy);
 //   -- render image from 0,0 at dx,dy top-left coords
--- a/dom/canvas/CanvasRenderingContextHelper.cpp
+++ b/dom/canvas/CanvasRenderingContextHelper.cpp
@@ -36,17 +36,17 @@ void CanvasRenderingContextHelper::ToBlo
       RefPtr<BlobImpl> blobImpl = aBlobImpl;
 
       RefPtr<Blob> blob;
 
       if (blobImpl) {
         blob = Blob::Create(mGlobal, blobImpl);
       }
 
-      RefPtr<BlobCallback> callback(mBlobCallback.forget());
+      RefPtr<BlobCallback> callback(std::move(mBlobCallback));
       ErrorResult rv;
 
       callback->Call(blob, rv);
 
       mGlobal = nullptr;
       MOZ_ASSERT(!mBlobCallback);
 
       return rv.StealNSResult();
@@ -168,17 +168,17 @@ already_AddRefed<nsISupports> CanvasRend
     // CC participant from QI doesn't addref.
     nsXPCOMCycleCollectionParticipant* cp = nullptr;
     CallQueryInterface(context, &cp);
     if (!cp) {
       aRv.Throw(NS_ERROR_FAILURE);
       return nullptr;
     }
 
-    mCurrentContext = context.forget();
+    mCurrentContext = std::move(context);
     mCurrentContextType = contextType;
 
     nsresult rv = UpdateContext(aCx, aContextOptions, aRv);
     if (NS_FAILED(rv)) {
       // See bug 645792 and bug 1215072.
       // We want to throw only if dictionary initialization fails,
       // so only in case aRv has been set to some error value.
       if (contextType == CanvasContextType::WebGL1)
--- a/dom/clients/manager/ClientHandle.cpp
+++ b/dom/clients/manager/ClientHandle.cpp
@@ -116,34 +116,34 @@ RefPtr<GenericErrorResultPromise> Client
       ClientControlledArgs(aServiceWorker.ToIPC()),
       [outerPromise](const ClientOpResult& aResult) {
         outerPromise->Resolve(true, __func__);
       },
       [outerPromise](const ClientOpResult& aResult) {
         outerPromise->Reject(aResult.get_CopyableErrorResult(), __func__);
       });
 
-  return outerPromise.forget();
+  return outerPromise;
 }
 
 RefPtr<ClientStatePromise> ClientHandle::Focus(CallerType aCallerType) {
   RefPtr<ClientStatePromise::Private> outerPromise =
       new ClientStatePromise::Private(__func__);
 
   StartOp(
       ClientFocusArgs(aCallerType),
       [outerPromise](const ClientOpResult& aResult) {
         outerPromise->Resolve(
             ClientState::FromIPC(aResult.get_IPCClientState()), __func__);
       },
       [outerPromise](const ClientOpResult& aResult) {
         outerPromise->Reject(aResult.get_CopyableErrorResult(), __func__);
       });
 
-  return outerPromise.forget();
+  return outerPromise;
 }
 
 RefPtr<GenericErrorResultPromise> ClientHandle::PostMessage(
     StructuredCloneData& aData, const ServiceWorkerDescriptor& aSource) {
   if (IsShutdown()) {
     CopyableErrorResult rv;
     rv.ThrowInvalidStateError("Client has been destroyed");
     return GenericErrorResultPromise::CreateAndReject(rv, __func__);
@@ -166,17 +166,17 @@ RefPtr<GenericErrorResultPromise> Client
       std::move(args),
       [outerPromise](const ClientOpResult& aResult) {
         outerPromise->Resolve(true, __func__);
       },
       [outerPromise](const ClientOpResult& aResult) {
         outerPromise->Reject(aResult.get_CopyableErrorResult(), __func__);
       });
 
-  return outerPromise.forget();
+  return outerPromise;
 }
 
 RefPtr<GenericPromise> ClientHandle::OnDetach() {
   NS_ASSERT_OWNINGTHREAD(ClientSource);
 
   if (!mDetachPromise) {
     mDetachPromise = new GenericPromise::Private(__func__);
     if (IsShutdown()) {
--- a/dom/clients/manager/ClientManager.cpp
+++ b/dom/clients/manager/ClientManager.cpp
@@ -190,17 +190,17 @@ RefPtr<ClientOpPromise> ClientManager::S
         }
       },
       [promise] {
         CopyableErrorResult rv;
         rv.ThrowInvalidStateError("Client has been destroyed");
         promise->Reject(rv, __func__);
       });
 
-  return promise.forget();
+  return promise;
 }
 
 // static
 already_AddRefed<ClientManager> ClientManager::GetOrCreateForCurrentThread() {
   MOZ_DIAGNOSTIC_ASSERT(sClientManagerThreadLocalMagic1 == kThreadLocalMagic1);
   MOZ_DIAGNOSTIC_ASSERT(sClientManagerThreadLocalMagic2 == kThreadLocalMagic2);
   MOZ_DIAGNOSTIC_ASSERT(sClientManagerThreadLocalIndex != kBadThreadLocalIndex);
   MOZ_DIAGNOSTIC_ASSERT(sClientManagerThreadLocalIndex ==
--- a/dom/clients/manager/ClientManagerService.cpp
+++ b/dom/clients/manager/ClientManagerService.cpp
@@ -98,17 +98,17 @@ RefPtr<GenericPromise> OnShutdown() {
         if (NS_FAILED(rv)) {
           ref->Resolve(true, __func__);
           return;
         }
       });
 
   MOZ_ALWAYS_SUCCEEDS(SystemGroup::Dispatch(TaskCategory::Other, r.forget()));
 
-  return ref.forget();
+  return ref;
 }
 
 }  // anonymous namespace
 
 ClientManagerService::ClientManagerService() : mShutdown(false) {
   AssertIsOnBackgroundThread();
 
   // Only register one shutdown handler at a time.  If a previous service
@@ -305,17 +305,17 @@ RefPtr<ClientOpPromise> ClientManagerSer
   PClientNavigateOpParent* result =
       manager->SendPClientNavigateOpConstructor(op, args);
   if (!result) {
     CopyableErrorResult rv;
     rv.ThrowInvalidStateError("Client is aborted");
     promise->Reject(rv, __func__);
   }
 
-  return promise.forget();
+  return promise;
 }
 
 namespace {
 
 class PromiseListHolder final {
   RefPtr<ClientOpPromise::Private> mResultPromise;
   nsTArray<RefPtr<ClientOpPromise>> mPromiseList;
   nsTArray<ClientInfoAndState> mResultList;
@@ -467,17 +467,17 @@ RefPtr<ClientOpPromise> ClaimOnMainThrea
               promise->Reject(aRv, __func__);
             });
 
         scopeExit.release();
       });
 
   MOZ_ALWAYS_SUCCEEDS(SystemGroup::Dispatch(TaskCategory::Other, r.forget()));
 
-  return promise.forget();
+  return promise;
 }
 
 }  // anonymous namespace
 
 RefPtr<ClientOpPromise> ClientManagerService::Claim(
     const ClientClaimArgs& aArgs) {
   AssertIsOnBackgroundThread();
 
@@ -652,17 +652,17 @@ RefPtr<ClientOpPromise> ClientManagerSer
     already_AddRefed<ContentParent> aSourceProcess) {
   RefPtr<ClientOpPromise::Private> promise =
       new ClientOpPromise::Private(__func__);
 
   nsCOMPtr<nsIRunnable> r =
       new OpenWindowRunnable(promise, aArgs, std::move(aSourceProcess));
   MOZ_ALWAYS_SUCCEEDS(SystemGroup::Dispatch(TaskCategory::Other, r.forget()));
 
-  return promise.forget();
+  return promise;
 }
 
 bool ClientManagerService::HasWindow(
     const Maybe<ContentParentId>& aContentParentId,
     const PrincipalInfo& aPrincipalInfo, const nsID& aClientId) {
   AssertIsOnBackgroundThread();
 
   ClientSourceParent* source = FindSource(aClientId, aPrincipalInfo);
--- a/dom/clients/manager/ClientNavigateOpChild.cpp
+++ b/dom/clients/manager/ClientNavigateOpChild.cpp
@@ -279,17 +279,17 @@ RefPtr<ClientOpPromise> ClientNavigateOp
 
   rv = webProgress->AddProgressListener(listener,
                                         nsIWebProgress::NOTIFY_STATE_DOCUMENT);
   if (NS_FAILED(rv)) {
     CopyableErrorResult result;
     // XXXbz Can we throw something better here?
     result.Throw(rv);
     promise->Reject(result, __func__);
-    return promise.forget();
+    return promise;
   }
 
   return promise->Then(
       mSerialEventTarget, __func__,
       [listener](const ClientOpPromise::ResolveOrRejectValue& aValue) {
         return ClientOpPromise::CreateAndResolveOrReject(aValue, __func__);
       });
 }
--- a/dom/clients/manager/ClientOpenWindowUtils.cpp
+++ b/dom/clients/manager/ClientOpenWindowUtils.cpp
@@ -455,19 +455,19 @@ RefPtr<ClientOpPromise> ClientOpenWindow
   RefPtr<BrowsingContext> bc;
   CopyableErrorResult rv;
   OpenWindow(aArgs, getter_AddRefs(bc), rv);
 
   nsCOMPtr<nsPIDOMWindowOuter> outerWindow(bc->GetDOMWindow());
 
   if (NS_WARN_IF(rv.Failed())) {
     promise->Reject(rv, __func__);
-    return promise.forget();
+    return promise;
   }
 
   MOZ_DIAGNOSTIC_ASSERT(outerWindow);
   WaitForLoad(aArgs, outerWindow, promise);
 
-  return promise.forget();
+  return promise;
 }
 
 }  // namespace dom
 }  // namespace mozilla
--- a/dom/clients/manager/ClientSource.cpp
+++ b/dom/clients/manager/ClientSource.cpp
@@ -645,17 +645,17 @@ RefPtr<ClientOpPromise> ClientSource::Cl
             outerPromise->Resolve(CopyableErrorResult(), __func__);
           },
           [outerPromise, holder](const CopyableErrorResult& aResult) {
             holder->Complete();
             outerPromise->Reject(aResult, __func__);
           })
       ->Track(*holder);
 
-  return outerPromise.forget();
+  return outerPromise;
 }
 
 RefPtr<ClientOpPromise> ClientSource::GetInfoAndState(
     const ClientGetInfoAndStateArgs& aArgs) {
   Result<ClientState, ErrorResult> state = SnapshotState();
   if (state.isErr()) {
     return ClientOpPromise::CreateAndReject(
         CopyableErrorResult(state.unwrapErr()), __func__);
--- a/dom/clients/manager/ClientSourceParent.cpp
+++ b/dom/clients/manager/ClientSourceParent.cpp
@@ -284,13 +284,13 @@ RefPtr<ClientOpPromise> ClientSourcePare
     mController.emplace(aArgs.get_ClientControlledArgs().serviceWorker());
   }
 
   // Constructor failure will reject the promise via ActorDestroy().
   ClientSourceOpParent* actor =
       new ClientSourceOpParent(std::move(aArgs), promise);
   Unused << SendPClientSourceOpConstructor(actor, actor->Args());
 
-  return promise.forget();
+  return promise;
 }
 
 }  // namespace dom
 }  // namespace mozilla
--- a/dom/events/AsyncEventDispatcher.cpp
+++ b/dom/events/AsyncEventDispatcher.cpp
@@ -22,17 +22,17 @@ using namespace dom;
 AsyncEventDispatcher::AsyncEventDispatcher(EventTarget* aTarget,
                                            WidgetEvent& aEvent)
     : CancelableRunnable("AsyncEventDispatcher"),
       mTarget(aTarget),
       mEventMessage(eUnidentifiedEvent) {
   MOZ_ASSERT(mTarget);
   RefPtr<Event> event =
       EventDispatcher::CreateEvent(aTarget, nullptr, &aEvent, EmptyString());
-  mEvent = event.forget();
+  mEvent = std::move(event);
   mEventType.SetIsVoid(true);
   NS_ASSERTION(mEvent, "Should never fail to create an event");
   mEvent->DuplicatePrivateData();
   mEvent->SetTrusted(aEvent.IsTrusted());
 }
 
 NS_IMETHODIMP
 AsyncEventDispatcher::Run() {
--- a/dom/events/EventListenerManager.h
+++ b/dom/events/EventListenerManager.h
@@ -204,17 +204,17 @@ class EventListenerManager final : publi
           mListenerType(eNoListener),
           mListenerIsHandler(false),
           mHandlerIsString(false),
           mAllEvents(false),
           mIsChrome(false) {}
 
     Listener(Listener&& aOther)
         : mListener(std::move(aOther.mListener)),
-          mTypeAtom(aOther.mTypeAtom.forget()),
+          mTypeAtom(std::move(aOther.mTypeAtom)),
           mEventMessage(aOther.mEventMessage),
           mListenerType(aOther.mListenerType),
           mListenerIsHandler(aOther.mListenerIsHandler),
           mHandlerIsString(aOther.mHandlerIsString),
           mAllEvents(aOther.mAllEvents),
           mIsChrome(aOther.mIsChrome) {
       aOther.mEventMessage = eVoidEvent;
       aOther.mListenerType = eNoListener;
--- a/dom/events/EventStateManager.cpp
+++ b/dom/events/EventStateManager.cpp
@@ -3991,17 +3991,17 @@ void EventStateManager::UpdateCursor(nsP
     // while rather than taking its fallback cursor directly.
     if (customCursor.mEarlierCursorLoading &&
         gLastCursorSourceFrame == aTargetFrame &&
         TimeStamp::NowLoRes() - gLastCursorUpdateTime <
             TimeDuration::FromMilliseconds(kCursorLoadingTimeout)) {
       return;
     }
     cursor = framecursor->mCursor;
-    container = customCursor.mContainer.forget();
+    container = std::move(customCursor.mContainer);
     hotspot = Some(customCursor.mHotspot);
   }
 
   if (StaticPrefs::ui_use_activity_cursor()) {
     // Check whether or not to show the busy cursor
     nsCOMPtr<nsIDocShell> docShell(aPresContext->GetDocShell());
     if (!docShell) return;
     auto busyFlags = docShell->GetBusyFlags();
--- a/dom/events/IMEContentObserver.cpp
+++ b/dom/events/IMEContentObserver.cpp
@@ -2074,30 +2074,30 @@ void IMEContentObserver::DocumentObserve
   MOZ_ASSERT(aDocument);
 
   // Guarantee that aDocument won't be destroyed during a call of
   // StopObserving().
   RefPtr<Document> newDocument = aDocument;
 
   StopObserving();
 
-  mDocument = newDocument.forget();
+  mDocument = std::move(newDocument);
   mDocument->AddObserver(this);
 }
 
 void IMEContentObserver::DocumentObserver::StopObserving() {
   if (!IsObserving()) {
     return;
   }
 
   // Grab IMEContentObserver which could be destroyed during method calls.
-  RefPtr<IMEContentObserver> observer = mIMEContentObserver.forget();
+  RefPtr<IMEContentObserver> observer = std::move(mIMEContentObserver);
 
   // Stop observing the document first.
-  RefPtr<Document> document = mDocument.forget();
+  RefPtr<Document> document = std::move(mDocument);
   document->RemoveObserver(this);
 
   // Notify IMEContentObserver of ending of document updates if this already
   // notified it of beginning of document updates.
   for (; IsUpdating(); --mDocumentUpdating) {
     // FYI: IsUpdating() returns true until mDocumentUpdating becomes 0.
     //      However, IsObserving() returns false now because mDocument was
     //      already cleared above.  Therefore, this method won't be called
--- a/dom/fetch/FetchDriver.cpp
+++ b/dom/fetch/FetchDriver.cpp
@@ -274,17 +274,17 @@ AlternativeDataStreamListener::OnDataAva
 
 NS_IMETHODIMP
 AlternativeDataStreamListener::OnStopRequest(nsIRequest* aRequest,
                                              nsresult aStatusCode) {
   AssertIsOnMainThread();
 
   // Alternative data loading is going to finish, breaking the reference cycle
   // here by taking the ownership to a loacl variable.
-  RefPtr<FetchDriver> fetchDriver = mFetchDriver.forget();
+  RefPtr<FetchDriver> fetchDriver = std::move(mFetchDriver);
 
   if (mStatus == AlternativeDataStreamListener::CANCELED) {
     // do nothing
     return NS_OK;
   }
 
   if (mStatus == AlternativeDataStreamListener::FALLBACK) {
     MOZ_ASSERT(fetchDriver);
@@ -1201,17 +1201,17 @@ NS_IMETHODIMP
 FetchDriver::OnStopRequest(nsIRequest* aRequest, nsresult aStatusCode) {
   AssertIsOnMainThread();
 
   MOZ_DIAGNOSTIC_ASSERT(!mOnStopRequestCalled);
   mOnStopRequestCalled = true;
 
   // main data loading is going to finish, breaking the reference cycle.
   RefPtr<AlternativeDataStreamListener> altDataListener =
-      mAltDataListener.forget();
+      std::move(mAltDataListener);
 
   // We need to check mObserver, which is nulled by FailWithNetworkError(),
   // because in the case of "error" redirect mode, aStatusCode may be NS_OK but
   // mResponse will definitely be null so we must not take the else branch.
   if (NS_FAILED(aStatusCode) || !mObserver) {
     nsCOMPtr<nsIAsyncOutputStream> outputStream =
         do_QueryInterface(mPipeOutputStream);
     if (outputStream) {
--- a/dom/fetch/FetchStreamReader.cpp
+++ b/dom/fetch/FetchStreamReader.cpp
@@ -77,17 +77,17 @@ nsresult FetchStreamReader::Create(JSCon
 
     if (NS_WARN_IF(!workerRef)) {
       streamReader->mPipeOut->CloseWithStatus(NS_ERROR_DOM_INVALID_STATE_ERR);
       return NS_ERROR_DOM_INVALID_STATE_ERR;
     }
 
     // These 2 objects create a ref-cycle here that is broken when the stream is
     // closed or the worker shutsdown.
-    streamReader->mWorkerRef = workerRef.forget();
+    streamReader->mWorkerRef = std::move(workerRef);
   }
 
   pipeIn.forget(aInputStream);
   streamReader.forget(aStreamReader);
   return NS_OK;
 }
 
 FetchStreamReader::FetchStreamReader(nsIGlobalObject* aGlobal)
--- a/dom/fetch/FetchUtil.cpp
+++ b/dom/fetch/FetchUtil.cpp
@@ -268,17 +268,17 @@ class WorkerStreamOwner final {
     }
 
     return self.forget();
   }
 
   struct Destroyer final : CancelableRunnable {
     RefPtr<WorkerStreamOwner> mDoomed;
 
-    explicit Destroyer(already_AddRefed<WorkerStreamOwner>&& aDoomed)
+    explicit Destroyer(RefPtr<WorkerStreamOwner>&& aDoomed)
         : CancelableRunnable("WorkerStreamOwner::Destroyer"),
           mDoomed(std::move(aDoomed)) {}
 
     NS_IMETHOD
     Run() override {
       mDoomed = nullptr;
       return NS_OK;
     }
@@ -327,17 +327,18 @@ class JSStreamConsumer final : public ns
     // their global's event target thread.
 
     RefPtr<Runnable> destroyer;
     if (mWindowStreamOwner) {
       MOZ_DIAGNOSTIC_ASSERT(!mWorkerStreamOwner);
       destroyer = new WindowStreamOwner::Destroyer(mWindowStreamOwner.forget());
     } else {
       MOZ_DIAGNOSTIC_ASSERT(mWorkerStreamOwner);
-      destroyer = new WorkerStreamOwner::Destroyer(mWorkerStreamOwner.forget());
+      destroyer =
+          new WorkerStreamOwner::Destroyer(std::move(mWorkerStreamOwner));
     }
 
     MOZ_ALWAYS_SUCCEEDS(mOwningEventTarget->Dispatch(destroyer.forget()));
   }
 
   static nsresult WriteSegment(nsIInputStream* aStream, void* aClosure,
                                const char* aFromSegment, uint32_t aToOffset,
                                uint32_t aCount, uint32_t* aWriteCount) {
--- a/dom/file/StreamBlobImpl.cpp
+++ b/dom/file/StreamBlobImpl.cpp
@@ -72,17 +72,17 @@ void StreamBlobImpl::CreateInputStream(n
 
   aRv = NS_CloneInputStream(mInputStream, getter_AddRefs(clonedStream),
                             getter_AddRefs(replacementStream));
   if (NS_WARN_IF(aRv.Failed())) {
     return;
   }
 
   if (replacementStream) {
-    mInputStream = replacementStream.forget();
+    mInputStream = std::move(replacementStream);
   }
 
   nsCOMPtr<nsIInputStream> wrappedStream =
       InputStreamLengthWrapper::MaybeWrap(clonedStream.forget(), mLength);
 
   wrappedStream.forget(aStream);
 }
 
--- a/dom/filehandle/ActorsParent.cpp
+++ b/dom/filehandle/ActorsParent.cpp
@@ -1085,17 +1085,17 @@ void BackgroundMutableFileParentBase::In
         if (NS_WARN_IF(
                 !fileHandles.AppendElement(iter.Get()->GetKey(), fallible))) {
           return false;
         }
       }
 
       if (count) {
         for (uint32_t index = 0; index < count; index++) {
-          RefPtr<FileHandle> fileHandle = fileHandles[index].forget();
+          RefPtr<FileHandle> fileHandle = std::move(fileHandles[index]);
           MOZ_ASSERT(fileHandle);
 
           fileHandle->Invalidate();
         }
       }
 
       return true;
     }
--- a/dom/html/HTMLFormElement.cpp
+++ b/dom/html/HTMLFormElement.cpp
@@ -1669,17 +1669,17 @@ nsresult HTMLFormElement::GetActionURL(n
     rv = actionURL->GetSpec(spec);
     NS_ENSURE_SUCCESS(rv, rv);
     CopyUTF8toUTF16(spec, *params.AppendElement());
 
     // upgrade the actionURL from http:// to use https://
     nsCOMPtr<nsIURI> upgradedActionURL;
     rv = NS_GetSecureUpgradedURI(actionURL, getter_AddRefs(upgradedActionURL));
     NS_ENSURE_SUCCESS(rv, rv);
-    actionURL = upgradedActionURL.forget();
+    actionURL = std::move(upgradedActionURL);
 
     // let's log a message to the console that we are upgrading a request
     nsAutoCString scheme;
     rv = actionURL->GetScheme(scheme);
     NS_ENSURE_SUCCESS(rv, rv);
     CopyUTF8toUTF16(scheme, *params.AppendElement());
 
     CSP_LogLocalizedStr(
--- a/dom/html/HTMLMediaElement.cpp
+++ b/dom/html/HTMLMediaElement.cpp
@@ -3045,17 +3045,17 @@ MediaResult HTMLMediaElement::LoadResour
     return MediaResult(rv, "Failed to set up decoder");
   }
 
   AssertReadyStateIsNothing();
 
   RefPtr<ChannelLoader> loader = new ChannelLoader;
   nsresult rv = loader->Load(this);
   if (NS_SUCCEEDED(rv)) {
-    mChannelLoader = loader.forget();
+    mChannelLoader = std::move(loader);
   }
   return MediaResult(rv, "Failed to load channel");
 }
 
 nsresult HTMLMediaElement::LoadWithChannel(nsIChannel* aChannel,
                                            nsIStreamListener** aListener) {
   NS_ENSURE_ARG_POINTER(aChannel);
   NS_ENSURE_ARG_POINTER(aListener);
--- a/dom/html/HTMLSlotElement.cpp
+++ b/dom/html/HTMLSlotElement.cpp
@@ -10,18 +10,17 @@
 #include "mozilla/dom/HTMLSlotElementBinding.h"
 #include "mozilla/dom/HTMLUnknownElement.h"
 #include "mozilla/dom/ShadowRoot.h"
 #include "nsGkAtoms.h"
 
 nsGenericHTMLElement* NS_NewHTMLSlotElement(
     already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
     mozilla::dom::FromParser aFromParser) {
-  RefPtr<mozilla::dom::NodeInfo> nodeInfo(std::move(aNodeInfo));
-  return new mozilla::dom::HTMLSlotElement(nodeInfo.forget());
+  return new mozilla::dom::HTMLSlotElement(std::move(aNodeInfo));
 }
 
 namespace mozilla {
 namespace dom {
 
 HTMLSlotElement::HTMLSlotElement(
     already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo)
     : nsGenericHTMLElement(std::move(aNodeInfo)) {}
--- a/dom/html/nsHTMLDocument.cpp
+++ b/dom/html/nsHTMLDocument.cpp
@@ -520,17 +520,17 @@ nsresult nsHTMLDocument::StartDocumentLo
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   nsCOMPtr<nsIContentViewer> cv;
   if (docShell) {
     docShell->GetContentViewer(getter_AddRefs(cv));
   }
   if (!cv) {
-    cv = parentContentViewer.forget();
+    cv = std::move(parentContentViewer);
   }
 
   nsAutoCString urlSpec;
   uri->GetSpec(urlSpec);
 #ifdef DEBUG_charset
   printf("Determining charset for %s\n", urlSpec.get());
 #endif
 
--- a/dom/indexedDB/ActorsParent.cpp
+++ b/dom/indexedDB/ActorsParent.cpp
@@ -22493,27 +22493,27 @@ nsresult DeleteDatabaseOp::VersionChange
 
   return NS_OK;
 }
 
 TransactionDatabaseOperationBase::TransactionDatabaseOperationBase(
     RefPtr<TransactionBase> aTransaction)
     : DatabaseOperationBase(aTransaction->GetLoggingInfo()->Id(),
                             aTransaction->GetLoggingInfo()->NextRequestSN()),
-      mTransaction(aTransaction.forget()),
+      mTransaction(std::move(aTransaction)),
       mTransactionIsAborted((*mTransaction)->IsAborted()),
       mTransactionLoggingSerialNumber((*mTransaction)->LoggingSerialNumber()) {
   MOZ_ASSERT(LoggingSerialNumber());
 }
 
 TransactionDatabaseOperationBase::TransactionDatabaseOperationBase(
     RefPtr<TransactionBase> aTransaction, uint64_t aLoggingSerialNumber)
     : DatabaseOperationBase(aTransaction->GetLoggingInfo()->Id(),
                             aLoggingSerialNumber),
-      mTransaction(aTransaction.forget()),
+      mTransaction(std::move(aTransaction)),
       mTransactionIsAborted((*mTransaction)->IsAborted()),
       mTransactionLoggingSerialNumber((*mTransaction)->LoggingSerialNumber()) {}
 
 TransactionDatabaseOperationBase::~TransactionDatabaseOperationBase() {
   MOZ_ASSERT(mInternalState == InternalState::Completed);
   MOZ_ASSERT(!mTransaction,
              "TransactionDatabaseOperationBase::Cleanup() was not called by a "
              "subclass!");
--- a/dom/ipc/BrowserBridgeParent.cpp
+++ b/dom/ipc/BrowserBridgeParent.cpp
@@ -87,17 +87,17 @@ nsresult BrowserBridgeParent::InitWithPr
       aContentParent->ChildID(), aContentParent->IsForBrowser(),
       /* aIsTopLevel */ false);
   if (NS_WARN_IF(!ok)) {
     MOZ_ASSERT(false, "Browser Constructor Failed");
     return NS_ERROR_FAILURE;
   }
 
   // Set our BrowserParent object to the newly created browser.
-  mBrowserParent = browserParent.forget();
+  mBrowserParent = std::move(browserParent);
   mBrowserParent->SetOwnerElement(Manager()->GetOwnerElement());
   mBrowserParent->InitRendering();
 
   windowParent->Init(aWindowInit);
 
   // Send the newly created layers ID back into content.
   Unused << SendSetLayersId(mBrowserParent->GetLayersId());
   return NS_OK;
--- a/dom/ipc/BrowserChild.cpp
+++ b/dom/ipc/BrowserChild.cpp
@@ -3820,17 +3820,17 @@ NS_IMETHODIMP BrowserChild::OnSecurityCh
       if (nsPIDOMWindowInner* window = outerWindow->GetCurrentInnerWindow()) {
         isSecureContext = window->IsSecureContext();
       } else {
         return NS_OK;
       }
     }
 
     securityChangeData.emplace();
-    securityChangeData->securityInfo() = securityInfo.forget();
+    securityChangeData->securityInfo() = ToRefPtr(std::move(securityInfo));
     securityChangeData->isSecureContext() = isSecureContext;
   }
 
   Unused << SendOnSecurityChange(webProgressData, requestData, aState,
                                  securityChangeData);
 
   return NS_OK;
 }
--- a/dom/ipc/CSPMessageUtils.cpp
+++ b/dom/ipc/CSPMessageUtils.cpp
@@ -47,13 +47,13 @@ bool ParamTraits<nsIContentSecurityPolic
 
   nsCOMPtr<nsISupports> iSupports;
   nsresult rv = NS_DeserializeObject(cspString, getter_AddRefs(iSupports));
   NS_ENSURE_SUCCESS(rv, false);
 
   nsCOMPtr<nsIContentSecurityPolicy> csp = do_QueryInterface(iSupports);
   NS_ENSURE_TRUE(csp, false);
 
-  *aResult = csp.forget();
+  *aResult = ToRefPtr(std::move(csp));
   return true;
 }
 
 }  // namespace IPC
--- a/dom/ipc/ClonedErrorHolder.cpp
+++ b/dom/ipc/ClonedErrorHolder.cpp
@@ -75,17 +75,17 @@ void ClonedErrorHolder::Init(JSContext* 
 
     stack = JS::ExceptionStackOrNull(aError);
   } else {
     RefPtr<DOMException> domExn;
     RefPtr<Exception> exn;
     if (NS_SUCCEEDED(UNWRAP_OBJECT(DOMException, aError, domExn))) {
       mType = Type::DOMException;
       mCode = domExn->Code();
-      exn = domExn.forget();
+      exn = std::move(domExn);
     } else if (NS_SUCCEEDED(UNWRAP_OBJECT(Exception, aError, exn))) {
       mType = Type::Exception;
     } else {
       aRv.ThrowNotSupportedError(
           "We can only clone DOM Exceptions and native JS Error objects");
       return;
     }
 
--- a/dom/ipc/PermissionMessageUtils.h
+++ b/dom/ipc/PermissionMessageUtils.h
@@ -50,17 +50,17 @@ struct IPDLParamTraits<nsIPrincipal*> {
 
   // Overload to support deserializing nsCOMPtr<nsIPrincipal> directly.
   static bool Read(const IPC::Message* aMsg, PickleIterator* aIter,
                    IProtocol* aActor, nsCOMPtr<nsIPrincipal>* aResult) {
     RefPtr<nsIPrincipal> result;
     if (!Read(aMsg, aIter, aActor, &result)) {
       return false;
     }
-    *aResult = result.forget();
+    *aResult = std::move(result);
     return true;
   }
 };
 
 template <>
 struct IPDLParamTraits<IPC::Principal> {
   typedef IPC::Principal paramType;
   static void Write(IPC::Message* aMsg, IProtocol* aActor,
--- a/dom/ipc/PropertyBagUtils.cpp
+++ b/dom/ipc/PropertyBagUtils.cpp
@@ -197,17 +197,17 @@ bool IPDLParamTraits<nsIVariant*>::Read(
       variant->SetAsVoid();
       break;
     case nsIDataType::VTYPE_EMPTY:
       break;
     default:
       MOZ_CRASH("Non handled variant type, patch welcome");
       return false;
   }
-  *aResult = variant.forget();
+  *aResult = std::move(variant);
   return true;
 }
 
 void IPDLParamTraits<nsIPropertyBag2*>::Write(Message* aMsg, IProtocol* aActor,
                                               nsIPropertyBag2* aParam) {
   // We send a nsIPropertyBag as an array of IPDLProperty
   nsTArray<IPDLProperty> bag;
 
@@ -232,18 +232,18 @@ bool IPDLParamTraits<nsIPropertyBag2*>::
   nsTArray<IPDLProperty> bag;
   if (!ReadIPDLParam(aMsg, aIter, aActor, &bag)) {
     return false;
   }
 
   auto properties = MakeRefPtr<nsHashPropertyBag>();
 
   for (auto& entry : bag) {
-    nsCOMPtr<nsIVariant> variant = entry.value().forget();
+    nsCOMPtr<nsIVariant> variant = std::move(entry.value());
     MOZ_ALWAYS_SUCCEEDS(
         properties->SetProperty(std::move(entry.name()), variant));
   }
-  *aResult = properties.forget();
+  *aResult = std::move(properties);
   return true;
 }
 
 }  // namespace ipc
 }  // namespace mozilla
--- a/dom/ipc/ReferrerInfoUtils.cpp
+++ b/dom/ipc/ReferrerInfoUtils.cpp
@@ -40,13 +40,13 @@ bool ParamTraits<nsIReferrerInfo*>::Read
   if (!ReadParam(aMsg, aIter, &infoString)) {
     return false;
   }
   nsCOMPtr<nsISupports> iSupports;
   nsresult rv = NS_DeserializeObject(infoString, getter_AddRefs(iSupports));
   NS_ENSURE_SUCCESS(rv, false);
   nsCOMPtr<nsIReferrerInfo> referrerInfo = do_QueryInterface(iSupports);
   NS_ENSURE_TRUE(referrerInfo, false);
-  *aResult = referrerInfo.forget();
+  *aResult = ToRefPtr(std::move(referrerInfo));
   return true;
 }
 
 }  // namespace IPC
--- a/dom/localstorage/ActorsParent.cpp
+++ b/dom/localstorage/ActorsParent.cpp
@@ -1713,20 +1713,19 @@ class Datastore final
   int64_t mSizeOfItems;
   bool mClosed;
   bool mInUpdateBatch;
 
  public:
   // Created by PrepareDatastoreOp.
   Datastore(const nsACString& aGroup, const nsACString& aOrigin,
             uint32_t aPrivateBrowsingId, int64_t aUsage, int64_t aSizeOfKeys,
-            int64_t aSizeOfItems,
-            already_AddRefed<DirectoryLock>&& aDirectoryLock,
-            already_AddRefed<Connection>&& aConnection,
-            already_AddRefed<QuotaObject>&& aQuotaObject,
+            int64_t aSizeOfItems, RefPtr<DirectoryLock>&& aDirectoryLock,
+            RefPtr<Connection>&& aConnection,
+            RefPtr<QuotaObject>&& aQuotaObject,
             nsDataHashtable<nsStringHashKey, LSValue>& aValues,
             nsTArray<LSItemInfo>& aOrderedItems);
 
   const nsCString& Origin() const { return mOrigin; }
 
   uint32_t PrivateBrowsingId() const { return mPrivateBrowsingId; }
 
   bool IsPersistent() const {
@@ -4763,19 +4762,19 @@ void ConnectionThread::Shutdown() {
 
 /*******************************************************************************
  * Datastore
  ******************************************************************************/
 
 Datastore::Datastore(const nsACString& aGroup, const nsACString& aOrigin,
                      uint32_t aPrivateBrowsingId, int64_t aUsage,
                      int64_t aSizeOfKeys, int64_t aSizeOfItems,
-                     already_AddRefed<DirectoryLock>&& aDirectoryLock,
-                     already_AddRefed<Connection>&& aConnection,
-                     already_AddRefed<QuotaObject>&& aQuotaObject,
+                     RefPtr<DirectoryLock>&& aDirectoryLock,
+                     RefPtr<Connection>&& aConnection,
+                     RefPtr<QuotaObject>&& aQuotaObject,
                      nsDataHashtable<nsStringHashKey, LSValue>& aValues,
                      nsTArray<LSItemInfo>& aOrderedItems)
     : mDirectoryLock(std::move(aDirectoryLock)),
       mConnection(std::move(aConnection)),
       mQuotaObject(std::move(aQuotaObject)),
       mGroup(aGroup),
       mOrigin(aOrigin),
       mPrivateBrowsingId(aPrivateBrowsingId),
@@ -7193,17 +7192,17 @@ nsresult PrepareDatastoreOp::OpenDirecto
   RefPtr<DirectoryLock> pendingDirectoryLock =
       QuotaManager::Get()->CreateDirectoryLock(PERSISTENCE_TYPE_DEFAULT, mGroup,
                                                mOrigin,
                                                mozilla::dom::quota::Client::LS,
                                                /* aExclusive */ false, this);
   MOZ_ASSERT(pendingDirectoryLock);
 
   if (mNestedState == NestedState::DirectoryOpenPending) {
-    mPendingDirectoryLock = pendingDirectoryLock.forget();
+    mPendingDirectoryLock = std::move(pendingDirectoryLock);
   }
 
   mRequestedDirectoryLock = true;
 
   return NS_OK;
 }
 
 void PrepareDatastoreOp::SendToIOThread() {
@@ -7863,20 +7862,20 @@ void PrepareDatastoreOp::GetResponse(LSR
 
       quotaObject = GetQuotaObject();
       if (!quotaObject) {
         aResponse = NS_ERROR_FAILURE;
         return;
       }
     }
 
-    mDatastore = new Datastore(mGroup, mOrigin, mPrivateBrowsingId, mUsage,
-                               mSizeOfKeys, mSizeOfItems,
-                               mDirectoryLock.forget(), mConnection.forget(),
-                               quotaObject.forget(), mValues, mOrderedItems);
+    mDatastore = new Datastore(
+        mGroup, mOrigin, mPrivateBrowsingId, mUsage, mSizeOfKeys, mSizeOfItems,
+        std::move(mDirectoryLock), std::move(mConnection),
+        std::move(quotaObject), mValues, mOrderedItems);
 
     mDatastore->NoteLivePrepareDatastoreOp(this);
 
     if (!gDatastores) {
       gDatastores = new DatastoreHashtable();
     }
 
     MOZ_ASSERT(!gDatastores->Get(mOrigin));
--- a/dom/media/AudioSegment.h
+++ b/dom/media/AudioSegment.h
@@ -392,17 +392,17 @@ class AudioSegment : public MediaSegment
     }
     chunk->mBufferFormat = AUDIO_FORMAT_S16;
     chunk->mPrincipalHandle = aPrincipalHandle;
   }
   // Consumes aChunk, and returns a pointer to the persistent copy of aChunk
   // in the segment.
   AudioChunk* AppendAndConsumeChunk(AudioChunk* aChunk) {
     AudioChunk* chunk = AppendChunk(aChunk->mDuration);
-    chunk->mBuffer = aChunk->mBuffer.forget();
+    chunk->mBuffer = std::move(aChunk->mBuffer);
     chunk->mChannelData.SwapElements(aChunk->mChannelData);
 
     MOZ_ASSERT(chunk->mBuffer || aChunk->mChannelData.IsEmpty(),
                "Appending invalid data ?");
 
     chunk->mVolume = aChunk->mVolume;
     chunk->mBufferFormat = aChunk->mBufferFormat;
     chunk->mPrincipalHandle = aChunk->mPrincipalHandle;
--- a/dom/media/CanvasCaptureMediaStream.cpp
+++ b/dom/media/CanvasCaptureMediaStream.cpp
@@ -41,25 +41,25 @@ OutputStreamDriver::~OutputStreamDriver(
 
 void OutputStreamDriver::EndTrack() {
   MOZ_ASSERT(NS_IsMainThread());
   if (!mSourceStream->IsDestroyed()) {
     mSourceStream->Destroy();
   }
 }
 
-void OutputStreamDriver::SetImage(const RefPtr<layers::Image>& aImage,
+void OutputStreamDriver::SetImage(RefPtr<layers::Image>&& aImage,
                                   const TimeStamp& aTime) {
   MOZ_ASSERT(NS_IsMainThread());
 
   TRACE_COMMENT("SourceMediaTrack %p", mSourceStream.get());
 
   VideoSegment segment;
-  segment.AppendFrame(do_AddRef(aImage), aImage->GetSize(), mPrincipalHandle,
-                      false, aTime);
+  const auto size = aImage->GetSize();
+  segment.AppendFrame(aImage.forget(), size, mPrincipalHandle, false, aTime);
   mSourceStream->AppendData(&segment);
 }
 
 // ----------------------------------------------------------------------
 
 class TimerDriver : public OutputStreamDriver {
  public:
   explicit TimerDriver(SourceMediaTrack* aSourceStream, const double& aFPS,
@@ -87,17 +87,17 @@ class TimerDriver : public OutputStreamD
                 const TimeStamp& aTime) override {
     RefPtr<Image> image = aImage;
 
     if (!mFrameCaptureRequested) {
       return;
     }
 
     mFrameCaptureRequested = false;
-    SetImage(image.forget(), aTime);
+    SetImage(std::move(image), aTime);
   }
 
   void Forget() override {
     if (mTimer) {
       mTimer->Cancel();
       mTimer = nullptr;
     }
   }
@@ -121,17 +121,17 @@ class AutoDriver : public OutputStreamDr
   void NewFrame(already_AddRefed<Image> aImage,
                 const TimeStamp& aTime) override {
     // Don't reset `mFrameCaptureRequested` since AutoDriver shall always have
     // `mFrameCaptureRequested` set to true.
     // This also means we should accept every frame as NewFrame is called only
     // after something changed.
 
     RefPtr<Image> image = aImage;
-    SetImage(image.forget(), aTime);
+    SetImage(std::move(image), aTime);
   }
 
  protected:
   virtual ~AutoDriver() {}
 };
 
 // ----------------------------------------------------------------------
 
--- a/dom/media/CanvasCaptureMediaStream.h
+++ b/dom/media/CanvasCaptureMediaStream.h
@@ -65,17 +65,17 @@ class OutputStreamDriver : public FrameC
                      const PrincipalHandle& aPrincipalHandle);
 
   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(OutputStreamDriver);
 
   /*
    * Sub classes can SetImage() to update the image being appended to the
    * output stream. It will be appended on the next NotifyPull from MTG.
    */
-  void SetImage(const RefPtr<layers::Image>& aImage, const TimeStamp& aTime);
+  void SetImage(RefPtr<layers::Image>&& aImage, const TimeStamp& aTime);
 
   /*
    * Ends the track in mSourceStream when we know there won't be any more images
    * requested for it.
    */
   void EndTrack();
 
   /*
--- a/dom/media/MediaCache.cpp
+++ b/dom/media/MediaCache.cpp
@@ -769,17 +769,17 @@ RefPtr<MediaCache> MediaCache::GetMediaC
   if (!sThreadInit) {
     sThreadInit = true;
     nsCOMPtr<nsIThread> thread;
     nsresult rv = NS_NewNamedThread("MediaCache", getter_AddRefs(thread));
     if (NS_FAILED(rv)) {
       NS_WARNING("Failed to create a thread for MediaCache.");
       return nullptr;
     }
-    sThread = thread.forget();
+    sThread = ToRefPtr(std::move(thread));
 
     static struct ClearThread {
       // Called during shutdown to clear sThread.
       void operator=(std::nullptr_t) {
         nsCOMPtr<nsIThread> thread = sThread.forget();
         MOZ_ASSERT(thread);
         thread->Shutdown();
       }
--- a/dom/media/MediaDecoderStateMachine.cpp
+++ b/dom/media/MediaDecoderStateMachine.cpp
@@ -1694,17 +1694,17 @@ class MediaDecoderStateMachine::VideoOnl
 
     RefPtr<MediaDecoder::SeekPromise> p =
         AccurateSeekingState::Enter(std::move(aSeekJob), aVisibility);
 
     // Dispatch a mozvideoonlyseekbegin event to indicate UI for corresponding
     // changes.
     mMaster->mOnPlaybackEvent.Notify(MediaPlaybackEvent::VideoOnlySeekBegin);
 
-    return p.forget();
+    return p;
   }
 
   void Exit() override {
     // We are completing or discarding this video-only seek operation now,
     // dispatch an event so that the UI can change in response to the end
     // of video-only seek.
     mMaster->mOnPlaybackEvent.Notify(
         MediaPlaybackEvent::VideoOnlySeekCompleted);
@@ -3762,17 +3762,17 @@ RefPtr<GenericPromise> MediaDecoderState
       NS_NewRunnableFunction("MediaDecoderStateMachine::RequestDebugInfo",
                              [self, p, &aInfo]() {
                                self->GetDebugInfo(aInfo);
                                p->Resolve(true, __func__);
                              }),
       AbstractThread::TailDispatch);
   MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
   Unused << rv;
-  return p.forget();
+  return p;
 }
 
 class VideoQueueMemoryFunctor : public nsDequeFunctor {
  public:
   VideoQueueMemoryFunctor() : mSize(0) {}
 
   MOZ_DEFINE_MALLOC_SIZE_OF(MallocSizeOf);
 
--- a/dom/media/MediaFormatReader.cpp
+++ b/dom/media/MediaFormatReader.cpp
@@ -261,17 +261,17 @@ void MediaFormatReader::DecoderFactory::
   switch (aData.mStage) {
     case Stage::None: {
       MOZ_ASSERT(!aData.mToken);
       aData.mPolicy->Alloc()
           ->Then(
               mOwner->OwnerThread(), __func__,
               [this, &aData](RefPtr<Token> aToken) {
                 aData.mTokenRequest.Complete();
-                aData.mToken = aToken.forget();
+                aData.mToken = std::move(aToken);
                 aData.mStage = Stage::CreateDecoder;
                 RunStage(aData);
               },
               [&aData]() {
                 aData.mTokenRequest.Complete();
                 aData.mStage = Stage::None;
               })
           ->Track(aData.mTokenRequest);
@@ -403,17 +403,17 @@ void MediaFormatReader::DecoderFactory::
            "initialize_decoder", DDNoValue{});
   aData.mDecoder->Init()
       ->Then(
           mOwner->OwnerThread(), __func__,
           [this, &aData, &ownerData](TrackType aTrack) {
             aData.mInitRequest.Complete();
             aData.mStage = Stage::None;
             MutexAutoLock lock(ownerData.mMutex);
-            ownerData.mDecoder = aData.mDecoder.forget();
+            ownerData.mDecoder = std::move(aData.mDecoder);
             ownerData.mDescription = ownerData.mDecoder->GetDescriptionName();
             DDLOGEX2("MediaFormatReader::DecoderFactory", this,
                      DDLogCategory::Log, "decoder_initialized", DDNoValue{});
             DecoderDoctorLogger::LinkParentAndChild(
                 "MediaFormatReader::DecoderData", &ownerData, "decoder",
                 ownerData.mDecoder.get());
             mOwner->SetVideoDecodeThreshold();
             mOwner->ScheduleUpdate(aTrack);
@@ -451,17 +451,17 @@ class MediaFormatReader::DemuxerProxy {
                           "DemuxerProxy::mTaskQueue")),
         mData(new Data(aDemuxer)) {
     MOZ_COUNT_CTOR(DemuxerProxy);
   }
 
   ~DemuxerProxy() { MOZ_COUNT_DTOR(DemuxerProxy); }
 
   RefPtr<ShutdownPromise> Shutdown() {
-    RefPtr<Data> data = mData.forget();
+    RefPtr<Data> data = std::move(mData);
     return InvokeAsync(mTaskQueue, __func__, [data]() {
       // We need to clear our reference to the demuxer now. So that in the event
       // the init promise wasn't resolved, such as what can happen with the
       // mediasource demuxer that is waiting on more data, it will force the
       // init promise to be rejected.
       data->mDemuxer = nullptr;
       data->mAudioDemuxer = nullptr;
       data->mVideoDemuxer = nullptr;
@@ -671,17 +671,17 @@ class MediaFormatReader::DemuxerProxy::W
   RefPtr<MediaTrackDemuxer> mTrackDemuxer;
   // All following members are protected by mMutex
   nsresult mNextRandomAccessPointResult = NS_OK;
   TimeUnit mNextRandomAccessPoint;
   TimeIntervals mBuffered;
   friend class DemuxerProxy;
 
   ~Wrapper() {
-    RefPtr<MediaTrackDemuxer> trackDemuxer = mTrackDemuxer.forget();
+    RefPtr<MediaTrackDemuxer> trackDemuxer = std::move(mTrackDemuxer);
     nsresult rv = mTaskQueue->Dispatch(NS_NewRunnableFunction(
         "MediaFormatReader::DemuxerProxy::Wrapper::~Wrapper",
         [trackDemuxer]() { trackDemuxer->BreakCycles(); }));
     MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
     Unused << rv;
     DecoderDoctorLogger::LogDestruction(
         "MediaFormatReader::DemuxerProxy::Wrapper", this);
   }
--- a/dom/media/MediaRecorder.cpp
+++ b/dom/media/MediaRecorder.cpp
@@ -1965,28 +1965,28 @@ void MediaRecorder::NotifyError(nsresult
   // exceptions here, but defensively check.
   switch (aRv) {
     case NS_ERROR_DOM_SECURITY_ERR:
       if (!mSecurityDomException) {
         LOG(LogLevel::Debug, ("MediaRecorder.NotifyError: "
                               "mSecurityDomException was not initialized"));
         mSecurityDomException = DOMException::Create(NS_ERROR_DOM_SECURITY_ERR);
       }
-      init.mError = mSecurityDomException.forget();
+      init.mError = std::move(mSecurityDomException);
       break;
     default:
       if (!mUnknownDomException) {
         LOG(LogLevel::Debug, ("MediaRecorder.NotifyError: "
                               "mUnknownDomException was not initialized"));
         mUnknownDomException = DOMException::Create(NS_ERROR_DOM_UNKNOWN_ERR);
       }
       LOG(LogLevel::Debug, ("MediaRecorder.NotifyError: "
                             "mUnknownDomException being fired for aRv: %X",
                             uint32_t(aRv)));
-      init.mError = mUnknownDomException.forget();
+      init.mError = std::move(mUnknownDomException);
   }
 
   RefPtr<MediaRecorderErrorEvent> event = MediaRecorderErrorEvent::Constructor(
       this, NS_LITERAL_STRING("error"), init);
   event->SetTrusted(true);
 
   IgnoredErrorResult res;
   DispatchEvent(*event, res);
--- a/dom/media/MediaShutdownManager.cpp
+++ b/dom/media/MediaShutdownManager.cpp
@@ -54,17 +54,17 @@ static nsCOMPtr<nsIAsyncShutdownClient> 
   nsresult rv = svc->GetProfileBeforeChange(getter_AddRefs(barrier));
   if (!barrier) {
     // We are probably in a content process. We need to do cleanup at
     // XPCOM shutdown in leakchecking builds.
     rv = svc->GetXpcomWillShutdown(getter_AddRefs(barrier));
   }
   MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv));
   MOZ_RELEASE_ASSERT(barrier);
-  return barrier.forget();
+  return barrier;
 }
 
 void MediaShutdownManager::InitStatics() {
   MOZ_ASSERT(NS_IsMainThread());
   if (sInitPhase != NotInited) {
     return;
   }
 
--- a/dom/media/VideoSegment.cpp
+++ b/dom/media/VideoSegment.cpp
@@ -31,17 +31,17 @@ VideoFrame::~VideoFrame() {}
 
 void VideoFrame::SetNull() {
   mImage = nullptr;
   mIntrinsicSize = gfx::IntSize(0, 0);
   mPrincipalHandle = PRINCIPAL_HANDLE_NONE;
 }
 
 void VideoFrame::TakeFrom(VideoFrame* aFrame) {
-  mImage = aFrame->mImage.forget();
+  mImage = std::move(aFrame->mImage);
   mIntrinsicSize = aFrame->mIntrinsicSize;
   mForceBlack = aFrame->GetForceBlack();
   mPrincipalHandle = aFrame->mPrincipalHandle;
 }
 
 /* static */
 already_AddRefed<Image> VideoFrame::CreateBlackImage(
     const gfx::IntSize& aSize) {
--- a/dom/media/VideoUtils.h
+++ b/dom/media/VideoUtils.h
@@ -287,17 +287,17 @@ RefPtr<GenericPromise> InvokeUntil(Work 
               Iteration(aPromise, aLocalWork, aLocalCondition);
             });
         AbstractThread::GetCurrent()->Dispatch(r.forget());
       }
     }
   };
 
   Helper::Iteration(p, aWork, aCondition);
-  return p.forget();
+  return p;
 }
 
 // Simple timer to run a runnable after a timeout.
 class SimpleTimer : public nsITimerCallback, public nsINamed {
  public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSINAMED
 
--- a/dom/media/gmp/CDMStorageIdProvider.cpp
+++ b/dom/media/gmp/CDMStorageIdProvider.cpp
@@ -27,17 +27,16 @@ nsCString CDMStorageIdProvider::ComputeS
     GMP_LOG_DEBUG(
         "CDMStorageIdProvider::ComputeStorageId: get machineId failed.");
     return EmptyCString();
   }
 
   std::string originSalt(aOriginSalt.BeginReading(), aOriginSalt.Length());
   std::string input =
       machineId + originSalt + CDMStorageIdProvider::kBrowserIdentifier;
-  nsAutoCString storageId;
   nsresult rv;
   nsCOMPtr<nsICryptoHash> hasher =
       do_CreateInstance("@mozilla.org/security/hash;1", &rv);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     GMP_LOG_DEBUG(
         "CDMStorageIdProvider::ComputeStorageId: no crypto hash(0x%08" PRIx32
         ")",
         static_cast<uint32_t>(rv));
@@ -58,21 +57,22 @@ nsCString CDMStorageIdProvider::ComputeS
   if (NS_WARN_IF(NS_FAILED(rv))) {
     GMP_LOG_DEBUG(
         "CDMStorageIdProvider::ComputeStorageId: failed to update "
         "hash(0x%08" PRIx32 ")",
         static_cast<uint32_t>(rv));
     return EmptyCString();
   }
 
+  nsCString storageId;
   rv = hasher->Finish(false, storageId);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     GMP_LOG_DEBUG(
         "CDMStorageIdProvider::ComputeStorageId: failed to get the final hash "
         "result(0x%08" PRIx32 ")",
         static_cast<uint32_t>(rv));
     return EmptyCString();
   }
-  return std::move(storageId);
+  return storageId;
 #endif
 }
 
 }  // namespace mozilla
\ No newline at end of file
--- a/dom/media/gmp/GMPService.cpp
+++ b/dom/media/gmp/GMPService.cpp
@@ -63,17 +63,17 @@ class GMPServiceCreateHelper final : pub
     } else {
       RefPtr<GMPServiceCreateHelper> createHelper =
           new GMPServiceCreateHelper();
 
       mozilla::SyncRunnable::DispatchToThread(
           SystemGroup::EventTargetFor(mozilla::TaskCategory::Other),
           createHelper, true);
 
-      service = createHelper->mService.forget();
+      service = std::move(createHelper->mService);
     }
 
     return service.forget();
   }
 
  private:
   GMPServiceCreateHelper() : Runnable("GMPServiceCreateHelper") {}
 
--- a/dom/media/gmp/GMPServiceParent.cpp
+++ b/dom/media/gmp/GMPServiceParent.cpp
@@ -1504,17 +1504,17 @@ static nsCOMPtr<nsIAsyncShutdownClient> 
   nsCOMPtr<nsIAsyncShutdownService> svc = services::GetAsyncShutdown();
   MOZ_RELEASE_ASSERT(svc);
 
   nsCOMPtr<nsIAsyncShutdownClient> barrier;
   nsresult rv = svc->GetXpcomWillShutdown(getter_AddRefs(barrier));
 
   MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv));
   MOZ_RELEASE_ASSERT(barrier);
-  return barrier.forget();
+  return barrier;
 }
 
 NS_IMETHODIMP
 GeckoMediaPluginServiceParent::GetName(nsAString& aName) {
   aName = NS_LITERAL_STRING("GeckoMediaPluginServiceParent: shutdown");
   return NS_OK;
 }
 
--- a/dom/media/ipc/RemoteMediaDataDecoder.cpp
+++ b/dom/media/ipc/RemoteMediaDataDecoder.cpp
@@ -87,17 +87,17 @@ RefPtr<ShutdownPromise> RemoteMediaDataD
       [self]() {
         RefPtr<ShutdownPromise> p = self->mChild->Shutdown();
 
         // We're about to be destroyed and drop our ref to
         // *DecoderChild. Make sure we put a ref into the
         // task queue for the *DecoderChild thread to keep
         // it alive until we send the delete message.
         p->Then(RemoteDecoderManagerChild::GetManagerThread(), __func__,
-                [child = RefPtr<IRemoteDecoderChild>(self->mChild.forget())](
+                [child = std::move(self->mChild)](
                     const ShutdownPromise::ResolveOrRejectValue& aValue) {
                   MOZ_ASSERT(aValue.IsResolve());
                   child->DestroyIPDL();
                   return ShutdownPromise::CreateAndResolveOrReject(aValue,
                                                                    __func__);
                 });
         return p;
       });
--- a/dom/media/platforms/AllocationPolicy.cpp
+++ b/dom/media/platforms/AllocationPolicy.cpp
@@ -41,40 +41,40 @@ auto AllocPolicyImpl::Alloc() -> RefPtr<
   // No decoder limit set.
   if (mDecoderLimit < 0) {
     return Promise::CreateAndResolve(new Token(), __func__);
   }
 
   RefPtr<PromisePrivate> p = new PromisePrivate(__func__);
   mPromises.push(p);
   ResolvePromise(mon);
-  return p.forget();
+  return p;
 }
 
 void AllocPolicyImpl::Dealloc() {
   ReentrantMonitorAutoEnter mon(mMonitor);
   ++mDecoderLimit;
   ResolvePromise(mon);
 }
 
 void AllocPolicyImpl::ResolvePromise(ReentrantMonitorAutoEnter& aProofOfLock) {
   MOZ_ASSERT(mDecoderLimit >= 0);
 
   if (mDecoderLimit > 0 && !mPromises.empty()) {
     --mDecoderLimit;
-    RefPtr<PromisePrivate> p = mPromises.front().forget();
+    RefPtr<PromisePrivate> p = std::move(mPromises.front());
     mPromises.pop();
     p->Resolve(new AutoDeallocToken(this), __func__);
   }
 }
 
 void AllocPolicyImpl::RejectAll() {
   ReentrantMonitorAutoEnter mon(mMonitor);
   while (!mPromises.empty()) {
-    RefPtr<PromisePrivate> p = mPromises.front().forget();
+    RefPtr<PromisePrivate> p = std::move(mPromises.front());
     mPromises.pop();
     p->Reject(true, __func__);
   }
 }
 
 static int32_t MediaDecoderLimitDefault() {
 #ifdef MOZ_WIDGET_ANDROID
   if (jni::GetAPIVersion() < 18) {
@@ -132,17 +132,17 @@ class SingleAllocPolicy::AutoDeallocComb
 
 auto SingleAllocPolicy::Alloc() -> RefPtr<Promise> {
   MOZ_DIAGNOSTIC_ASSERT(MaxDecoderLimit() == 1,
                         "We can only handle at most one token out at a time.");
   RefPtr<SingleAllocPolicy> self = this;
   return AllocPolicyImpl::Alloc()->Then(
       mOwnerThread, __func__,
       [self](RefPtr<Token> aToken) {
-        RefPtr<Token> localToken = aToken.forget();
+        RefPtr<Token> localToken = std::move(aToken);
         RefPtr<Promise> p = self->mPendingPromise.Ensure(__func__);
         GlobalAllocPolicy::Instance(self->mTrack)
             ->Alloc()
             ->Then(
                 self->mOwnerThread, __func__,
                 [self, localToken = std::move(localToken)](
                     RefPtr<Token> aToken) mutable {
                   self->mTokenRequest.Complete();
@@ -181,18 +181,18 @@ AllocationWrapper::AllocationWrapper(
                                           mDecoder.get());
 }
 
 AllocationWrapper::~AllocationWrapper() {
   DecoderDoctorLogger::LogDestruction("AllocationWrapper", this);
 }
 
 RefPtr<ShutdownPromise> AllocationWrapper::Shutdown() {
-  RefPtr<MediaDataDecoder> decoder = mDecoder.forget();
-  RefPtr<Token> token = mToken.forget();
+  RefPtr<MediaDataDecoder> decoder = std::move(mDecoder);
+  RefPtr<Token> token = std::move(mToken);
   return decoder->Shutdown()->Then(
       AbstractThread::GetCurrent(), __func__,
       [token]() { return ShutdownPromise::CreateAndResolve(true, __func__); });
 }
 /* static */ RefPtr<AllocationWrapper::AllocateDecoderPromise>
 AllocationWrapper::CreateDecoder(const CreateDecoderParams& aParams,
                                  AllocPolicy* aPolicy) {
   // aParams.mConfig is guaranteed to stay alive during the lifetime of the
--- a/dom/media/platforms/PDMFactory.cpp
+++ b/dom/media/platforms/PDMFactory.cpp
@@ -289,17 +289,17 @@ already_AddRefed<MediaDataDecoder> PDMFa
       !aParams.mUseNullDecoder.mUse && !aParams.mNoWrapper.mDontUseWrapper) {
     RefPtr<MediaChangeMonitor> h = new MediaChangeMonitor(aPDM, aParams);
     const MediaResult result = h->GetLastError();
     if (NS_SUCCEEDED(result) || result == NS_ERROR_NOT_INITIALIZED) {
       // The MediaChangeMonitor either successfully created the wrapped decoder,
       // or there wasn't enough initialization data to do so (such as what can
       // happen with AVC3). Otherwise, there was some problem, for example WMF
       // DLLs were missing.
-      m = h.forget();
+      m = std::move(h);
     } else if (aParams.mError) {
       *aParams.mError = result;
     }
   } else {
     m = aPDM->CreateVideoDecoder(aParams);
   }
 
   return m.forget();
--- a/dom/media/platforms/agnostic/eme/EMEDecoderModule.cpp
+++ b/dom/media/platforms/agnostic/eme/EMEDecoderModule.cpp
@@ -248,17 +248,17 @@ class EMEDecryptor : public MediaDataDec
 
   RefPtr<ShutdownPromise> Shutdown() override {
     RefPtr<EMEDecryptor> self = this;
     return InvokeAsync(mTaskQueue, __func__, [self, this]() {
       MOZ_ASSERT(!mIsShutdown);
       mIsShutdown = true;
       mSamplesWaitingForKey->BreakCycles();
       mSamplesWaitingForKey = nullptr;
-      RefPtr<MediaDataDecoder> decoder = mDecoder.forget();
+      RefPtr<MediaDataDecoder> decoder = std::move(mDecoder);
       mProxy = nullptr;
       return decoder->Shutdown();
     });
   }
 
   nsCString GetDescriptionName() const override {
     return mDecoder->GetDescriptionName();
   }
--- a/dom/media/platforms/wrappers/MediaChangeMonitor.cpp
+++ b/dom/media/platforms/wrappers/MediaChangeMonitor.cpp
@@ -407,29 +407,29 @@ RefPtr<ShutdownPromise> MediaChangeMonit
     mDrainRequest.DisconnectIfExists();
     mFlushRequest.DisconnectIfExists();
     mFlushPromise.RejectIfExists(NS_ERROR_DOM_MEDIA_CANCELED, __func__);
     mShutdownRequest.DisconnectIfExists();
 
     if (mShutdownPromise) {
       // We have a shutdown in progress, return that promise instead as we can't
       // shutdown a decoder twice.
-      RefPtr<ShutdownPromise> p = mShutdownPromise.forget();
+      RefPtr<ShutdownPromise> p = std::move(mShutdownPromise);
       return p;
     }
     return ShutdownDecoder();
   });
 }
 
 RefPtr<ShutdownPromise> MediaChangeMonitor::ShutdownDecoder() {
   RefPtr<MediaChangeMonitor> self = this;
   return InvokeAsync(mTaskQueue, __func__, [self, this]() {
     mConversionRequired.reset();
     if (mDecoder) {
-      RefPtr<MediaDataDecoder> decoder = mDecoder.forget();
+      RefPtr<MediaDataDecoder> decoder = std::move(mDecoder);
       return decoder->Shutdown();
     }
     return ShutdownPromise::CreateAndResolve(true, __func__);
   });
 }
 
 bool MediaChangeMonitor::IsHardwareAccelerated(
     nsACString& aFailureReason) const {
--- a/dom/media/webaudio/AudioBlock.cpp
+++ b/dom/media/webaudio/AudioBlock.cpp
@@ -153,14 +153,14 @@ void AudioBlock::AllocateChannels(uint32
     }
   }
 
   RefPtr<AudioBlockBuffer> buffer = AudioBlockBuffer::Create(aChannelCount);
   mChannelData.SetLength(aChannelCount);
   for (uint32_t i = 0; i < aChannelCount; ++i) {
     mChannelData[i] = buffer->ChannelData(i);
   }
-  mBuffer = buffer.forget();
+  mBuffer = std::move(buffer);
   mVolume = 1.0f;
   mBufferFormat = AUDIO_FORMAT_FLOAT32;
 }
 
 }  // namespace mozilla
--- a/dom/media/webaudio/AudioBuffer.cpp
+++ b/dom/media/webaudio/AudioBuffer.cpp
@@ -204,17 +204,17 @@ void AudioBuffer::ClearJSChannels() { mJ
 void AudioBuffer::SetSharedChannels(
     already_AddRefed<ThreadSharedFloatArrayBufferList> aBuffer) {
   RefPtr<ThreadSharedFloatArrayBufferList> buffer = aBuffer;
   uint32_t channelCount = buffer->GetChannels();
   mSharedChannels.mChannelData.SetLength(channelCount);
   for (uint32_t i = 0; i < channelCount; ++i) {
     mSharedChannels.mChannelData[i] = buffer->GetData(i);
   }
-  mSharedChannels.mBuffer = buffer.forget();
+  mSharedChannels.mBuffer = std::move(buffer);
   mSharedChannels.mBufferFormat = AUDIO_FORMAT_FLOAT32;
 }
 
 /* static */
 already_AddRefed<AudioBuffer> AudioBuffer::Create(
     nsPIDOMWindowInner* aWindow, uint32_t aNumberOfChannels, uint32_t aLength,
     float aSampleRate,
     already_AddRefed<ThreadSharedFloatArrayBufferList> aInitialContents,
--- a/dom/media/webaudio/AudioNode.cpp
+++ b/dom/media/webaudio/AudioNode.cpp
@@ -163,29 +163,29 @@ void AudioNode::DisconnectFromGraph() {
     size_t i = mInputNodes.Length() - 1;
     RefPtr<AudioNode> input = mInputNodes[i].mInputNode;
     mInputNodes.RemoveElementAt(i);
     input->mOutputNodes.RemoveElement(this);
   }
 
   while (!mOutputNodes.IsEmpty()) {
     size_t i = mOutputNodes.Length() - 1;
-    RefPtr<AudioNode> output = mOutputNodes[i].forget();
+    RefPtr<AudioNode> output = std::move(mOutputNodes[i]);
     mOutputNodes.RemoveElementAt(i);
     size_t inputIndex = FindIndexOfNode(output->mInputNodes, this);
     // It doesn't matter which one we remove, since we're going to remove all
     // entries for this node anyway.
     output->mInputNodes.RemoveElementAt(inputIndex);
     // This effects of this connection will remain.
     output->NotifyHasPhantomInput();
   }
 
   while (!mOutputParams.IsEmpty()) {
     size_t i = mOutputParams.Length() - 1;
-    RefPtr<AudioParam> output = mOutputParams[i].forget();
+    RefPtr<AudioParam> output = std::move(mOutputParams[i]);
     mOutputParams.RemoveElementAt(i);
     size_t inputIndex = FindIndexOfNode(output->InputNodes(), this);
     // It doesn't matter which one we remove, since we're going to remove all
     // entries for this node anyway.
     output->RemoveInputNode(inputIndex);
   }
 
   DestroyMediaTrack();
@@ -331,17 +331,17 @@ bool AudioNode::DisconnectFromOutputIfCo
   InputNode& input = destination->mInputNodes[aInputIndex];
   if (input.mInputNode != this) {
     return false;
   }
 
   // Remove one instance of 'dest' from mOutputNodes. There could be
   // others, and it's not correct to remove them all since some of them
   // could be for different output ports.
-  RefPtr<AudioNode> output = mOutputNodes[aOutputNodeIndex].forget();
+  RefPtr<AudioNode> output = std::move(mOutputNodes[aOutputNodeIndex]);
   mOutputNodes.RemoveElementAt(aOutputNodeIndex);
   // Destroying the InputNode here sends a message to the graph thread
   // to disconnect the tracks, which should be sent before the
   // RunAfterPendingUpdates() call below.
   destination->mInputNodes.RemoveElementAt(aInputIndex);
   output->NotifyInputsChanged();
   if (mTrack) {
     nsCOMPtr<nsIRunnable> runnable = new RunnableRelease(output.forget());
--- a/dom/media/webaudio/MediaBufferDecoder.cpp
+++ b/dom/media/webaudio/MediaBufferDecoder.cpp
@@ -499,17 +499,17 @@ void MediaDecodeTask::FinishDecode() {
     return;
   }
   auto data = static_cast<AudioDataValue*>(floatBuffer->Data());
   for (uint32_t i = 0; i < channelCount; ++i) {
     mDecodeJob.mBuffer.mChannelData[i] = data;
     data += resampledFrames;
   }
 #endif
-  mDecodeJob.mBuffer.mBuffer = buffer.forget();
+  mDecodeJob.mBuffer.mBuffer = std::move(buffer);
   mDecodeJob.mBuffer.mVolume = 1.0f;
   mDecodeJob.mBuffer.mBufferFormat = AUDIO_OUTPUT_FORMAT;
 
   uint32_t writeIndex = 0;
   RefPtr<AudioData> audioData;
   while ((audioData = mAudioQueue.PopFront())) {
     audioData->EnsureAudioBuffer();  // could lead to a copy :(
     const AudioDataValue* bufferData =
--- a/dom/media/webm/NesteggPacketHolder.h
+++ b/dom/media/webm/NesteggPacketHolder.h
@@ -109,17 +109,17 @@ class WebMPacketQueue {
 
   void Push(NesteggPacketHolder* aItem) { mQueue.push_back(aItem); }
 
   void PushFront(NesteggPacketHolder* aItem) {
     mQueue.push_front(std::move(aItem));
   }
 
   already_AddRefed<NesteggPacketHolder> PopFront() {
-    RefPtr<NesteggPacketHolder> result = mQueue.front().forget();
+    RefPtr<NesteggPacketHolder> result = std::move(mQueue.front());
     mQueue.pop_front();
     return result.forget();
   }
 
   void Reset() {
     while (!mQueue.empty()) {
       mQueue.pop_front();
     }
--- a/dom/media/webm/WebMDemuxer.h
+++ b/dom/media/webm/WebMDemuxer.h
@@ -42,23 +42,23 @@ class MediaRawDataQueue {
 
   void PushFront(MediaRawDataQueue&& aOther) {
     while (!aOther.mQueue.empty()) {
       PushFront(aOther.Pop());
     }
   }
 
   already_AddRefed<MediaRawData> PopFront() {
-    RefPtr<MediaRawData> result = mQueue.front().forget();
+    RefPtr<MediaRawData> result = std::move(mQueue.front());
     mQueue.pop_front();
     return result.forget();
   }
 
   already_AddRefed<MediaRawData> Pop() {
-    RefPtr<MediaRawData> result = mQueue.back().forget();
+    RefPtr<MediaRawData> result = std::move(mQueue.back());
     mQueue.pop_back();
     return result.forget();
   }
 
   void Reset() {
     while (!mQueue.empty()) {
       mQueue.pop_front();
     }
--- a/dom/midi/MIDIAccessManager.cpp
+++ b/dom/midi/MIDIAccessManager.cpp
@@ -89,17 +89,17 @@ bool MIDIAccessManager::AddObserver(Obse
     }
     RefPtr<MIDIManagerChild> mgr(new MIDIManagerChild());
     PMIDIManagerChild* constructedMgr = actor->SendPMIDIManagerConstructor(mgr);
 
     if (NS_WARN_IF(!constructedMgr)) {
       return false;
     }
     MOZ_ASSERT(constructedMgr == mgr);
-    mChild = mgr.forget();
+    mChild = std::move(mgr);
     // Add a ref to mChild here, that will be deref'd by
     // BackgroundChildImpl::DeallocPMIDIManagerChild on IPC cleanup.
     mChild->SetActorAlive();
   }
   return true;
 }
 
 void MIDIAccessManager::RemoveObserver(Observer<MIDIPortList>* aObserver) {
--- a/dom/notification/Notification.cpp
+++ b/dom/notification/Notification.cpp
@@ -1712,17 +1712,17 @@ class WorkerGetCallback final : public S
     AssertIsOnMainThread();
     MOZ_ASSERT(aProxy);
   }
 
   NS_IMETHOD Done() final {
     AssertIsOnMainThread();
     MOZ_ASSERT(mPromiseProxy, "Was Done() called twice?");
 
-    RefPtr<PromiseWorkerProxy> proxy = mPromiseProxy.forget();
+    RefPtr<PromiseWorkerProxy> proxy = std::move(mPromiseProxy);
     MutexAutoLock lock(proxy->Lock());
     if (proxy->CleanedUp()) {
       return NS_OK;
     }
 
     RefPtr<WorkerGetResultRunnable> r = new WorkerGetResultRunnable(
         proxy->GetWorkerPrivate(), proxy, std::move(mStrings));
 
--- a/dom/payments/PaymentRequestData.cpp
+++ b/dom/payments/PaymentRequestData.cpp
@@ -166,17 +166,17 @@ nsresult PaymentDetailsModifier::Create(
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
       rv = items->AppendElement(additionalItem);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
     }
-    displayItems = items.forget();
+    displayItems = std::move(items);
   }
   nsCOMPtr<nsIPaymentDetailsModifier> modifier =
       new PaymentDetailsModifier(aIPCModifier.supportedMethods(), total,
                                  displayItems, aIPCModifier.data());
   modifier.forget(aModifier);
   return NS_OK;
 }
 
@@ -317,34 +317,34 @@ nsresult PaymentDetails::Create(const IP
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
     rv = items->AppendElement(item);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
   }
-  displayItems = items.forget();
+  displayItems = std::move(items);
 
   nsCOMPtr<nsIArray> shippingOptions;
   nsCOMPtr<nsIMutableArray> options = do_CreateInstance(NS_ARRAY_CONTRACTID);
   MOZ_ASSERT(options);
   for (const IPCPaymentShippingOption& shippingOption :
        aIPCDetails.shippingOptions()) {
     nsCOMPtr<nsIPaymentShippingOption> option;
     rv = PaymentShippingOption::Create(shippingOption, getter_AddRefs(option));
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
     rv = options->AppendElement(option);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
   }
-  shippingOptions = options.forget();
+  shippingOptions = std::move(options);
 
   nsCOMPtr<nsIArray> modifiers;
   nsCOMPtr<nsIMutableArray> detailsModifiers =
       do_CreateInstance(NS_ARRAY_CONTRACTID);
   MOZ_ASSERT(detailsModifiers);
   for (const IPCPaymentDetailsModifier& modifier : aIPCDetails.modifiers()) {
     nsCOMPtr<nsIPaymentDetailsModifier> detailsModifier;
     rv = PaymentDetailsModifier::Create(modifier,
@@ -352,17 +352,17 @@ nsresult PaymentDetails::Create(const IP
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
     rv = detailsModifiers->AppendElement(detailsModifier);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
   }
-  modifiers = detailsModifiers.forget();
+  modifiers = std::move(detailsModifiers);
 
   nsCOMPtr<nsIPaymentDetails> details = new PaymentDetails(
       aIPCDetails.id(), total, displayItems, shippingOptions, modifiers,
       aIPCDetails.error(), aIPCDetails.shippingAddressErrors(),
       aIPCDetails.payerErrors(), aIPCDetails.paymentMethodErrors());
 
   details.forget(aDetails);
   return NS_OK;
--- a/dom/presentation/PresentationSessionInfo.cpp
+++ b/dom/presentation/PresentationSessionInfo.cpp
@@ -1023,17 +1023,17 @@ PresentationControllingInfo::OnListNetwo
 nsresult PresentationControllingInfo::NotifyReconnectResult(nsresult aStatus) {
   if (!mReconnectCallback) {
     MOZ_ASSERT(false, "mReconnectCallback can not be null here.");
     return NS_ERROR_FAILURE;
   }
 
   mIsReconnecting = false;
   nsCOMPtr<nsIPresentationServiceCallback> callback =
-      mReconnectCallback.forget();
+      std::move(mReconnectCallback);
   if (NS_FAILED(aStatus)) {
     return callback->NotifyError(aStatus);
   }
 
   return callback->NotifySuccess(GetUrl());
 }
 
 // nsIPresentationSessionTransportCallback
--- a/dom/promise/Promise.cpp
+++ b/dom/promise/Promise.cpp
@@ -373,24 +373,24 @@ class PromiseNativeHandlerShim final : p
  public:
   explicit PromiseNativeHandlerShim(PromiseNativeHandler* aInner)
       : mInner(aInner) {
     MOZ_ASSERT(mInner);
   }
 
   MOZ_CAN_RUN_SCRIPT
   void ResolvedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override {
-    RefPtr<PromiseNativeHandler> inner = mInner.forget();
+    RefPtr<PromiseNativeHandler> inner = std::move(mInner);
     inner->ResolvedCallback(aCx, aValue);
     MOZ_ASSERT(!mInner);
   }
 
   MOZ_CAN_RUN_SCRIPT
   void RejectedCallback(JSContext* aCx, JS::Handle<JS::Value> aValue) override {
-    RefPtr<PromiseNativeHandler> inner = mInner.forget();
+    RefPtr<PromiseNativeHandler> inner = std::move(mInner);
     inner->RejectedCallback(aCx, aValue);
     MOZ_ASSERT(!mInner);
   }
 
   bool WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto,
                   JS::MutableHandle<JSObject*> aWrapper) {
     return PromiseNativeHandler_Binding::Wrap(aCx, this, aGivenProto, aWrapper);
   }
--- a/dom/push/PushManager.cpp
+++ b/dom/push/PushManager.cpp
@@ -89,17 +89,17 @@ nsresult GetSubscriptionParams(nsIPushSu
   }
 
   return NS_OK;
 }
 
 class GetSubscriptionResultRunnable final : public WorkerRunnable {
  public:
   GetSubscriptionResultRunnable(WorkerPrivate* aWorkerPrivate,
-                                already_AddRefed<PromiseWorkerProxy>&& aProxy,
+                                RefPtr<PromiseWorkerProxy>&& aProxy,
                                 nsresult aStatus, const nsAString& aEndpoint,
                                 const nsAString& aScope,
                                 nsTArray<uint8_t>&& aRawP256dhKey,
                                 nsTArray<uint8_t>&& aAuthSecret,
                                 nsTArray<uint8_t>&& aAppServerKey)
       : WorkerRunnable(aWorkerPrivate),
         mProxy(std::move(aProxy)),
         mStatus(aStatus),
@@ -166,17 +166,17 @@ class GetSubscriptionCallback final : pu
     nsTArray<uint8_t> rawP256dhKey, authSecret, appServerKey;
     if (NS_SUCCEEDED(aStatus)) {
       aStatus = GetSubscriptionParams(aSubscription, endpoint, rawP256dhKey,
                                       authSecret, appServerKey);
     }
 
     WorkerPrivate* worker = mProxy->GetWorkerPrivate();
     RefPtr<GetSubscriptionResultRunnable> r = new GetSubscriptionResultRunnable(
-        worker, mProxy.forget(), aStatus, endpoint, mScope,
+        worker, std::move(mProxy), aStatus, endpoint, mScope,
         std::move(rawP256dhKey), std::move(authSecret),
         std::move(appServerKey));
     MOZ_ALWAYS_TRUE(r->Dispatch());
 
     return NS_OK;
   }
 
   // Convenience method for use in this file.
--- a/dom/push/PushSubscription.cpp
+++ b/dom/push/PushSubscription.cpp
@@ -50,17 +50,17 @@ class UnsubscribeResultCallback final : 
   RefPtr<Promise> mPromise;
 };
 
 NS_IMPL_ISUPPORTS(UnsubscribeResultCallback, nsIUnsubscribeResultCallback)
 
 class UnsubscribeResultRunnable final : public WorkerRunnable {
  public:
   UnsubscribeResultRunnable(WorkerPrivate* aWorkerPrivate,
-                            already_AddRefed<PromiseWorkerProxy>&& aProxy,
+                            RefPtr<PromiseWorkerProxy>&& aProxy,
                             nsresult aStatus, bool aSuccess)
       : WorkerRunnable(aWorkerPrivate),
         mProxy(std::move(aProxy)),
         mStatus(aStatus),
         mSuccess(aSuccess) {
     AssertIsOnMainThread();
   }
 
@@ -105,17 +105,17 @@ class WorkerUnsubscribeResultCallback fi
 
     MutexAutoLock lock(mProxy->Lock());
     if (mProxy->CleanedUp()) {
       return NS_OK;
     }
 
     WorkerPrivate* worker = mProxy->GetWorkerPrivate();
     RefPtr<UnsubscribeResultRunnable> r = new UnsubscribeResultRunnable(
-        worker, mProxy.forget(), aStatus, aSuccess);
+        worker, std::move(mProxy), aStatus, aSuccess);
     MOZ_ALWAYS_TRUE(r->Dispatch());
 
     return NS_OK;
   }
 
  private:
   ~WorkerUnsubscribeResultCallback() {}
 
--- a/dom/script/ScriptLoader.cpp
+++ b/dom/script/ScriptLoader.cpp
@@ -2023,18 +2023,18 @@ NotifyOffThreadScriptLoadCompletedRunnab
 }
 
 NS_IMETHODIMP
 NotifyOffThreadScriptLoadCompletedRunnable::Run() {
   MOZ_ASSERT(NS_IsMainThread());
 
   // We want these to be dropped on the main thread, once we return from this
   // function.
-  RefPtr<ScriptLoadRequest> request = mRequest.forget();
-  RefPtr<ScriptLoader> loader = mLoader.forget();
+  RefPtr<ScriptLoadRequest> request = std::move(mRequest);
+  RefPtr<ScriptLoader> loader = std::move(mLoader);
 
   request->mOffThreadToken = mToken;
   nsresult rv = loader->ProcessOffThreadRequest(request);
 
   return rv;
 }
 
 static void OffThreadScriptLoaderCallback(JS::OffThreadToken* aToken,
--- a/dom/security/DOMSecurityManager.cpp
+++ b/dom/security/DOMSecurityManager.cpp
@@ -43,17 +43,17 @@ void DOMSecurityManager::Initialize() {
 
   nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
   if (NS_WARN_IF(!obs)) {
     return;
   }
 
   obs->AddObserver(service, NS_HTTP_ON_EXAMINE_RESPONSE_TOPIC, false);
   obs->AddObserver(service, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
-  gDOMSecurityManager = service.forget();
+  gDOMSecurityManager = std::move(service);
 }
 
 /* static */
 void DOMSecurityManager::Shutdown() {
   MOZ_ASSERT(NS_IsMainThread());
 
   if (!gDOMSecurityManager) {
     return;
--- a/dom/security/featurepolicy/FeaturePolicyUtils.cpp
+++ b/dom/security/featurepolicy/FeaturePolicyUtils.cpp
@@ -302,19 +302,19 @@ bool IPDLParamTraits<dom::FeaturePolicy*
   // to child document. That does not need to bind feature policy with a node.
   RefPtr<dom::FeaturePolicy> featurePolicy = new dom::FeaturePolicy(nullptr);
   featurePolicy->SetDefaultOrigin(info.defaultOrigin());
   featurePolicy->SetInheritedDeniedFeatureNames(
       info.inheritedDeniedFeatureNames());
 
   nsString declaredString = info.declaredString();
   if (declaredString.IsEmpty() || !info.selfOrigin()) {
-    *aResult = featurePolicy.forget();
+    *aResult = std::move(featurePolicy);
     return true;
   }
   featurePolicy->SetDeclaredPolicy(nullptr, declaredString, info.selfOrigin(),
                                    info.srcOrigin());
-  *aResult = featurePolicy.forget();
+  *aResult = std::move(featurePolicy);
   return true;
 }
 }  // namespace ipc
 
 }  // namespace mozilla
--- a/dom/serviceworkers/ServiceWorkerContainer.cpp
+++ b/dom/serviceworkers/ServiceWorkerContainer.cpp
@@ -175,17 +175,17 @@ struct MOZ_HEAP_CLASS ServiceWorkerConta
  private:
   ~ReceivedMessage() = default;
 };
 
 void ServiceWorkerContainer::ReceiveMessage(
     const ClientPostMessageArgs& aArgs) {
   RefPtr<ReceivedMessage> message = new ReceivedMessage(aArgs);
   if (mMessagesStarted) {
-    EnqueueReceivedMessageDispatch(message.forget());
+    EnqueueReceivedMessageDispatch(std::move(message));
   } else {
     mPendingMessages.AppendElement(message.forget());
   }
 }
 
 JSObject* ServiceWorkerContainer::WrapObject(
     JSContext* aCx, JS::Handle<JSObject*> aGivenProto) {
   return ServiceWorkerContainer_Binding::Wrap(aCx, this, aGivenProto);
@@ -282,23 +282,23 @@ already_AddRefed<Promise> ServiceWorkerC
   }
 
   // Strip the any ref from both the script and scope URLs.
   nsCOMPtr<nsIURI> cloneWithoutRef;
   aRv = NS_GetURIWithoutRef(scriptURI, getter_AddRefs(cloneWithoutRef));
   if (aRv.Failed()) {
     return nullptr;
   }
-  scriptURI = cloneWithoutRef.forget();
+  scriptURI = std::move(cloneWithoutRef);
 
   aRv = NS_GetURIWithoutRef(scopeURI, getter_AddRefs(cloneWithoutRef));
   if (aRv.Failed()) {
     return nullptr;
   }
-  scopeURI = cloneWithoutRef.forget();
+  scopeURI = std::move(cloneWithoutRef);
 
   ServiceWorkerScopeAndScriptAreValid(clientInfo.ref(), scopeURI, scriptURI,
                                       aRv);
   if (aRv.Failed()) {
     return nullptr;
   }
 
   nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(global);
--- a/dom/serviceworkers/ServiceWorkerManager.cpp
+++ b/dom/serviceworkers/ServiceWorkerManager.cpp
@@ -387,17 +387,17 @@ RefPtr<GenericErrorResultPromise> Servic
   RefPtr<ServiceWorkerManager> self(this);
 
   const ServiceWorkerDescriptor& active =
       aRegistrationInfo->GetActive()->Descriptor();
 
   auto entry = mControlledClients.LookupForAdd(aClientInfo.Id());
   if (entry) {
     RefPtr<ServiceWorkerRegistrationInfo> old =
-        entry.Data()->mRegistrationInfo.forget();
+        std::move(entry.Data()->mRegistrationInfo);
 
     if (aControlClientHandle) {
       promise = entry.Data()->mClientHandle->Control(active);
     } else {
       promise = GenericErrorResultPromise::CreateAndResolve(false, __func__);
     }
 
     entry.Data()->mRegistrationInfo = aRegistrationInfo;
@@ -463,17 +463,17 @@ RefPtr<GenericErrorResultPromise> Servic
 void ServiceWorkerManager::StopControllingClient(
     const ClientInfo& aClientInfo) {
   auto entry = mControlledClients.Lookup(aClientInfo.Id());
   if (!entry) {
     return;
   }
 
   RefPtr<ServiceWorkerRegistrationInfo> reg =
-      entry.Data()->mRegistrationInfo.forget();
+      std::move(entry.Data()->mRegistrationInfo);
 
   entry.Remove();
 
   StopControllingRegistration(reg);
 }
 
 void ServiceWorkerManager::MaybeStartShutdown() {
   MOZ_ASSERT(NS_IsMainThread());
--- a/dom/serviceworkers/ServiceWorkerPrivate.cpp
+++ b/dom/serviceworkers/ServiceWorkerPrivate.cpp
@@ -101,17 +101,17 @@ ServiceWorkerPrivate::ServiceWorkerPriva
 
     // Assert in all debug builds as well as non-debug Nightly and Dev Edition.
 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
     MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(inner->Initialize()));
 #else
     MOZ_ALWAYS_SUCCEEDS(inner->Initialize());
 #endif
 
-    mInner = inner.forget();
+    mInner = std::move(inner);
   }
 }
 
 ServiceWorkerPrivate::~ServiceWorkerPrivate() {
   MOZ_ASSERT(!mWorkerPrivate);
   MOZ_ASSERT(!mTokenCount);
   MOZ_ASSERT(!mInner);
   MOZ_ASSERT(!mInfo);
@@ -1793,17 +1793,18 @@ void ServiceWorkerPrivate::TerminateWork
     if (StaticPrefs::dom_serviceWorkers_testing_enabled()) {
       nsCOMPtr<nsIObserverService> os = services::GetObserverService();
       if (os) {
         os->NotifyObservers(nullptr, "service-worker-shutdown", nullptr);
       }
     }
 
     Unused << NS_WARN_IF(!mWorkerPrivate->Cancel());
-    RefPtr<WorkerPrivate> workerPrivate(mWorkerPrivate.forget());
+    RefPtr<WorkerPrivate> workerPrivate = std::move(mWorkerPrivate);
+    mozilla::Unused << workerPrivate;
     mSupportsArray.Clear();
 
     // Any pending events are never going to fire on this worker.  Cancel
     // them so that intercepted channels can be reset and other resources
     // cleaned up.
     nsTArray<RefPtr<WorkerRunnable>> pendingEvents;
     mPendingFunctionalEvents.SwapElements(pendingEvents);
     for (uint32_t i = 0; i < pendingEvents.Length(); ++i) {
@@ -1864,17 +1865,17 @@ void ServiceWorkerPrivate::UpdateState(S
   if (aState != ServiceWorkerState::Activated) {
     return;
   }
 
   nsTArray<RefPtr<WorkerRunnable>> pendingEvents;
   mPendingFunctionalEvents.SwapElements(pendingEvents);
 
   for (uint32_t i = 0; i < pendingEvents.Length(); ++i) {
-    RefPtr<WorkerRunnable> r = pendingEvents[i].forget();
+    RefPtr<WorkerRunnable> r = std::move(pendingEvents[i]);
     if (NS_WARN_IF(!r->Dispatch())) {
       NS_WARNING("Failed to dispatch pending functional event!");
     }
   }
 }
 
 nsresult ServiceWorkerPrivate::GetDebugger(nsIWorkerDebugger** aResult) {
   MOZ_ASSERT(NS_IsMainThread());
--- a/dom/serviceworkers/ServiceWorkerRegistration.cpp
+++ b/dom/serviceworkers/ServiceWorkerRegistration.cpp
@@ -450,19 +450,19 @@ void ServiceWorkerRegistration::UpdateSt
   MaybeScheduleUpdateFound(aInstalling);
 
   // Move the currently exposed workers into a separate list
   // of "old" workers.  We will then potentially add them
   // back to the registration properties below based on the
   // given descriptor.  Any that are not restored will need
   // to be moved to the redundant state.
   AutoTArray<RefPtr<ServiceWorker>, 3> oldWorkerList({
-      mInstallingWorker.forget(),
-      mWaitingWorker.forget(),
-      mActiveWorker.forget(),
+      std::move(mInstallingWorker),
+      std::move(mWaitingWorker),
+      std::move(mActiveWorker),
   });
 
   // Its important that all state changes are actually applied before
   // dispatching any statechange events.  Each ServiceWorker object
   // should be in the correct state and the ServiceWorkerRegistration
   // properties need to be set correctly as well.  To accomplish this
   // we use a ScopeExit to dispatch any statechange events.
   auto scopeExit = MakeScopeExit([&] {
--- a/dom/serviceworkers/ServiceWorkerRegistrationImpl.cpp
+++ b/dom/serviceworkers/ServiceWorkerRegistrationImpl.cpp
@@ -457,17 +457,17 @@ class StartUnregisterRunnable final : pu
     if (!swm) {
       mPromise->Reject(NS_ERROR_DOM_INVALID_STATE_ERR, __func__);
       return NS_OK;
     }
 
     RefPtr<GenericPromise::Private> promise;
     {
       MutexAutoLock lock(mMutex);
-      promise = mPromise.forget();
+      promise = std::move(mPromise);
     }
 
     RefPtr<WorkerUnregisterCallback> cb =
         new WorkerUnregisterCallback(std::move(mWorkerRef), std::move(promise));
 
     nsresult rv = swm->Unregister(principal, cb,
                                   NS_ConvertUTF8toUTF16(mDescriptor.Scope()));
     if (NS_WARN_IF(NS_FAILED(rv))) {
--- a/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp
+++ b/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp
@@ -564,47 +564,47 @@ void ServiceWorkerRegistrationInfo::Clea
 
 void ServiceWorkerRegistrationInfo::ClearInstalling() {
   MOZ_ASSERT(NS_IsMainThread());
 
   if (!mInstallingWorker) {
     return;
   }
 
-  RefPtr<ServiceWorkerInfo> installing = mInstallingWorker.forget();
+  RefPtr<ServiceWorkerInfo> installing = std::move(mInstallingWorker);
   installing->UpdateState(ServiceWorkerState::Redundant);
   installing->UpdateRedundantTime();
 
   UpdateRegistrationState();
   NotifyChromeRegistrationListeners();
 }
 
 void ServiceWorkerRegistrationInfo::TransitionEvaluatingToInstalling() {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(mEvaluatingWorker);
   MOZ_ASSERT(!mInstallingWorker);
 
-  mInstallingWorker = mEvaluatingWorker.forget();
+  mInstallingWorker = std::move(mEvaluatingWorker);
   mInstallingWorker->UpdateState(ServiceWorkerState::Installing);
 
   UpdateRegistrationState();
   NotifyChromeRegistrationListeners();
 }
 
 void ServiceWorkerRegistrationInfo::TransitionInstallingToWaiting() {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(mInstallingWorker);
 
   if (mWaitingWorker) {
     MOZ_ASSERT(mInstallingWorker->CacheName() != mWaitingWorker->CacheName());
     mWaitingWorker->UpdateState(ServiceWorkerState::Redundant);
     mWaitingWorker->UpdateRedundantTime();
   }
 
-  mWaitingWorker = mInstallingWorker.forget();
+  mWaitingWorker = std::move(mInstallingWorker);
   mWaitingWorker->UpdateState(ServiceWorkerState::Installed);
   mWaitingWorker->UpdateInstalledTime();
 
   UpdateRegistrationState();
   NotifyChromeRegistrationListeners();
 
   // TODO: When bug 1426401 is implemented we will need to call
   //       StoreRegistration() here to persist the waiting worker.
@@ -649,17 +649,17 @@ void ServiceWorkerRegistrationInfo::Tran
   if (mActiveWorker) {
     MOZ_ASSERT(mWaitingWorker->CacheName() != mActiveWorker->CacheName());
     mActiveWorker->UpdateState(ServiceWorkerState::Redundant);
     mActiveWorker->UpdateRedundantTime();
   }
 
   // We are transitioning from waiting to active normally, so go to
   // the activating state.
-  mActiveWorker = mWaitingWorker.forget();
+  mActiveWorker = std::move(mWaitingWorker);
   mActiveWorker->UpdateState(ServiceWorkerState::Activating);
 
   nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction(
       "ServiceWorkerRegistrationInfo::TransitionWaitingToActive", [] {
         RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
         if (swm) {
           swm->CheckPendingReadyPromises();
         }
--- a/dom/serviceworkers/ServiceWorkerRegistrationProxy.cpp
+++ b/dom/serviceworkers/ServiceWorkerRegistrationProxy.cpp
@@ -224,17 +224,17 @@ RefPtr<GenericPromise> ServiceWorkerRegi
                              NS_ConvertUTF8toUTF16(self->mReg->Scope()));
         NS_ENSURE_SUCCESS_VOID(rv);
 
         scopeExit.release();
       });
 
   MOZ_ALWAYS_SUCCEEDS(SystemGroup::Dispatch(TaskCategory::Other, r.forget()));
 
-  return promise.forget();
+  return promise;
 }
 
 namespace {
 
 class UpdateCallback final : public ServiceWorkerUpdateFinishCallback {
   RefPtr<ServiceWorkerRegistrationPromise::Private> mPromise;
 
   ~UpdateCallback() = default;
--- a/dom/storage/SessionStorageManager.cpp
+++ b/dom/storage/SessionStorageManager.cpp
@@ -26,17 +26,17 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(
 NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTION(SessionStorageManager, mBrowsingContext)
 NS_IMPL_CYCLE_COLLECTING_ADDREF(SessionStorageManager)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(SessionStorageManager)
 
 SessionStorageManager::SessionStorageManager(
     RefPtr<BrowsingContext> aBrowsingContext)
-    : mBrowsingContext(aBrowsingContext.forget()) {
+    : mBrowsingContext(std::move(aBrowsingContext)) {
   if (const auto service = SessionStorageService::Get()) {
     service->RegisterSessionStorageManager(this);
   }
 
   StorageObserver* observer = StorageObserver::Self();
   NS_ASSERTION(
       observer,
       "No StorageObserver, cannot observe private data delete notifications!");
--- a/dom/system/OSFileConstants.cpp
+++ b/dom/system/OSFileConstants.cpp
@@ -950,17 +950,17 @@ already_AddRefed<OSFileConstantsService>
     MOZ_ASSERT(NS_IsMainThread());
 
     RefPtr<OSFileConstantsService> service = new OSFileConstantsService();
     nsresult rv = service->InitOSFileConstants();
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return nullptr;
     }
 
-    gInstance = service.forget();
+    gInstance = std::move(service);
     ClearOnShutdown(&gInstance);
   }
 
   RefPtr<OSFileConstantsService> copy = gInstance;
   return copy.forget();
 }
 
 OSFileConstantsService::OSFileConstantsService()
--- a/dom/webauthn/WebAuthnManagerBase.cpp
+++ b/dom/webauthn/WebAuthnManagerBase.cpp
@@ -54,17 +54,17 @@ bool WebAuthnManagerBase::MaybeCreateBac
   PWebAuthnTransactionChild* constructedMgr =
       actorChild->SendPWebAuthnTransactionConstructor(mgr);
 
   if (NS_WARN_IF(!constructedMgr)) {
     return false;
   }
 
   MOZ_ASSERT(constructedMgr == mgr);
-  mChild = mgr.forget();
+  mChild = std::move(mgr);
 
   return true;
 }
 
 void WebAuthnManagerBase::ActorDestroyed() {
   MOZ_ASSERT(NS_IsMainThread());
   mChild = nullptr;
 }
--- a/dom/webbrowserpersist/nsWebBrowserPersist.cpp
+++ b/dom/webbrowserpersist/nsWebBrowserPersist.cpp
@@ -641,17 +641,17 @@ void nsWebBrowserPersist::SerializeNextF
   RefPtr<FlatURIMap> flatMap = new FlatURIMap(targetBaseSpec);
   for (auto iter = mURIMap.Iter(); !iter.Done(); iter.Next()) {
     nsAutoCString mapTo;
     nsresult rv = iter.UserData()->GetLocalURI(mTargetBaseURI, mapTo);
     if (NS_SUCCEEDED(rv) || !mapTo.IsVoid()) {
       flatMap->Add(iter.Key(), mapTo);
     }
   }
-  mFlatURIMap = flatMap.forget();
+  mFlatURIMap = std::move(flatMap);
 
   nsCOMPtr<nsIFile> localFile;
   GetLocalFileFromURI(docData->mFile, getter_AddRefs(localFile));
   if (localFile) {
     // if we're not replacing an existing file but the file
     // exists, something is wrong
     bool fileExists = false;
     rv = localFile->Exists(&fileExists);
--- a/dom/workers/RuntimeService.cpp
+++ b/dom/workers/RuntimeService.cpp
@@ -992,17 +992,17 @@ class WorkerJSContext final : public moz
     } else {
       MOZ_ASSERT(IsWorkerDebuggerGlobal(global) ||
                  IsWorkerDebuggerSandbox(global));
 
       microTaskQueue = &GetDebuggerMicroTaskQueue();
     }
 
     JS::JobQueueMayNotBeEmpty(cx);
-    microTaskQueue->push(runnable.forget());
+    microTaskQueue->push(std::move(runnable));
   }
 
   bool IsSystemCaller() const override {
     return mWorkerPrivate->UsesSystemPrincipal();
   }
 
   void ReportError(JSErrorReport* aReport,
                    JS::ConstUTF8CharsZ aToStringResult) override {
--- a/dom/workers/ScriptLoader.cpp
+++ b/dom/workers/ScriptLoader.cpp
@@ -1892,17 +1892,17 @@ class ChannelGetterRunnable final : publ
         // Nested workers are always dedicated.
         nsIContentPolicy::TYPE_INTERNAL_WORKER, mLoadInfo.mCookieSettings,
         mLoadInfo.mReferrerInfo, getter_AddRefs(channel));
     NS_ENSURE_SUCCESS(mResult, true);
 
     mResult = mLoadInfo.SetPrincipalsAndCSPFromChannel(channel);
     NS_ENSURE_SUCCESS(mResult, true);
 
-    mLoadInfo.mChannel = channel.forget();
+    mLoadInfo.mChannel = std::move(channel);
     return true;
   }
 
   nsresult GetResult() const { return mResult; }
 
  private:
   virtual ~ChannelGetterRunnable() = default;
 };
--- a/dom/workers/WorkerEventTarget.cpp
+++ b/dom/workers/WorkerEventTarget.cpp
@@ -13,19 +13,19 @@ namespace {
 
 class WrappedControlRunnable final : public WorkerControlRunnable {
   nsCOMPtr<nsIRunnable> mInner;
 
   ~WrappedControlRunnable() = default;
 
  public:
   WrappedControlRunnable(WorkerPrivate* aWorkerPrivate,
-                         already_AddRefed<nsIRunnable>&& aInner)
+                         nsCOMPtr<nsIRunnable>&& aInner)
       : WorkerControlRunnable(aWorkerPrivate, WorkerThreadUnchangedBusyCount),
-        mInner(aInner) {}
+        mInner(std::move(aInner)) {}
 
   virtual bool PreDispatch(WorkerPrivate* aWorkerPrivate) override {
     // Silence bad assertions, this can be dispatched from any thread.
     return true;
   }
 
   virtual void PostDispatch(WorkerPrivate* aWorkerPrivate,
                             bool aDispatchResult) override {
@@ -93,21 +93,21 @@ WorkerEventTarget::Dispatch(already_AddR
 
   if (mBehavior == Behavior::Hybrid) {
     RefPtr<WorkerRunnable> r =
         mWorkerPrivate->MaybeWrapAsWorkerRunnable(runnable.forget());
     if (r->Dispatch()) {
       return NS_OK;
     }
 
-    runnable = r.forget();
+    runnable = std::move(r);
   }
 
   RefPtr<WorkerControlRunnable> r =
-      new WrappedControlRunnable(mWorkerPrivate, runnable.forget());
+      new WrappedControlRunnable(mWorkerPrivate, std::move(runnable));
   if (!r->Dispatch()) {
     return NS_ERROR_FAILURE;
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -2414,17 +2414,17 @@ nsresult WorkerPrivate::SetIsDebuggerRea
   mDebuggerReady = aReady;
 
   if (aReady && mDebuggerRegistered) {
     // Dispatch all the delayed runnables without releasing the lock, to ensure
     // that the order in which debuggee runnables execute is the same as the
     // order in which they were originally dispatched.
     auto pending = std::move(mDelayedDebuggeeRunnables);
     for (uint32_t i = 0; i < pending.Length(); i++) {
-      RefPtr<WorkerRunnable> runnable = pending[i].forget();
+      RefPtr<WorkerRunnable> runnable = std::move(pending[i]);
       nsresult rv = DispatchLockHeld(runnable.forget(), nullptr, lock);
       NS_ENSURE_SUCCESS(rv, rv);
     }
     MOZ_RELEASE_ASSERT(mDelayedDebuggeeRunnables.IsEmpty());
   }
 
   return NS_OK;
 }
@@ -2727,17 +2727,17 @@ void WorkerPrivate::OverrideLoadInfoLoad
   //  - content = true
   //  - use remote tabs = false
   nsCOMPtr<nsILoadGroup> loadGroup = do_CreateInstance(NS_LOADGROUP_CONTRACTID);
 
   nsresult rv =
       loadGroup->SetNotificationCallbacks(aLoadInfo.mInterfaceRequestor);
   MOZ_ALWAYS_SUCCEEDS(rv);
 
-  aLoadInfo.mLoadGroup = loadGroup.forget();
+  aLoadInfo.mLoadGroup = std::move(loadGroup);
 
   MOZ_ASSERT(NS_LoadGroupMatchesPrincipal(aLoadInfo.mLoadGroup, aPrincipal));
 }
 
 void WorkerPrivate::DoRunLoop(JSContext* aCx) {
   MOZ_ACCESS_THREAD_BOUND(mWorkerThreadAccessible, data);
   MOZ_ASSERT(mThread);
 
@@ -3443,17 +3443,17 @@ void WorkerPrivate::ClearMainEventQueue(
 
   MOZ_ASSERT(mSyncLoopStack.IsEmpty());
   MOZ_ASSERT(!mCancelAllPendingRunnables);
   mCancelAllPendingRunnables = true;
 
   if (WorkerNeverRan == aRanOrNot) {
     for (uint32_t count = mPreStartRunnables.Length(), index = 0; index < count;
          index++) {
-      RefPtr<WorkerRunnable> runnable = mPreStartRunnables[index].forget();
+      RefPtr<WorkerRunnable> runnable = std::move(mPreStartRunnables[index]);
       static_cast<nsIRunnable*>(runnable.get())->Run();
     }
   } else {
     nsIThread* currentThread = NS_GetCurrentThread();
     MOZ_ASSERT(currentThread);
 
     NS_ProcessPendingEvents(currentThread);
 
@@ -5188,21 +5188,21 @@ WorkerPrivate::EventTarget::IsOnCurrentT
 
   return mWorkerPrivate->IsOnCurrentThread();
 }
 
 WorkerPrivate::AutoPushEventLoopGlobal::AutoPushEventLoopGlobal(
     WorkerPrivate* aWorkerPrivate, JSContext* aCx)
     : mWorkerPrivate(aWorkerPrivate) {
   MOZ_ACCESS_THREAD_BOUND(mWorkerPrivate->mWorkerThreadAccessible, data);
-  mOldEventLoopGlobal = data->mCurrentEventLoopGlobal.forget();
+  mOldEventLoopGlobal = std::move(data->mCurrentEventLoopGlobal);
   if (JSObject* global = JS::CurrentGlobalOrNull(aCx)) {
     data->mCurrentEventLoopGlobal = xpc::NativeGlobal(global);
   }
 }
 
 WorkerPrivate::AutoPushEventLoopGlobal::~AutoPushEventLoopGlobal() {
   MOZ_ACCESS_THREAD_BOUND(mWorkerPrivate->mWorkerThreadAccessible, data);
-  data->mCurrentEventLoopGlobal = mOldEventLoopGlobal.forget();
+  data->mCurrentEventLoopGlobal = std::move(mOldEventLoopGlobal);
 }
 
 }  // namespace dom
 }  // namespace mozilla
--- a/dom/workers/WorkerRunnable.cpp
+++ b/dom/workers/WorkerRunnable.cpp
@@ -417,20 +417,19 @@ WorkerSyncRunnable::WorkerSyncRunnable(W
 #ifdef DEBUG
   if (mSyncLoopTarget) {
     mWorkerPrivate->AssertValidSyncLoop(mSyncLoopTarget);
   }
 #endif
 }
 
 WorkerSyncRunnable::WorkerSyncRunnable(
-    WorkerPrivate* aWorkerPrivate,
-    already_AddRefed<nsIEventTarget>&& aSyncLoopTarget)
+    WorkerPrivate* aWorkerPrivate, nsCOMPtr<nsIEventTarget>&& aSyncLoopTarget)
     : WorkerRunnable(aWorkerPrivate, WorkerThreadUnchangedBusyCount),
-      mSyncLoopTarget(aSyncLoopTarget) {
+      mSyncLoopTarget(std::move(aSyncLoopTarget)) {
 #ifdef DEBUG
   if (mSyncLoopTarget) {
     mWorkerPrivate->AssertValidSyncLoop(mSyncLoopTarget);
   }
 #endif
 }
 
 WorkerSyncRunnable::~WorkerSyncRunnable() = default;
@@ -444,18 +443,18 @@ bool WorkerSyncRunnable::DispatchInterna
 
   return WorkerRunnable::DispatchInternal();
 }
 
 void MainThreadWorkerSyncRunnable::PostDispatch(WorkerPrivate* aWorkerPrivate,
                                                 bool aDispatchResult) {}
 
 MainThreadStopSyncLoopRunnable::MainThreadStopSyncLoopRunnable(
-    WorkerPrivate* aWorkerPrivate,
-    already_AddRefed<nsIEventTarget>&& aSyncLoopTarget, bool aResult)
+    WorkerPrivate* aWorkerPrivate, nsCOMPtr<nsIEventTarget>&& aSyncLoopTarget,
+    bool aResult)
     : WorkerSyncRunnable(aWorkerPrivate, std::move(aSyncLoopTarget)),
       mResult(aResult) {
   AssertIsOnMainThread();
 #ifdef DEBUG
   mWorkerPrivate->AssertValidSyncLoop(mSyncLoopTarget);
 #endif
 }
 
@@ -571,17 +570,17 @@ void WorkerMainThreadRunnable::Dispatch(
 NS_IMETHODIMP
 WorkerMainThreadRunnable::Run() {
   AssertIsOnMainThread();
 
   bool runResult = MainThreadRun();
 
   RefPtr<MainThreadStopSyncLoopRunnable> response =
       new MainThreadStopSyncLoopRunnable(mWorkerPrivate,
-                                         mSyncLoopTarget.forget(), runResult);
+                                         std::move(mSyncLoopTarget), runResult);
 
   MOZ_ALWAYS_TRUE(response->Dispatch());
 
   return NS_OK;
 }
 
 bool WorkerSameThreadRunnable::PreDispatch(WorkerPrivate* aWorkerPrivate) {
   // We don't call WorkerRunnable::PreDispatch, because we're using
--- a/dom/workers/WorkerRunnable.h
+++ b/dom/workers/WorkerRunnable.h
@@ -204,17 +204,17 @@ class WorkerSyncRunnable : public Worker
   nsCOMPtr<nsIEventTarget> mSyncLoopTarget;
 
   // Passing null for aSyncLoopTarget is allowed and will result in the behavior
   // of a normal WorkerRunnable.
   WorkerSyncRunnable(WorkerPrivate* aWorkerPrivate,
                      nsIEventTarget* aSyncLoopTarget);
 
   WorkerSyncRunnable(WorkerPrivate* aWorkerPrivate,
-                     already_AddRefed<nsIEventTarget>&& aSyncLoopTarget);
+                     nsCOMPtr<nsIEventTarget>&& aSyncLoopTarget);
 
   virtual ~WorkerSyncRunnable();
 
   virtual bool DispatchInternal() override;
 };
 
 // This runnable is identical to WorkerSyncRunnable except it is meant to be
 // created on and dispatched from the main thread only.  Its WorkerRun/PostRun
@@ -224,19 +224,18 @@ class MainThreadWorkerSyncRunnable : pub
   // Passing null for aSyncLoopTarget is allowed and will result in the behavior
   // of a normal WorkerRunnable.
   MainThreadWorkerSyncRunnable(WorkerPrivate* aWorkerPrivate,
                                nsIEventTarget* aSyncLoopTarget)
       : WorkerSyncRunnable(aWorkerPrivate, aSyncLoopTarget) {
     AssertIsOnMainThread();
   }
 
-  MainThreadWorkerSyncRunnable(
-      WorkerPrivate* aWorkerPrivate,
-      already_AddRefed<nsIEventTarget>&& aSyncLoopTarget)
+  MainThreadWorkerSyncRunnable(WorkerPrivate* aWorkerPrivate,
+                               nsCOMPtr<nsIEventTarget>&& aSyncLoopTarget)
       : WorkerSyncRunnable(aWorkerPrivate, std::move(aSyncLoopTarget)) {
     AssertIsOnMainThread();
   }
 
   virtual ~MainThreadWorkerSyncRunnable() = default;
 
  private:
   virtual bool PreDispatch(WorkerPrivate* aWorkerPrivate) override {
@@ -414,19 +413,19 @@ class WorkerProxyToMainThreadRunnable : 
 // main-thread only. As sync loops keep the busy count incremented as long as
 // they run this runnable does not modify the busy count
 // in any way.
 class MainThreadStopSyncLoopRunnable : public WorkerSyncRunnable {
   bool mResult;
 
  public:
   // Passing null for aSyncLoopTarget is not allowed.
-  MainThreadStopSyncLoopRunnable(
-      WorkerPrivate* aWorkerPrivate,
-      already_AddRefed<nsIEventTarget>&& aSyncLoopTarget, bool aResult);
+  MainThreadStopSyncLoopRunnable(WorkerPrivate* aWorkerPrivate,
+                                 nsCOMPtr<nsIEventTarget>&& aSyncLoopTarget,
+                                 bool aResult);
 
   // By default StopSyncLoopRunnables cannot be canceled since they could leave
   // a sync loop spinning forever.
   nsresult Cancel() override;
 
  protected:
   virtual ~MainThreadStopSyncLoopRunnable() = default;
 
--- a/dom/workers/WorkerScope.cpp
+++ b/dom/workers/WorkerScope.cpp
@@ -560,33 +560,33 @@ WorkerGlobalScope::GetServiceWorkerRegis
   mWorkerPrivate->AssertIsOnWorkerThread();
   RefPtr<ServiceWorkerRegistration> ref;
   ForEachEventTargetObject([&](DOMEventTargetHelper* aTarget, bool* aDoneOut) {
     RefPtr<ServiceWorkerRegistration> swr = do_QueryObject(aTarget);
     if (!swr || !swr->MatchesDescriptor(aDescriptor)) {
       return;
     }
 
-    ref = swr.forget();
+    ref = std::move(swr);
     *aDoneOut = true;
   });
-  return ref.forget();
+  return ref;
 }
 
 RefPtr<ServiceWorkerRegistration>
 WorkerGlobalScope::GetOrCreateServiceWorkerRegistration(
     const ServiceWorkerRegistrationDescriptor& aDescriptor) {
   mWorkerPrivate->AssertIsOnWorkerThread();
   RefPtr<ServiceWorkerRegistration> ref =
       GetServiceWorkerRegistration(aDescriptor);
   if (!ref) {
     ref = ServiceWorkerRegistration::CreateForWorker(mWorkerPrivate, this,
                                                      aDescriptor);
   }
-  return ref.forget();
+  return ref;
 }
 
 uint64_t WorkerGlobalScope::WindowID() const {
   return mWorkerPrivate->WindowID();
 }
 
 void WorkerGlobalScope::FirstPartyStorageAccessGranted() {
   // Reset the IndexedDB factory.
--- a/dom/worklet/WorkletThread.cpp
+++ b/dom/worklet/WorkletThread.cpp
@@ -147,17 +147,17 @@ class WorkletJSContext final : public Cy
     MOZ_ASSERT(cx);
 
 #ifdef DEBUG
     JS::Rooted<JSObject*> global(cx, JS::CurrentGlobalOrNull(cx));
     MOZ_ASSERT(global);
 #endif
 
     JS::JobQueueMayNotBeEmpty(cx);
-    GetMicroTaskQueue().push(runnable.forget());
+    GetMicroTaskQueue().push(std::move(runnable));
   }
 
   bool IsSystemCaller() const override {
     // Currently no support for special system worklet privileges.
     return false;
   }
 
   void ReportError(JSErrorReport* aReport,
--- a/dom/xhr/XMLHttpRequestWorker.cpp
+++ b/dom/xhr/XMLHttpRequestWorker.cpp
@@ -815,18 +815,18 @@ void Proxy::Teardown(bool aSendUnpin) {
         if (!runnable->Dispatch()) {
           MOZ_CRASH("We're going to hang at shutdown anyways.");
         }
       }
 
       if (mSyncLoopTarget) {
         // We have an unclosed sync loop.  Fix that now.
         RefPtr<MainThreadStopSyncLoopRunnable> runnable =
-            new MainThreadStopSyncLoopRunnable(mWorkerPrivate,
-                                               mSyncLoopTarget.forget(), false);
+            new MainThreadStopSyncLoopRunnable(
+                mWorkerPrivate, std::move(mSyncLoopTarget), false);
         if (!runnable->Dispatch()) {
           MOZ_CRASH("We're going to hang at shutdown anyways.");
         }
       }
 
       mOutstandingSendCount = 0;
     }
 
--- a/dom/xslt/xslt/txExecutionState.cpp
+++ b/dom/xslt/xslt/txExecutionState.cpp
@@ -466,13 +466,13 @@ void txExecutionState::removeVariable(co
 }
 
 void txExecutionState::pushParamMap(txParameterMap* aParams) {
   mParamStack.AppendElement(mTemplateParams.forget());
   mTemplateParams = aParams;
 }
 
 already_AddRefed<txParameterMap> txExecutionState::popParamMap() {
-  RefPtr<txParameterMap> oldParams = mTemplateParams.forget();
+  RefPtr<txParameterMap> oldParams = std::move(mTemplateParams);
   mTemplateParams = mParamStack.PopLastElement();
 
   return oldParams.forget();
 }
--- a/dom/xslt/xslt/txMozillaTextOutput.cpp
+++ b/dom/xslt/xslt/txMozillaTextOutput.cpp
@@ -186,17 +186,17 @@ nsresult txMozillaTextOutput::createResu
 
     rv = html->AppendChildTo(body, false);
     NS_ENSURE_SUCCESS(rv, rv);
 
     {
       RefPtr<Element> textParent;
       rv = createXHTMLElement(nsGkAtoms::pre, getter_AddRefs(textParent));
       NS_ENSURE_SUCCESS(rv, rv);
-      mTextParent = textParent.forget();
+      mTextParent = std::move(textParent);
     }
 
     rv = mTextParent->AsElement()->SetAttr(
         kNameSpaceID_None, nsGkAtoms::id,
         NS_LITERAL_STRING("transformiixResult"), false);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = body->AppendChildTo(mTextParent, false);
--- a/dom/xul/nsXULElement.cpp
+++ b/dom/xul/nsXULElement.cpp
@@ -1413,17 +1413,17 @@ nsresult nsXULPrototypeElement::Deserial
             rv = aStream->ReadObject(true, getter_AddRefs(supports));
             if (NS_WARN_IF(NS_FAILED(rv))) return rv;
             script->mSrcURI = do_QueryInterface(supports);
 
             rv = script->DeserializeOutOfLine(aStream, aProtoDoc);
             if (NS_WARN_IF(NS_FAILED(rv))) return rv;
           }
 
-          child = script.forget();
+          child = std::move(script);
           break;
         }
         default:
           MOZ_ASSERT(false, "Unexpected child type!");
           return NS_ERROR_UNEXPECTED;
       }
 
       MOZ_ASSERT(child, "Don't append null to mChildren");
@@ -1771,17 +1771,18 @@ NotifyOffThreadScriptCompletedRunnable::
 
   if (!sReceivers) {
     // We've already shut down.
     return NS_OK;
   }
 
   auto index = sReceivers->IndexOf(mReceiver);
   MOZ_RELEASE_ASSERT(index != sReceivers->NoIndex);
-  nsCOMPtr<nsIOffThreadScriptReceiver> receiver = (*sReceivers)[index].forget();
+  nsCOMPtr<nsIOffThreadScriptReceiver> receiver =
+      std::move((*sReceivers)[index]);
   sReceivers->RemoveElementAt(index);
 
   return receiver->OnScriptCompileComplete(script,
                                            script ? NS_OK : NS_ERROR_FAILURE);
 }
 
 static void OffThreadScriptReceiverCallback(JS::OffThreadToken* aToken,
                                             void* aCallbackData) {
--- a/editor/libeditor/EditorBase.cpp
+++ b/editor/libeditor/EditorBase.cpp
@@ -1531,17 +1531,17 @@ EditorBase::InsertPaddingBRElementForEmp
   nsresult rv = InsertNodeWithTransaction(*newBRElement, pointToInsert);
   if (NS_WARN_IF(Destroyed())) {
     return CreateElementResult(NS_ERROR_EDITOR_DESTROYED);
   }
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return CreateElementResult(rv);
   }
 
-  return CreateElementResult(newBRElement.forget());
+  return CreateElementResult(std::move(newBRElement));
 }
 
 already_AddRefed<nsIContent> EditorBase::SplitNodeWithTransaction(
     const EditorDOMPoint& aStartOfRightNode, ErrorResult& aError) {
   MOZ_ASSERT(IsEditActionDataAvailable());
 
   if (NS_WARN_IF(!aStartOfRightNode.IsSet()) ||
       NS_WARN_IF(!aStartOfRightNode.GetContainerAsContent())) {
@@ -3342,17 +3342,17 @@ nsresult EditorBase::DoJoinNodes(nsINode
     // with iteration.
     for (uint32_t i = childNodes->Length(); i; --i) {
       nsCOMPtr<nsIContent> childNode = childNodes->Item(i - 1);
       if (childNode) {
         // prepend children of aNodeToJoin
         ErrorResult err;
         aNodeToKeep->InsertBefore(*childNode, firstNode, err);
         NS_ENSURE_TRUE(!err.Failed(), err.StealNSResult());
-        firstNode = childNode.forget();
+        firstNode = std::move(childNode);
       }
     }
   }
 
   // Delete the extra node.
   ErrorResult err;
   aParent->RemoveChild(*aNodeToJoin, err);
 
--- a/editor/libeditor/EditorUtils.h
+++ b/editor/libeditor/EditorUtils.h
@@ -215,18 +215,18 @@ class MOZ_STACK_CLASS CreateNodeResultBa
 
   explicit CreateNodeResultBase(nsresult aRv) : mRv(aRv) {
     MOZ_DIAGNOSTIC_ASSERT(NS_FAILED(mRv));
   }
 
   explicit CreateNodeResultBase(NodeType* aNode)
       : mNode(aNode), mRv(aNode ? NS_OK : NS_ERROR_FAILURE) {}
 
-  explicit CreateNodeResultBase(already_AddRefed<NodeType>&& aNode)
-      : mNode(aNode), mRv(mNode.get() ? NS_OK : NS_ERROR_FAILURE) {}
+  explicit CreateNodeResultBase(RefPtr<NodeType>&& aNode)
+      : mNode(std::move(aNode)), mRv(mNode.get() ? NS_OK : NS_ERROR_FAILURE) {}
 
   CreateNodeResultBase(const SelfType& aOther) = delete;
   SelfType& operator=(const SelfType& aOther) = delete;
   CreateNodeResultBase(SelfType&& aOther) = default;
   SelfType& operator=(SelfType&& aOther) = default;
 
   already_AddRefed<NodeType> forget() {
     mRv = NS_ERROR_NOT_INITIALIZED;
--- a/editor/libeditor/HTMLEditSubActionHandler.cpp
+++ b/editor/libeditor/HTMLEditSubActionHandler.cpp
@@ -6073,17 +6073,17 @@ CreateElementResult HTMLEditor::ChangeLi
   }
 
   RefPtr<Element> listElement =
       ReplaceContainerWithTransaction(aListElement, aNewListTag);
   if (NS_WARN_IF(Destroyed())) {
     return CreateElementResult(NS_ERROR_EDITOR_DESTROYED);
   }
   NS_WARNING_ASSERTION(listElement != nullptr, "Failed to create list element");
-  return CreateElementResult(listElement.forget());
+  return CreateElementResult(std::move(listElement));
 }
 
 nsresult HTMLEditor::CreateStyleForInsertText(AbstractRange& aAbstractRange) {
   MOZ_ASSERT(IsEditActionDataAvailable());
   MOZ_ASSERT(aAbstractRange.IsPositioned());
   MOZ_ASSERT(mTypeInState);
 
   RefPtr<Element> documentRootElement = GetDocument()->GetRootElement();
--- a/editor/libeditor/HTMLEditor.cpp
+++ b/editor/libeditor/HTMLEditor.cpp
@@ -4532,17 +4532,17 @@ nsresult HTMLEditor::CopyLastEditableChi
     return NS_OK;
   }
 
   RefPtr<Element> brElement =
       InsertBRElementWithTransaction(EditorDOMPoint(firstClonsedElement, 0));
   if (NS_WARN_IF(!brElement)) {
     return NS_ERROR_FAILURE;
   }
-  *aNewBrElement = brElement.forget();
+  *aNewBrElement = std::move(brElement);
   return NS_OK;
 }
 
 nsresult HTMLEditor::GetElementOrigin(Element& aElement, int32_t& aX,
                                       int32_t& aY) {
   aX = 0;
   aY = 0;
 
--- a/editor/libeditor/HTMLEditorDataTransfer.cpp
+++ b/editor/libeditor/HTMLEditorDataTransfer.cpp
@@ -724,17 +724,17 @@ nsresult HTMLEditor::StripFormattingNode
   }
 
   if (!aNode.IsHTMLElement(nsGkAtoms::pre)) {
     nsCOMPtr<nsIContent> child = aNode.GetLastChild();
     while (child) {
       nsCOMPtr<nsIContent> previous = child->GetPreviousSibling();
       nsresult rv = StripFormattingNodes(*child, aListOnly);
       NS_ENSURE_SUCCESS(rv, rv);
-      child = previous.forget();
+      child = std::move(previous);
     }
   }
   return NS_OK;
 }
 
 nsresult HTMLEditor::PrepareTransferable(nsITransferable** aTransferable) {
   return NS_OK;
 }
@@ -2650,17 +2650,17 @@ nsresult HTMLEditor::CreateDOMFragmentFr
   // If there was no context, then treat all of the data we did get as the
   // pasted data.
   if (contextLeaf) {
     *outEndNode = *outStartNode = contextLeaf;
   } else {
     *outEndNode = *outStartNode = fragment;
   }
 
-  *outFragNode = fragment.forget();
+  *outFragNode = std::move(fragment);
   *outStartOffset = 0;
 
   // get the infoString contents
   if (!aInfoStr.IsEmpty()) {
     int32_t sep = aInfoStr.FindChar((char16_t)',');
     nsAutoString numstr1(Substring(aInfoStr, 0, sep));
     nsAutoString numstr2(
         Substring(aInfoStr, sep + 1, aInfoStr.Length() - (sep + 1)));
--- a/editor/libeditor/HTMLStyleEditor.cpp
+++ b/editor/libeditor/HTMLStyleEditor.cpp
@@ -922,17 +922,17 @@ nsresult HTMLEditor::RemoveStyleInside(E
     nsCOMPtr<nsIContent> nextSibling = child->GetNextSibling();
     if (child->IsElement()) {
       nsresult rv = RemoveStyleInside(MOZ_KnownLive(*child->AsElement()),
                                       aProperty, aAttribute);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
     }
-    child = nextSibling.forget();
+    child = ToRefPtr(std::move(nextSibling));
   }
 
   // Next, remove the element or its attribute.
   bool removeHTMLStyle = false;
   if (aProperty) {
     removeHTMLStyle =
         // If the element is a presentation element of aProperty
         aElement.NodeInfo()->NameAtom() == aProperty ||
--- a/editor/libeditor/ManualNAC.h
+++ b/editor/libeditor/ManualNAC.h
@@ -40,32 +40,32 @@ class ManualNACPtr final {
       nac = new ManualNACArray();
       parentContent->SetProperty(nsGkAtoms::manualNACProperty, nac,
                                  nsINode::DeleteProperty<ManualNACArray>);
     }
     nac->AppendElement(mPtr);
   }
 
   // We use move semantics, and delete the copy-constructor and operator=.
-  ManualNACPtr(ManualNACPtr&& aOther) : mPtr(aOther.mPtr.forget()) {}
+  ManualNACPtr(ManualNACPtr&& aOther) : mPtr(std::move(aOther.mPtr)) {}
   ManualNACPtr(ManualNACPtr& aOther) = delete;
   ManualNACPtr& operator=(ManualNACPtr&& aOther) {
-    mPtr = aOther.mPtr.forget();
+    mPtr = std::move(aOther.mPtr);
     return *this;
   }
   ManualNACPtr& operator=(ManualNACPtr& aOther) = delete;
 
   ~ManualNACPtr() { Reset(); }
 
   void Reset() {
     if (!mPtr) {
       return;
     }
 
-    RefPtr<dom::Element> ptr = mPtr.forget();
+    RefPtr<dom::Element> ptr = std::move(mPtr);
     RemoveContentFromNACArray(ptr);
   }
 
   static void RemoveContentFromNACArray(nsIContent* aAnonymousContent) {
     nsIContent* parentContent = aAnonymousContent->GetParent();
     if (!parentContent) {
       NS_WARNING("Potentially leaking manual NAC");
       return;
--- a/extensions/auth/nsIAuthModule.cpp
+++ b/extensions/auth/nsIAuthModule.cpp
@@ -34,30 +34,30 @@ already_AddRefed<nsIAuthModule> nsIAuthM
     RefPtr<nsAuthSambaNTLM> sambaAuth = new nsAuthSambaNTLM();
 
     nsresult rv = sambaAuth->SpawnNTLMAuthHelper();
     if (NS_FAILED(rv)) {
       // Failure here probably means that cached credentials were not available
       return nullptr;
     }
 
-    auth = sambaAuth.forget();
+    auth = std::move(sambaAuth);
 #endif
   } else if (!nsCRT::strcmp(aType, "sasl-gssapi")) {
     auth = new nsAuthSASL();
   } else if (!nsCRT::strcmp(aType, "ntlm") && XRE_IsParentProcess() &&
              EnsureNSSInitializedChromeOrContent()) {
     RefPtr<nsNTLMAuthModule> ntlmAuth = new nsNTLMAuthModule();
 
     nsresult rv = ntlmAuth->InitTest();
     if (NS_FAILED(rv)) {
       return nullptr;
     }
 
-    auth = ntlmAuth.forget();
+    auth = std::move(ntlmAuth);
   } else {
     return nullptr;
   }
 
   return auth.forget();
 }
 
 mozilla::LazyLogModule gNegotiateLog("negotiateauth");
--- a/extensions/permissions/nsPermissionManager.cpp
+++ b/extensions/permissions/nsPermissionManager.cpp
@@ -815,17 +815,17 @@ NS_IMPL_ISUPPORTS(CloseDatabaseListener,
 
 CloseDatabaseListener::CloseDatabaseListener(nsPermissionManager* aManager,
                                              bool aRebuildOnSuccess)
     : mManager(aManager), mRebuildOnSuccess(aRebuildOnSuccess) {}
 
 NS_IMETHODIMP
 CloseDatabaseListener::Complete(nsresult, nsISupports*) {
   // Help breaking cycles
-  RefPtr<nsPermissionManager> manager = mManager.forget();
+  RefPtr<nsPermissionManager> manager = std::move(mManager);
   if (mRebuildOnSuccess && !gIsShuttingDown) {
     return manager->InitDB(true);
   }
   return NS_OK;
 }
 
 /**
  * Simple callback used by |RemoveAllInternal| to trigger closing
@@ -865,17 +865,17 @@ NS_IMETHODIMP DeleteFromMozHostListener:
 
 NS_IMETHODIMP DeleteFromMozHostListener::HandleError(mozIStorageError*) {
   // Errors are handled in |HandleCompletion|
   return NS_OK;
 }
 
 NS_IMETHODIMP DeleteFromMozHostListener::HandleCompletion(uint16_t aReason) {
   // Help breaking cycles
-  RefPtr<nsPermissionManager> manager = mManager.forget();
+  RefPtr<nsPermissionManager> manager = std::move(mManager);
 
   if (aReason == REASON_ERROR) {
     manager->CloseDB(true);
   }
 
   return NS_OK;
 }
 
--- a/extensions/spellcheck/src/mozInlineSpellChecker.cpp
+++ b/extensions/spellcheck/src/mozInlineSpellChecker.cpp
@@ -562,17 +562,17 @@ nsresult mozInlineSpellChecker::Cleanup(
   // Notify ENDED observers now.  If we wait to notify as we normally do when
   // these async operations finish, then in the meantime the editor may create
   // another inline spell checker and cause more STARTED and ENDED
   // notifications to be broadcast.  Interleaved notifications for the same
   // editor but different inline spell checkers could easily confuse
   // observers.  They may receive two consecutive STARTED notifications for
   // example, which we guarantee will not happen.
 
-  RefPtr<TextEditor> textEditor = mTextEditor.forget();
+  RefPtr<TextEditor> textEditor = std::move(mTextEditor);
   if (mPendingSpellCheck) {
     // Cancel the pending editor spell checker initialization.
     mPendingSpellCheck = nullptr;
     mPendingInitEditorSpellCheckCallback->Cancel();
     mPendingInitEditorSpellCheckCallback = nullptr;
     ChangeNumPendingSpellChecks(-1, textEditor);
   }
 
--- a/gfx/2d/Factory.cpp
+++ b/gfx/2d/Factory.cpp
@@ -476,17 +476,17 @@ already_AddRefed<DrawTarget> Factory::Cr
       break;
     }
 #endif
 #ifdef USE_CAIRO
     case BackendType::CAIRO: {
       RefPtr<DrawTargetCairo> newTarget;
       newTarget = new DrawTargetCairo();
       if (newTarget->Init(aData, aSize, aStride, aFormat)) {
-        retVal = newTarget.forget();
+        retVal = std::move(newTarget);
       }
       break;
     }
 #endif
     default:
       gfxCriticalNote << "Invalid draw target type specified: "
                       << (int)aBackend;
       return nullptr;
--- a/gfx/2d/SourceSurfaceCapture.cpp
+++ b/gfx/2d/SourceSurfaceCapture.cpp
@@ -177,17 +177,17 @@ RefPtr<SourceSurface> SourceSurfaceCaptu
   } else {
     surf = dt->IntoLuminanceSource(mLuminanceType, mOpacity);
   }
 
   if (data) {
     surf->AddUserData(reinterpret_cast<UserDataKey*>(dt.get()), data, free);
   }
 
-  return surf.forget();
+  return surf;
 }
 
 already_AddRefed<DataSourceSurface> SourceSurfaceCapture::GetDataSurface() {
   RefPtr<SourceSurface> surface = Resolve();
   if (!surface) {
     return nullptr;
   }
   return surface->GetDataSurface();
--- a/gfx/ipc/GPUProcessManager.cpp
+++ b/gfx/ipc/GPUProcessManager.cpp
@@ -818,19 +818,18 @@ RefPtr<CompositorSession> GPUProcessMana
 
     RefPtr<APZInputBridgeChild> pinput = new APZInputBridgeChild();
     if (!mGPUChild->SendPAPZInputBridgeConstructor(pinput, aRootLayerTreeId)) {
       return nullptr;
     }
     apz->SetInputBridge(pinput);
   }
 
-  RefPtr<RemoteCompositorSession> session = new RemoteCompositorSession(
-      aWidget, child, widget, apz, aRootLayerTreeId);
-  return session.forget();
+  return new RemoteCompositorSession(aWidget, child, widget, apz,
+                                     aRootLayerTreeId);
 #else
   gfxCriticalNote << "Platform does not support out-of-process compositing";
   return nullptr;
 #endif
 }
 
 bool GPUProcessManager::CreateContentBridges(
     base::ProcessId aOtherProcess,
--- a/gfx/layers/apz/src/APZCTreeManager.cpp
+++ b/gfx/layers/apz/src/APZCTreeManager.cpp
@@ -700,38 +700,41 @@ void APZCTreeManager::SampleForWebRender
   // Sample async transforms on scrollable layers.
   for (const auto& mapping : mApzcMap) {
     AsyncPanZoomController* apzc = mapping.second;
     if (apzc->GetRenderRoot() != aRenderRoot) {
       // If this APZC belongs to a different render root, skip over it
       continue;
     }
 
-    const AsyncTransformComponents asyncTransformComponents = apzc->GetZoomAnimationId() ?
-        AsyncTransformComponents{AsyncTransformComponent::eLayout} : LayoutAndVisual;
+    const AsyncTransformComponents asyncTransformComponents =
+        apzc->GetZoomAnimationId()
+            ? AsyncTransformComponents{AsyncTransformComponent::eLayout}
+            : LayoutAndVisual;
     ParentLayerPoint layerTranslation =
         apzc->GetCurrentAsyncTransform(AsyncPanZoomController::eForCompositing,
                                        asyncTransformComponents)
             .mTranslation;
 
     if (Maybe<uint64_t> zoomAnimationId = apzc->GetZoomAnimationId()) {
       // for now we only support zooming on root content APZCs
       MOZ_ASSERT(apzc->IsRootContent());
 
       LayoutDeviceToParentLayerScale zoom =
         apzc->GetCurrentPinchZoomScale(AsyncPanZoomController::eForCompositing);
 
-      AsyncTransform asyncVisualTransform =
-          apzc->GetCurrentAsyncTransform(AsyncPanZoomController::eForCompositing,
-                                         AsyncTransformComponents{AsyncTransformComponent::eVisual});
+      AsyncTransform asyncVisualTransform = apzc->GetCurrentAsyncTransform(
+          AsyncPanZoomController::eForCompositing,
+          AsyncTransformComponents{AsyncTransformComponent::eVisual});
 
       transforms.AppendElement(wr::ToWrTransformProperty(
-          *zoomAnimationId,
-          LayoutDeviceToParentLayerMatrix4x4::Scaling(zoom.scale, zoom.scale, 1.0f) *
-          AsyncTransformComponentMatrix::Translation(asyncVisualTransform.mTranslation)));
+          *zoomAnimationId, LayoutDeviceToParentLayerMatrix4x4::Scaling(
+                                zoom.scale, zoom.scale, 1.0f) *
+                                AsyncTransformComponentMatrix::Translation(
+                                    asyncVisualTransform.mTranslation)));
 
       aTxn.UpdateIsTransformAsyncZooming(*zoomAnimationId,
                                          apzc->IsAsyncZooming());
     }
 
     // If layerTranslation includes only the layout component of the async
     // transform then it has not been scaled by the async zoom, so we want to
     // divide it by the resolution. If layerTranslation includes the visual
@@ -2950,17 +2953,17 @@ APZCTreeManager::HitTestResult APZCTreeM
         // If we hit a scrollbar, target the APZC for the content scrolled
         // by the scrollbar. (The scrollbar itself doesn't scroll with the
         // scrolled content, so it doesn't carry the scrolled content's
         // scroll metadata).
         RefPtr<AsyncPanZoomController> scrollTarget =
             GetTargetAPZC(n->GetLayersId(), n->GetScrollTargetId());
         if (scrollTarget) {
           hit.mLayersId = n->GetLayersId();
-          hit.mTargetApzc = scrollTarget.forget();
+          hit.mTargetApzc = std::move(scrollTarget);
           RefPtr<HitTestingTreeNode> scrollbarRef = scrollbarNode;
           hit.mScrollbarNode.Initialize(aProofOfTreeLock, scrollbarRef.forget(),
                                         mTreeLock);
           return hit;
         }
       } else if (IsFixedToRootContent(n)) {
         hit.mFixedPosSides = n->GetFixedPosSides();
       }
--- a/gfx/layers/apz/src/AsyncPanZoomController.cpp
+++ b/gfx/layers/apz/src/AsyncPanZoomController.cpp
@@ -4109,17 +4109,17 @@ bool AsyncPanZoomController::AdvanceAnim
 
     requestAnimationFrame = UpdateAnimation(aSampleTime, &deferredTasks);
   }
   // Execute any deferred tasks queued up by mAnimation's Sample() (called by
   // UpdateAnimation()). This needs to be done after the monitor is released
   // since the tasks are allowed to call APZCTreeManager methods which can grab
   // the tree lock.
   for (uint32_t i = 0; i < deferredTasks.Length(); ++i) {
-    APZThreadUtils::RunOnControllerThread(deferredTasks[i].forget());
+    APZThreadUtils::RunOnControllerThread(std::move(deferredTasks[i]));
   }
 
   // If any of the deferred tasks starts a new animation, it will request a
   // new composite directly, so we can just return requestAnimationFrame here.
   return requestAnimationFrame;
 }
 
 CSSRect AsyncPanZoomController::GetCurrentAsyncLayoutViewport(
--- a/gfx/layers/apz/src/InputQueue.cpp
+++ b/gfx/layers/apz/src/InputQueue.cpp
@@ -562,17 +562,17 @@ void InputQueue::ScheduleMainThreadTimeo
     // when a timeout is reached. This codepath is used by tests that
     // want to exercise the fallback behaviour.
     // To ensure the fallback behaviour is used unconditionally, the timeout
     // is run right away instead of using PostDelayedTask(). However,
     // we can't run it right here, because MainThreadTimeout() expects that
     // the input block has at least one input event in mQueuedInputs, and
     // the event that triggered this call may not have been added to
     // mQueuedInputs yet.
-    mImmediateTimeout = timeoutTask.forget();
+    mImmediateTimeout = std::move(timeoutTask);
   } else {
     aTarget->PostDelayedTask(timeoutTask.forget(), timeout);
   }
 }
 
 InputBlockState* InputQueue::FindBlockForId(uint64_t aInputBlockId,
                                             InputData** aOutFirstInput) {
   for (const auto& queuedInput : mQueuedInputs) {
--- a/gfx/layers/composite/CompositorScreenshotGrabber.cpp
+++ b/gfx/layers/composite/CompositorScreenshotGrabber.cpp
@@ -180,17 +180,17 @@ void CompositorScreenshotGrabberImpl::Gr
   }
 
   aCompositor->ReadbackRenderTarget(scaledTarget, buffer);
 
   // This QueueItem will be added to the queue at the end of the next call to
   // ProcessQueue(). This ensures that the buffer isn't mapped into main memory
   // until the next frame. If we did it in this frame, we'd block on the GPU.
   mCurrentFrameQueueItem = Some(QueueItem{
-      TimeStamp::Now(), buffer.forget(), scaledSize, windowTarget->GetSize(),
+      TimeStamp::Now(), std::move(buffer), scaledSize, windowTarget->GetSize(),
       reinterpret_cast<uintptr_t>(static_cast<void*>(this))});
 }
 
 already_AddRefed<AsyncReadbackBuffer>
 CompositorScreenshotGrabberImpl::TakeNextBuffer(Compositor* aCompositor) {
   if (!mAvailableBuffers.IsEmpty()) {
     RefPtr<AsyncReadbackBuffer> buffer = mAvailableBuffers[0];
     mAvailableBuffers.RemoveElementAt(0);
--- a/gfx/layers/ipc/CompositorManagerChild.cpp
+++ b/gfx/layers/ipc/CompositorManagerChild.cpp
@@ -45,17 +45,17 @@ void CompositorManagerChild::InitSamePro
   RefPtr<CompositorManagerChild> child =
       new CompositorManagerChild(parent, aProcessToken, aNamespace);
   if (NS_WARN_IF(!child->CanSend())) {
     MOZ_DIAGNOSTIC_ASSERT(false, "Failed to open same process protocol");
     return;
   }
 
   parent->BindComplete(/* aIsRoot */ true);
-  sInstance = child.forget();
+  sInstance = std::move(child);
 }
 
 /* static */
 bool CompositorManagerChild::Init(Endpoint<PCompositorManagerChild>&& aEndpoint,
                                   uint32_t aNamespace,
                                   uint64_t aProcessToken /* = 0 */) {
   MOZ_ASSERT(NS_IsMainThread());
   if (sInstance) {
--- a/gfx/layers/ipc/UiCompositorControllerChild.cpp
+++ b/gfx/layers/ipc/UiCompositorControllerChild.cpp
@@ -181,17 +181,17 @@ void UiCompositorControllerChild::Destro
                           &UiCompositorControllerChild::Destroy),
         nsIThread::DISPATCH_SYNC);
     return;
   }
 
   if (mWidget) {
     // Dispatch mWidget to main thread to prevent it from being destructed by
     // the ui thread.
-    RefPtr<nsIWidget> widget = mWidget.forget();
+    RefPtr<nsIWidget> widget = std::move(mWidget);
     NS_ReleaseOnMainThreadSystemGroup("UiCompositorControllerChild::mWidget",
                                       widget.forget());
   }
 
   if (mIsOpen) {
     // Close the underlying IPC channel.
     PUiCompositorControllerChild::Close();
     mIsOpen = false;
--- a/gfx/layers/mlgpu/MLGPUScreenshotGrabber.cpp
+++ b/gfx/layers/mlgpu/MLGPUScreenshotGrabber.cpp
@@ -266,17 +266,17 @@ void MLGPUScreenshotGrabberImpl::GrabScr
   aDevice->CopyTexture(readbackTexture, IntPoint(), scaledTarget,
                        IntRect(IntPoint(), mReadbackTextureSize));
 
   // This QueueItem will be added to the queue at the end of the next call to
   // ProcessQueue(). This ensures that the ReadbackTexture isn't mapped into
   // main memory until the next frame. If we did it in this frame, we'd block on
   // the GPU.
   mCurrentFrameQueueItem =
-      Some(QueueItem{TimeStamp::Now(), readbackTexture.forget(), scaledSize,
+      Some(QueueItem{TimeStamp::Now(), std::move(readbackTexture), scaledSize,
                      aTexture->GetSize(), aDevice,
                      reinterpret_cast<uintptr_t>(static_cast<void*>(this))});
 }
 
 already_AddRefed<MLGTexture>
 MLGPUScreenshotGrabberImpl::TakeNextReadbackTexture(MLGDevice* aDevice) {
   if (!mAvailableReadbackTextures.IsEmpty()) {
     RefPtr<MLGTexture> readbackTexture = mAvailableReadbackTextures[0];
--- a/gfx/layers/mlgpu/MaskOperation.cpp
+++ b/gfx/layers/mlgpu/MaskOperation.cpp
@@ -66,17 +66,17 @@ RefPtr<TextureSource> GetMaskLayerTextur
     return nullptr;
   }
 
   RefPtr<TextureSource> source = texLayer->BindAndGetTexture();
   if (!source) {
     gfxWarning() << "Mask layer does not have a TextureSource";
     return nullptr;
   }
-  return source.forget();
+  return source;
 }
 
 MaskCombineOperation::MaskCombineOperation(FrameBuilder* aBuilder)
     : MaskOperation(aBuilder), mBuilder(aBuilder) {}
 
 MaskCombineOperation::~MaskCombineOperation() {}
 
 void MaskCombineOperation::Init(const MaskTextureList& aTextures) {
--- a/gfx/thebes/PrintTarget.cpp
+++ b/gfx/thebes/PrintTarget.cpp
@@ -129,17 +129,17 @@ already_AddRefed<DrawTarget> PrintTarget
         Factory::CreateDrawTargetForCairoSurface(similar, size);
 
     // The DT addrefs the surface, so we need drop our own reference to it:
     cairo_surface_destroy(similar);
 
     if (!dt || !dt->IsValid()) {
       return nullptr;
     }
-    mRefDT = dt.forget();
+    mRefDT = std::move(dt);
   }
 
   return do_AddRef(mRefDT);
 }
 
 /* static */
 void PrintTarget::AdjustPrintJobNameForIPP(const nsAString& aJobName,
                                            nsCString& aAdjustedJobName) {
--- a/gfx/thebes/PrintTargetSkPDF.cpp
+++ b/gfx/thebes/PrintTargetSkPDF.cpp
@@ -112,15 +112,15 @@ already_AddRefed<DrawTarget> PrintTarget
     mRefCanvas = mRefPDFDoc->beginPage(mSize.width, mSize.height);
     if (!mRefCanvas) {
       return nullptr;
     }
     RefPtr<DrawTarget> dt = Factory::CreateDrawTargetWithSkCanvas(mRefCanvas);
     if (!dt) {
       return nullptr;
     }
-    mRefDT = dt.forget();
+    mRefDT = std::move(dt);
   }
 
   return do_AddRef(mRefDT);
 }
 
 }  // namespace mozilla::gfx
--- a/gfx/vr/ipc/VRGPUParent.cpp
+++ b/gfx/vr/ipc/VRGPUParent.cpp
@@ -40,17 +40,17 @@ void VRGPUParent::DeferredDestroy() { mS
 
 /* static */
 RefPtr<VRGPUParent> VRGPUParent::CreateForGPU(
     Endpoint<PVRGPUParent>&& aEndpoint) {
   RefPtr<VRGPUParent> vcp = new VRGPUParent(aEndpoint.OtherPid());
   MessageLoop::current()->PostTask(NewRunnableMethod<Endpoint<PVRGPUParent>&&>(
       "gfx::VRGPUParent::Bind", vcp, &VRGPUParent::Bind, std::move(aEndpoint)));
 
-  return vcp.forget();
+  return vcp;
 }
 
 void VRGPUParent::Bind(Endpoint<PVRGPUParent>&& aEndpoint) {
   if (!aEndpoint.Bind(this)) {
     return;
   }
 
   mSelfRef = this;
--- a/image/imgFrame.h
+++ b/image/imgFrame.h
@@ -351,21 +351,21 @@ class DrawableFrameRef final {
       // The optimized surface has become invalid, so we need to redecode.
       // For example, on Windows, there may have been a device reset, and
       // all D2D surfaces now need to be recreated.
       mFrame = nullptr;
     }
   }
 
   DrawableFrameRef(DrawableFrameRef&& aOther)
-      : mFrame(aOther.mFrame.forget()), mRef(std::move(aOther.mRef)) {}
+      : mFrame(std::move(aOther.mFrame)), mRef(std::move(aOther.mRef)) {}
 
   DrawableFrameRef& operator=(DrawableFrameRef&& aOther) {
     MOZ_ASSERT(this != &aOther, "Self-moves are prohibited");
-    mFrame = aOther.mFrame.forget();
+    mFrame = std::move(aOther.mFrame);
     mRef = std::move(aOther.mRef);
     return *this;
   }
 
   explicit operator bool() const { return bool(mFrame); }
 
   imgFrame* operator->() {
     MOZ_ASSERT(mFrame);
@@ -418,34 +418,34 @@ class RawAccessFrameRef final {
 
     mData = mFrame->LockImageData(aOnlyFinished);
     if (!mData) {
       mFrame = nullptr;
     }
   }
 
   RawAccessFrameRef(RawAccessFrameRef&& aOther)
-      : mFrame(aOther.mFrame.forget()), mData(aOther.mData) {
+      : mFrame(std::move(aOther.mFrame)), mData(aOther.mData) {
     aOther.mData = nullptr;
   }
 
   ~RawAccessFrameRef() {
     if (mFrame) {
       mFrame->UnlockImageData();
     }
   }
 
   RawAccessFrameRef& operator=(RawAccessFrameRef&& aOther) {
     MOZ_ASSERT(this != &aOther, "Self-moves are prohibited");
 
     if (mFrame) {
       mFrame->UnlockImageData();
     }
 
-    mFrame = aOther.mFrame.forget();
+    mFrame = std::move(aOther.mFrame);
     mData = aOther.mData;
     aOther.mData = nullptr;
 
     return *this;
   }
 
   explicit operator bool() const { return bool(mFrame); }
 
--- a/image/imgTools.cpp
+++ b/image/imgTools.cpp
@@ -414,17 +414,17 @@ imgTools::DecodeImageAsync(nsIInputStrea
 
   // Prepare the input stream.
   nsCOMPtr<nsIInputStream> stream = aInStr;
   if (!NS_InputStreamIsBuffered(aInStr)) {
     nsCOMPtr<nsIInputStream> bufStream;
     rv = NS_NewBufferedInputStream(getter_AddRefs(bufStream), stream.forget(),
                                    1024);
     NS_ENSURE_SUCCESS(rv, rv);
-    stream = bufStream.forget();
+    stream = std::move(bufStream);
   }
 
   // Create a new image container to hold the decoded data.
   nsAutoCString mimeType(aMimeType);
   RefPtr<image::Image> image = ImageFactory::CreateAnonymousImage(mimeType, 0);
 
   // Already an error?
   if (image->HasError()) {
--- a/ipc/chromium/src/base/message_loop.cc
+++ b/ipc/chromium/src/base/message_loop.cc
@@ -319,17 +319,17 @@ void MessageLoop::RunInternal() {
 // Wrapper functions for use in above message loop framework.
 
 bool MessageLoop::ProcessNextDelayedNonNestableTask() {
   if (state_->run_depth > run_depth_base_) return false;
 
   if (deferred_non_nestable_work_queue_.empty()) return false;
 
   nsCOMPtr<nsIRunnable> task =
-      deferred_non_nestable_work_queue_.front().task.forget();
+      std::move(deferred_non_nestable_work_queue_.front().task);
   deferred_non_nestable_work_queue_.pop();
 
   RunTask(task.forget());
   return true;
 }
 
 //------------------------------------------------------------------------------
 
--- a/ipc/chromium/src/base/message_loop.h
+++ b/ipc/chromium/src/base/message_loop.h
@@ -296,17 +296,17 @@ class MessageLoop : public base::Message
     base::TimeTicks delayed_run_time;  // The time when the task should be run.
     int sequence_num;                  // Secondary sort key for run time.
     bool nestable;                     // OK to dispatch from a nested loop.
 
     PendingTask(already_AddRefed<nsIRunnable> aTask, bool aNestable)
         : task(aTask), sequence_num(0), nestable(aNestable) {}
 
     PendingTask(PendingTask&& aOther)
-        : task(aOther.task.forget()),
+        : task(std::move(aOther.task)),
           delayed_run_time(aOther.delayed_run_time),
           sequence_num(aOther.sequence_num),
           nestable(aOther.nestable) {}
 
     // std::priority_queue<T>::top is dumb, so we have to have this.
     PendingTask(const PendingTask& aOther)
         : task(aOther.task),
           delayed_run_time(aOther.delayed_run_time),
--- a/ipc/chromium/src/chrome/common/ipc_message.cc
+++ b/ipc/chromium/src/chrome/common/ipc_message.cc
@@ -94,17 +94,17 @@ Message::Message(int32_t routing_id, msg
 Message::Message(const char* data, int data_len)
     : Pickle(MSG_HEADER_SZ_DATA, data, data_len) {
   MOZ_COUNT_CTOR(IPC::Message);
 }
 
 Message::Message(Message&& other) : Pickle(std::move(other)) {
   MOZ_COUNT_CTOR(IPC::Message);
 #if defined(OS_POSIX)
-  file_descriptor_set_ = other.file_descriptor_set_.forget();
+  file_descriptor_set_ = std::move(other.file_descriptor_set_);
 #endif
 }
 
 /*static*/ Message* Message::IPDLMessage(int32_t routing_id, msgid_t type,
                                          HeaderFlags flags) {
   return new Message(routing_id, type, 0, flags, true);
 }
 
--- a/ipc/chromium/src/chrome/common/ipc_message_utils.h
+++ b/ipc/chromium/src/chrome/common/ipc_message_utils.h
@@ -472,17 +472,17 @@ struct ParamTraitsMozilla<nsCOMPtr<T>> {
     ParamTraits<T*>::Write(m, p.get());
   }
 
   static bool Read(const Message* m, PickleIterator* iter, nsCOMPtr<T>* r) {
     RefPtr<T> refptr;
     if (!ParamTraits<T*>::Read(m, iter, &refptr)) {
       return false;
     }
-    *r = refptr.forget();
+    *r = std::move(refptr);
     return true;
   }
 };
 
 // Finally, ParamTraits itself.
 
 template <class P>
 struct ParamTraits : ParamTraitsMozilla<P> {};
--- a/ipc/glue/IPCStreamDestination.cpp
+++ b/ipc/glue/IPCStreamDestination.cpp
@@ -29,19 +29,19 @@ class IPCStreamDestination::DelayedStart
     : public nsIAsyncInputStream,
       public nsISearchableInputStream,
       public nsICloneableInputStream,
       public nsIBufferedInputStream {
  public:
   NS_DECL_THREADSAFE_ISUPPORTS
 
   DelayedStartInputStream(IPCStreamDestination* aDestination,
-                          already_AddRefed<nsIAsyncInputStream>&& aStream)
+                          nsCOMPtr<nsIAsyncInputStream>&& aStream)
       : mDestination(aDestination),
-        mStream(aStream),
+        mStream(std::move(aStream)),
         mMutex("IPCStreamDestination::DelayedStartInputStream::mMutex") {
     MOZ_ASSERT(mDestination);
     MOZ_ASSERT(mStream);
   }
 
   void DestinationShutdown() {
     MutexAutoLock lock(mMutex);
     mDestination = nullptr;
@@ -297,17 +297,17 @@ void IPCStreamDestination::SetLength(int
 }
 
 already_AddRefed<nsIInputStream> IPCStreamDestination::TakeReader() {
   MOZ_ASSERT(mReader);
   MOZ_ASSERT(!mDelayedStartInputStream);
 
   if (mDelayedStart) {
     mDelayedStartInputStream =
-        new DelayedStartInputStream(this, mReader.forget());
+        new DelayedStartInputStream(this, std::move(mReader));
     RefPtr<nsIAsyncInputStream> inputStream = mDelayedStartInputStream;
     return inputStream.forget();
   }
 
   return mReader.forget();
 }
 
 bool IPCStreamDestination::IsOnOwningThread() const {
--- a/ipc/glue/InProcessImpl.cpp
+++ b/ipc/glue/InProcessImpl.cpp
@@ -71,18 +71,18 @@ void InProcessParent::Startup() {
   // Link the two actors
   if (!child->OpenOnSameThread(parent->GetIPCChannel(), ChildSide)) {
     MOZ_CRASH("Failed to open InProcessChild!");
   }
 
   parent->SetOtherProcessId(base::GetCurrentProcId());
 
   // Stash global references to fetch the other side of the reference.
-  InProcessParent::sSingleton = parent.forget();
-  InProcessChild::sSingleton = child.forget();
+  InProcessParent::sSingleton = std::move(parent);
+  InProcessChild::sSingleton = std::move(child);
 }
 
 /* static */
 void InProcessParent::Shutdown() {
   MOZ_ASSERT(NS_IsMainThread());
 
   if (!sSingleton || sShutdown) {
     return;
--- a/ipc/glue/TransportSecurityInfoUtils.cpp
+++ b/ipc/glue/TransportSecurityInfoUtils.cpp
@@ -35,17 +35,17 @@ bool ParamTraits<nsITransportSecurityInf
   }
 
   RefPtr<nsITransportSecurityInfo> info =
       new mozilla::psm::TransportSecurityInfo();
   if (!info->DeserializeFromIPC(aMsg, aIter)) {
     return false;
   }
 
-  *aResult = info.forget();
+  *aResult = std::move(info);
   return true;
 }
 
 void ParamTraits<nsIX509Cert*>::Write(Message* aMsg, nsIX509Cert* aParam) {
   bool nonNull = !!aParam;
   WriteParam(aMsg, nonNull);
   if (!nonNull) {
     return;
@@ -67,13 +67,13 @@ bool ParamTraits<nsIX509Cert*>::Read(con
     return true;
   }
 
   RefPtr<nsIX509Cert> cert = new nsNSSCertificate();
   if (!cert->DeserializeFromIPC(aMsg, aIter)) {
     return false;
   }
 
-  *aResult = cert.forget();
+  *aResult = std::move(cert);
   return true;
 }
 
 }  // namespace IPC
--- a/js/xpconnect/src/XPCInlines.h
+++ b/js/xpconnect/src/XPCInlines.h
@@ -238,17 +238,17 @@ inline bool XPCNativeSet::FindMember(JS:
   *pMember = Member;
 
   *pIsLocal = !Member || !protoSet ||
               (protoSet != this &&
                !protoSet->MatchesSetUpToInterface(this, Interface) &&
                (!protoSet->FindMember(name, &protoMember, (uint16_t*)nullptr) ||
                 protoMember != Member));
 
-  *pInterface = Interface.forget();
+  *pInterface = std::move(Interface);
 
   return true;
 }
 
 inline bool XPCNativeSet::HasInterface(XPCNativeInterface* aInterface) const {
   XPCNativeInterface* const* pp = mInterfaces;
 
   for (int i = (int)mInterfaceCount; i > 0; i--, pp++) {
--- a/js/xpconnect/src/XPCWrappedNative.cpp
+++ b/js/xpconnect/src/XPCWrappedNative.cpp
@@ -208,17 +208,17 @@ nsresult XPCWrappedNative::WrapNewGlobal
   bool success = JS_SplicePrototype(cx, global, protoObj);
   if (!success) {
     return NS_ERROR_FAILURE;
   }
 
   // Construct the wrapper, which takes over the strong reference to the
   // native object.
   RefPtr<XPCWrappedNative> wrapper =
-      new XPCWrappedNative(identity.forget(), proto);
+      new XPCWrappedNative(std::move(identity), proto);
 
   //
   // We don't call ::Init() on this wrapper, because our setup requirements
   // are different for globals. We do our setup inline here, instead.
   //
 
   wrapper->mScriptable = scrWrapper;
 
@@ -402,31 +402,31 @@ nsresult XPCWrappedNative::GetNewOrUsed(
   // wrapper is actually created, but before JS code can see it.
 
   if (info && !isClassInfoSingleton) {
     proto = XPCWrappedNativeProto::GetNewOrUsed(cx, Scope, info, scrProto);
     if (!proto) {
       return NS_ERROR_FAILURE;
     }
 
-    wrapper = new XPCWrappedNative(identity.forget(), proto);
+    wrapper = new XPCWrappedNative(std::move(identity), proto);
   } else {
     RefPtr<XPCNativeInterface> iface = Interface;
     if (!iface) {
       iface = XPCNativeInterface::GetISupports(cx);
     }
 
     XPCNativeSetKey key(cx, iface);
     RefPtr<XPCNativeSet> set = XPCNativeSet::GetNewOrUsed(cx, &key);
 
     if (!set) {
       return NS_ERROR_FAILURE;
     }
 
-    wrapper = new XPCWrappedNative(identity.forget(), Scope, set.forget());
+    wrapper = new XPCWrappedNative(std::move(identity), Scope, set.forget());
   }
 
   MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(parent),
              "Xray wrapper being used to parent XPCWrappedNative?");
 
   // We use an AutoMarkingPtr here because it is possible for JS gc to happen
   // after we have Init'd the wrapper but *before* we add it to the hashtable.
   // This would cause the mSet to get collected and we'd later crash. I've
@@ -476,34 +476,33 @@ static nsresult FinishCreate(JSContext* 
   }
 
   DEBUG_CheckClassInfoClaims(wrapper);
   wrapper.forget(resultWrapper);
   return NS_OK;
 }
 
 // This ctor is used if this object will have a proto.
-XPCWrappedNative::XPCWrappedNative(already_AddRefed<nsISupports>&& aIdentity,
+XPCWrappedNative::XPCWrappedNative(nsCOMPtr<nsISupports>&& aIdentity,
                                    XPCWrappedNativeProto* aProto)
     : mMaybeProto(aProto), mSet(aProto->GetSet()) {
   MOZ_ASSERT(NS_IsMainThread());
 
   mIdentity = aIdentity;
   mFlatJSObject.setFlags(FLAT_JS_OBJECT_VALID);
 
   MOZ_ASSERT(mMaybeProto, "bad ctor param");
   MOZ_ASSERT(mSet, "bad ctor param");
 }
 
 // This ctor is used if this object will NOT have a proto.
-XPCWrappedNative::XPCWrappedNative(already_AddRefed<nsISupports>&& aIdentity,
+XPCWrappedNative::XPCWrappedNative(nsCOMPtr<nsISupports>&& aIdentity,
                                    XPCWrappedNativeScope* aScope,
-                                   already_AddRefed<XPCNativeSet>&& aSet)
-
-    : mMaybeScope(TagScope(aScope)), mSet(aSet) {
+                                   RefPtr<XPCNativeSet>&& aSet)
+    : mMaybeScope(TagScope(aScope)), mSet(std::move(aSet)) {
   MOZ_ASSERT(NS_IsMainThread());
 
   mIdentity = aIdentity;
   mFlatJSObject.setFlags(FLAT_JS_OBJECT_VALID);
 
   MOZ_ASSERT(aScope, "bad ctor param");
   MOZ_ASSERT(mSet, "bad ctor param");
 }
@@ -862,17 +861,17 @@ bool XPCWrappedNative::ExtendSet(JSConte
                                  XPCNativeInterface* aInterface) {
   if (!mSet->HasInterface(aInterface)) {
     XPCNativeSetKey key(mSet, aInterface);
     RefPtr<XPCNativeSet> newSet = XPCNativeSet::GetNewOrUsed(aCx, &key);
     if (!newSet) {
       return false;
     }
 
-    mSet = newSet.forget();
+    mSet = std::move(newSet);
   }
   return true;
 }
 
 XPCWrappedNativeTearOff* XPCWrappedNative::FindTearOff(
     JSContext* cx, XPCNativeInterface* aInterface,
     bool needJSObject /* = false */, nsresult* pError /* = nullptr */) {
   nsresult rv = NS_OK;
--- a/js/xpconnect/src/XPCWrappedNativeInfo.cpp
+++ b/js/xpconnect/src/XPCWrappedNativeInfo.cpp
@@ -464,17 +464,17 @@ already_AddRefed<XPCNativeSet> XPCNative
   }
 
   RefPtr<XPCNativeSet> set = map->Find(&key);
 
   if (set) {
     return set.forget();
   }
 
-  set = NewInstance(cx, {iface.forget()});
+  set = NewInstance(cx, {std::move(iface)});
   if (!set) {
     return nullptr;
   }
 
   if (!map->AddNew(&key, set)) {
     NS_ERROR("failed to add our set!");
     set = nullptr;
   }
@@ -676,17 +676,17 @@ already_AddRefed<XPCNativeSet> XPCNative
   RefPtr<XPCNativeSet> obj = new (place) XPCNativeSet();
 
   // Stick the nsISupports in front and skip additional nsISupport(s)
   XPCNativeInterface** outp = (XPCNativeInterface**)&obj->mInterfaces;
 
   NS_ADDREF(*(outp++) = isup);
 
   for (auto key = array.begin(); key != array.end(); key++) {
-    RefPtr<XPCNativeInterface> cur = key->forget();
+    RefPtr<XPCNativeInterface> cur = std::move(*key);
     if (isup == cur) {
       continue;
     }
     *(outp++) = cur.forget().take();
   }
   obj->mInterfaceCount = slots;
 
   return obj.forget();
--- a/js/xpconnect/src/XPCWrappedNativeProto.cpp
+++ b/js/xpconnect/src/XPCWrappedNativeProto.cpp
@@ -10,20 +10,23 @@
 #include "pratom.h"
 
 using namespace mozilla;
 
 #ifdef DEBUG
 int32_t XPCWrappedNativeProto::gDEBUG_LiveProtoCount = 0;
 #endif
 
-XPCWrappedNativeProto::XPCWrappedNativeProto(
-    XPCWrappedNativeScope* Scope, nsIClassInfo* ClassInfo,
-    already_AddRefed<XPCNativeSet>&& Set)
-    : mScope(Scope), mJSProtoObject(nullptr), mClassInfo(ClassInfo), mSet(Set) {
+XPCWrappedNativeProto::XPCWrappedNativeProto(XPCWrappedNativeScope* Scope,
+                                             nsIClassInfo* ClassInfo,
+                                             RefPtr<XPCNativeSet>&& Set)
+    : mScope(Scope),
+      mJSProtoObject(nullptr),
+      mClassInfo(ClassInfo),
+      mSet(std::move(Set)) {
   // This native object lives as long as its associated JSObject - killed
   // by finalization of the JSObject (or explicitly if Init fails).
 
   MOZ_COUNT_CTOR(XPCWrappedNativeProto);
   MOZ_ASSERT(mScope);
 
 #ifdef DEBUG
   gDEBUG_LiveProtoCount++;
@@ -112,17 +115,17 @@ XPCWrappedNativeProto* XPCWrappedNativeP
     return proto;
   }
 
   RefPtr<XPCNativeSet> set = XPCNativeSet::GetNewOrUsed(cx, classInfo);
   if (!set) {
     return nullptr;
   }
 
-  proto = new XPCWrappedNativeProto(scope, classInfo, set.forget());
+  proto = new XPCWrappedNativeProto(scope, classInfo, std::move(set));
 
   if (!proto->Init(cx, scriptable)) {
     delete proto.get();
     return nullptr;
   }
 
   map->Add(classInfo, proto);
 
--- a/js/xpconnect/src/xpcprivate.h
+++ b/js/xpconnect/src/xpcprivate.h
@@ -1236,17 +1236,17 @@ class XPCWrappedNativeProto final {
 
  protected:
   // disable copy ctor and assignment
   XPCWrappedNativeProto(const XPCWrappedNativeProto& r) = delete;
   XPCWrappedNativeProto& operator=(const XPCWrappedNativeProto& r) = delete;
 
   // hide ctor
   XPCWrappedNativeProto(XPCWrappedNativeScope* Scope, nsIClassInfo* ClassInfo,
-                        already_AddRefed<XPCNativeSet>&& Set);
+                        RefPtr<XPCNativeSet>&& Set);
 
   bool Init(JSContext* cx, nsIXPCScriptable* scriptable);
 
  private:
 #ifdef DEBUG
   static int32_t gDEBUG_LiveProtoCount;
 #endif
 
@@ -1493,23 +1493,22 @@ class XPCWrappedNative final : public ns
   void Suspect(nsCycleCollectionNoteRootCallback& cb);
   void NoteTearoffs(nsCycleCollectionTraversalCallback& cb);
 
   // Make ctor and dtor protected (rather than private) to placate nsCOMPtr.
  protected:
   XPCWrappedNative() = delete;
 
   // This ctor is used if this object will have a proto.
-  XPCWrappedNative(already_AddRefed<nsISupports>&& aIdentity,
+  XPCWrappedNative(nsCOMPtr<nsISupports>&& aIdentity,
                    XPCWrappedNativeProto* aProto);
 
   // This ctor is used if this object will NOT have a proto.
-  XPCWrappedNative(already_AddRefed<nsISupports>&& aIdentity,
-                   XPCWrappedNativeScope* aScope,
-                   already_AddRefed<XPCNativeSet>&& aSet);
+  XPCWrappedNative(nsCOMPtr<nsISupports>&& aIdentity,
+                   XPCWrappedNativeScope* aScope, RefPtr<XPCNativeSet>&& aSet);
 
   virtual ~XPCWrappedNative();
   void Destroy();
 
  private:
   enum {
     // Flags bits for mFlatJSObject:
     FLAT_JS_OBJECT_VALID = js::Bit(0)
--- a/layout/base/PresShell.cpp
+++ b/layout/base/PresShell.cpp
@@ -3133,17 +3133,17 @@ nsresult PresShell::GoToAnchor(const nsA
     }
   }
 #endif  // #ifdef ACCESSIBILITY
 
   return rv;
 }
 
 nsresult PresShell::ScrollToAnchor() {
-  nsCOMPtr<nsIContent> lastAnchor = mLastAnchorScrolledTo.forget();
+  nsCOMPtr<nsIContent> lastAnchor = std::move(mLastAnchorScrolledTo);
   if (!lastAnchor) {
     return NS_OK;
   }
 
   NS_ASSERTION(mDidInitialize, "should have done initial reflow by now");
   nsIScrollableFrame* rootScroll = GetRootScrollFrameAsScrollable();
   if (!rootScroll ||
       mLastAnchorScrollPositionY != rootScroll->GetScrollPosition().y) {
--- a/layout/base/PresShell.h
+++ b/layout/base/PresShell.h
@@ -1985,17 +1985,17 @@ class PresShell final : public nsStubDoc
    */
   class MOZ_STACK_CLASS EventHandler final {
    public:
     EventHandler() = delete;
     EventHandler(const EventHandler& aOther) = delete;
     explicit EventHandler(PresShell& aPresShell)
         : mPresShell(aPresShell), mCurrentEventInfoSetter(nullptr) {}
     explicit EventHandler(RefPtr<PresShell>&& aPresShell)
-        : mPresShell(aPresShell.forget()), mCurrentEventInfoSetter(nullptr) {}
+        : mPresShell(std::move(aPresShell)), mCurrentEventInfoSetter(nullptr) {}
 
     /**
      * HandleEvent() may dispatch aGUIEvent.  This may redirect the event to
      * another PresShell, or the event may be handled by other classes like
      * AccessibleCaretEventHub, or discarded.  Otherwise, this sets current
      * event info of mPresShell and calls HandleEventWithCurrentEventInfo()
      * to dispatch the event into the DOM tree.
      *
--- a/layout/base/nsDocumentViewer.cpp
+++ b/layout/base/nsDocumentViewer.cpp
@@ -668,17 +668,18 @@ void nsDocumentViewer::LoadStart(Documen
   MOZ_ASSERT(aDocument);
 
   if (!mDocument) {
     mDocument = aDocument;
   }
 }
 
 void nsDocumentViewer::RemoveFocusListener() {
-  if (RefPtr<nsDocViewerFocusListener> oldListener = mFocusListener.forget()) {
+  if (RefPtr<nsDocViewerFocusListener> oldListener =
+          std::move(mFocusListener)) {
     oldListener->Disconnect();
     if (mDocument) {
       mDocument->RemoveEventListener(NS_LITERAL_STRING("focus"), oldListener,
                                      false);
       mDocument->RemoveEventListener(NS_LITERAL_STRING("blur"), oldListener,
                                      false);
     }
   }
@@ -1722,17 +1723,17 @@ nsDocumentViewer::Destroy() {
   }
 
   if (mSHEntry && mDocument && !mDocument->IsBFCachingAllowed()) {
     // Just drop the SHEntry now and pretend like we never even tried to bfcache
     // this viewer.  This should only happen when someone calls
     // DisallowBFCaching() after CanSavePresentation() already ran.  Ensure that
     // the SHEntry has no viewer and its state is synced up.  We want to do this
     // via a stack reference, in case those calls mess with our members.
-    nsCOMPtr<nsISHEntry> shEntry = mSHEntry.forget();
+    nsCOMPtr<nsISHEntry> shEntry = std::move(mSHEntry);
     shEntry->SetContentViewer(nullptr);
     shEntry->SyncPresentationState();
   }
 
   // If we were told to put ourselves into session history instead of destroy
   // the presentation, do that now.
   if (mSHEntry) {
     if (mPresShell) mPresShell->Freeze();
@@ -1776,17 +1777,18 @@ nsDocumentViewer::Destroy() {
       mDocument->Sanitize();
     }
 
     // Reverse ownership. Do this *after* calling sanitize so that sanitize
     // doesn't cause mutations that make the SHEntry drop the presentation
 
     // Grab a reference to mSHEntry before calling into things like
     // SyncPresentationState that might mess with our members.
-    nsCOMPtr<nsISHEntry> shEntry = mSHEntry.forget();  // we'll need this below
+    nsCOMPtr<nsISHEntry> shEntry =
+        std::move(mSHEntry);  // we'll need this below
 
     shEntry->SetContentViewer(this);
 
     // Always sync the presentation state.  That way even if someone screws up
     // and shEntry has no window state at this point we'll be ok; we just won't
     // cache ourselves.
     shEntry->SyncPresentationState();
     shEntry->SynchronizeLayoutHistoryState();
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -7638,19 +7638,19 @@ nsLayoutUtils::SurfaceFromElementResult 
   int32_t corsmode;
   if (NS_SUCCEEDED(imgRequest->GetCORSMode(&corsmode))) {
     result.mCORSUsed = (corsmode != imgIRequest::CORS_NONE);
   }
 
   bool hadCrossOriginRedirects = true;
   imgRequest->GetHadCrossOriginRedirects(&hadCrossOriginRedirects);
 
-  result.mPrincipal = principal.forget();
+  result.mPrincipal = std::move(principal);
   result.mHadCrossOriginRedirects = hadCrossOriginRedirects;
-  result.mImageRequest = imgRequest.forget();
+  result.mImageRequest = std::move(imgRequest);
   result.mIsWriteOnly = CanvasUtils::CheckWriteOnlySecurity(
       result.mCORSUsed, result.mPrincipal, result.mHadCrossOriginRedirects);
 
   return result;
 }
 
 nsLayoutUtils::SurfaceFromElementResult nsLayoutUtils::SurfaceFromElement(
     HTMLImageElement* aElement, uint32_t aSurfaceFlags,
@@ -7741,17 +7741,17 @@ nsLayoutUtils::SurfaceFromElementResult 
     }
   }
 
   result.mCORSUsed = aElement->GetCORSMode() != CORS_NONE;
   result.mHasSize = true;
   result.mSize = result.mLayersImage->GetSize();
   result.mIntrinsicSize =
       gfx::IntSize(aElement->VideoWidth(), aElement->VideoHeight());
-  result.mPrincipal = principal.forget();
+  result.mPrincipal = std::move(principal);
   result.mHadCrossOriginRedirects = aElement->HadCrossOriginRedirects();
   result.mIsWriteOnly = CanvasUtils::CheckWriteOnlySecurity(
       result.mCORSUsed, result.mPrincipal, result.mHadCrossOriginRedirects);
 
   return result;
 }
 
 nsLayoutUtils::SurfaceFromElementResult nsLayoutUtils::SurfaceFromElement(
--- a/layout/base/nsRefreshDriver.cpp
+++ b/layout/base/nsRefreshDriver.cpp
@@ -2461,17 +2461,17 @@ void nsRefreshDriver::PVsyncActorCreated
   RefPtr<RefreshDriverTimer> vsyncRefreshDriverTimer =
       new VsyncRefreshDriverTimer(aVsyncChild);
 
   // If we are using software timer, swap current timer to
   // VsyncRefreshDriverTimer.
   if (sRegularRateTimer) {
     sRegularRateTimer->SwapRefreshDrivers(vsyncRefreshDriverTimer);
   }
-  sRegularRateTimer = vsyncRefreshDriverTimer.forget();
+  sRegularRateTimer = std::move(vsyncRefreshDriverTimer);
 }
 
 void nsRefreshDriver::DoRefresh() {
   // Don't do a refresh unless we're in a state where we should be refreshing.
   if (!IsFrozen() && mPresContext && mActiveTimer) {
     DoTick();
   }
 }
--- a/layout/generic/nsFrameSelection.cpp
+++ b/layout/generic/nsFrameSelection.cpp
@@ -2534,17 +2534,17 @@ nsresult nsFrameSelection::SelectRowOrCo
   while (true) {
     // Loop through all cells in column or row to find first and last
     nsCOMPtr<nsIContent> curCellContent =
         tableFrame->GetCellAt(rowIndex, colIndex);
     if (!curCellContent) break;
 
     if (!firstCell) firstCell = curCellContent;
 
-    lastCell = curCellContent.forget();
+    lastCell = std::move(curCellContent);
 
     // Move to next cell in cellmap, skipping spanned locations
     if (aTarget == TableSelection::Row)
       colIndex += tableFrame->GetEffectiveRowSpanAt(rowIndex, colIndex);
     else
       rowIndex += tableFrame->GetEffectiveRowSpanAt(rowIndex, colIndex);
   }
 
--- a/layout/generic/nsIFrame.h
+++ b/layout/generic/nsIFrame.h
@@ -768,17 +768,17 @@ class nsIFrame : public nsQueryFrame {
 #else
   {
   }
 #endif
 
   void SetComputedStyle(ComputedStyle* aStyle) {
     if (aStyle != mComputedStyle) {
       AssertNewStyleIsSane(*aStyle);
-      RefPtr<ComputedStyle> oldComputedStyle = mComputedStyle.forget();
+      RefPtr<ComputedStyle> oldComputedStyle = std::move(mComputedStyle);
       mComputedStyle = aStyle;
       DidSetComputedStyle(oldComputedStyle);
     }
   }
 
   /**
    * SetComputedStyleWithoutNotification is for changes to the style
    * context that should suppress style change processing, in other
--- a/layout/generic/nsTextFrame.cpp
+++ b/layout/generic/nsTextFrame.cpp
@@ -4049,17 +4049,17 @@ bool nsTextPaintStyle::InitSelectionColo
 
   // Use ::selection pseudo class if applicable.
   if (RefPtr<ComputedStyle> style =
           mFrame->ComputeSelectionStyle(selectionStatus)) {
     mSelectionBGColor =
         style->GetVisitedDependentColor(&nsStyleBackground::mBackgroundColor);
     mSelectionTextColor =
         style->GetVisitedDependentColor(&nsStyleText::mWebkitTextFillColor);
-    mSelectionPseudoStyle = style.forget();
+    mSelectionPseudoStyle = std::move(style);
     return true;
   }
 
   nscolor selectionBGColor =
       LookAndFeel::GetColor(LookAndFeel::ColorID::TextSelectBackground);
 
   if (selectionStatus == nsISelectionController::SELECTION_ATTENTION) {
     mSelectionBGColor = LookAndFeel::GetColor(
--- a/layout/generic/nsVideoFrame.cpp
+++ b/layout/generic/nsVideoFrame.cpp
@@ -229,17 +229,17 @@ already_AddRefed<Layer> nsVideoFrame::Bu
   Matrix transform = preTransform * Matrix::Translation(p.x, p.y);
 
   layer->SetBaseTransform(gfx::Matrix4x4::From2D(transform));
   layer->SetScaleToSize(scaleHint, ScaleMode::STRETCH);
 
   uint32_t flags = element->HasAlpha() ? 0 : Layer::CONTENT_OPAQUE;
   layer->SetContentFlags(flags);
 
-  RefPtr<Layer> result = layer.forget();
+  RefPtr<Layer> result = std::move(layer);
   return result.forget();
 }
 
 class DispatchResizeEvent : public Runnable {
  public:
   explicit DispatchResizeEvent(nsIContent* aContent, const nsString& aName)
       : mozilla::Runnable("DispatchResizeEvent"),
         mContent(aContent),
--- a/layout/ipc/RemoteLayerTreeOwner.cpp
+++ b/layout/ipc/RemoteLayerTreeOwner.cpp
@@ -105,17 +105,17 @@ LayerManager* RemoteLayerTreeOwner::Atta
 
   // Perhaps the document containing this frame currently has no presentation?
   if (lm && lm->GetCompositorBridgeChild() && lm != mLayerManager) {
     mLayersConnected =
         lm->GetCompositorBridgeChild()->SendAdoptChild(mLayersId);
     FrameLayerBuilder::InvalidateAllLayers(lm);
   }
 
-  mLayerManager = lm.forget();
+  mLayerManager = std::move(lm);
   return mLayerManager;
 }
 
 void RemoteLayerTreeOwner::OwnerContentChanged() {
   Unused << AttachLayerManager();
 }
 
 void RemoteLayerTreeOwner::GetTextureFactoryIdentifier(
--- a/layout/painting/FrameLayerBuilder.cpp
+++ b/layout/painting/FrameLayerBuilder.cpp
@@ -3433,17 +3433,18 @@ void ContainerState::FinishPaintedLayerD
 
   if (!data->mLayer) {
     // No layer was recycled, so we create a new one.
     RefPtr<PaintedLayer> paintedLayer = CreatePaintedLayer(data);
     data->mLayer = paintedLayer;
 
     NS_ASSERTION(FindIndexOfLayerIn(mNewChildLayers, paintedLayer) < 0,
                  "Layer already in list???");
-    mNewChildLayers[data->mNewChildLayersIndex].mLayer = paintedLayer.forget();
+    mNewChildLayers[data->mNewChildLayersIndex].mLayer =
+        std::move(paintedLayer);
   }
 
   PaintedDisplayItemLayerUserData* userData =
       GetPaintedDisplayItemLayerUserData(data->mLayer);
   NS_ASSERTION(userData, "where did our user data go?");
   userData->mLastItemCount = data->mAssignedDisplayItems.size();
 
   NewLayerEntry* newLayerEntry = &mNewChildLayers[data->mNewChildLayersIndex];
@@ -5122,17 +5123,17 @@ void ContainerState::ProcessDisplayItems
             PaintedDisplayItemLayerUserData* userData =
                 GetPaintedDisplayItemLayerUserData(layer);
             paintedLayerData->mAssignedDisplayItems.reserve(
                 userData->mLastItemCount);
 
             NS_ASSERTION(FindIndexOfLayerIn(mNewChildLayers, layer) < 0,
                          "Layer already in list???");
             mNewChildLayers[paintedLayerData->mNewChildLayersIndex].mLayer =
-                layer.forget();
+                std::move(layer);
           }
         }
       }
 
       const auto ClearLayerSelectionIfNeeded = [&]() {
         if (!InOpacity() && !InTransform()) {
           selectedLayer = nullptr;
           containerAGR = nullptr;
--- a/layout/printing/nsPrintJob.cpp
+++ b/layout/printing/nsPrintJob.cpp
@@ -2803,17 +2803,17 @@ nsresult nsPrintJob::EnablePOsForPrintin
         return NS_OK;
       }
     } else if (treatAsNonFrameset) {
       for (uint32_t i = 0; i < printData->mPrintDocList.Length(); i++) {
         nsPrintObject* po = printData->mPrintDocList.ElementAt(i);
         NS_ASSERTION(po, "nsPrintObject can't be null!");
         nsCOMPtr<nsPIDOMWindowOuter> domWin = po->mDocShell->GetWindow();
         if (IsThereARangeSelection(domWin)) {
-          printData->mCurrentFocusWin = domWin.forget();
+          printData->mCurrentFocusWin = std::move(domWin);
           SetPrintPO(po, true);
           break;
         }
       }
       return NS_OK;
     }
   }
 
--- a/layout/style/CSSPageRule.cpp
+++ b/layout/style/CSSPageRule.cpp
@@ -58,17 +58,17 @@ nsresult CSSPageRuleDeclaration::SetCSSD
   if (rule->IsReadOnly()) {
     return NS_OK;
   }
 
   if (aDecl != mDecls) {
     mDecls->SetOwningRule(nullptr);
     RefPtr<DeclarationBlock> decls = aDecl;
     Servo_PageRule_SetStyle(rule->Raw(), decls->Raw());
-    mDecls = decls.forget();
+    mDecls = std::move(decls);
     mDecls->SetOwningRule(rule);
   }
 
   return NS_OK;
 }
 
 nsDOMCSSDeclaration::ParsingEnvironment
 CSSPageRuleDeclaration::GetParsingEnvironment(
--- a/layout/style/CSSStyleRule.cpp
+++ b/layout/style/CSSStyleRule.cpp
@@ -65,17 +65,17 @@ nsresult CSSStyleRuleDeclaration::SetCSS
     return NS_OK;
   }
 
   if (RefPtr<StyleSheet> sheet = rule->GetStyleSheet()) {
     if (aDecl != mDecls) {
       mDecls->SetOwningRule(nullptr);
       RefPtr<DeclarationBlock> decls = aDecl;
       Servo_StyleRule_SetStyle(rule->Raw(), decls->Raw());
-      mDecls = decls.forget();
+      mDecls = std::move(decls);
       mDecls->SetOwningRule(rule);
     }
     sheet->RuleChanged(rule);
   }
   return NS_OK;
 }
 
 Document* CSSStyleRuleDeclaration::DocToUpdate() { return nullptr; }
--- a/layout/style/GlobalStyleSheetCache.cpp
+++ b/layout/style/GlobalStyleSheetCache.cpp
@@ -311,17 +311,17 @@ void GlobalStyleSheetCache::LoadSheetFro
   sheet->SetSharedContents(aHeader->mSheets[i]);
   sheet->SetComplete();
 
   nsCOMPtr<nsIReferrerInfo> referrerInfo =
       dom::ReferrerInfo::CreateForExternalCSSResources(sheet);
   sheet->SetReferrerInfo(referrerInfo);
   URLExtraData::sShared[i] = sheet->URLData();
 
-  *aSheet = sheet.forget();
+  *aSheet = std::move(sheet);
 }
 
 void GlobalStyleSheetCache::InitSharedSheetsInParent() {
   MOZ_ASSERT(XRE_IsParentProcess());
   MOZ_RELEASE_ASSERT(!sSharedMemory);
 
   auto shm = MakeUnique<base::SharedMemory>();
   if (NS_WARN_IF(!shm->CreateFreezeable(kSharedMemorySize))) {
--- a/layout/style/Loader.cpp
+++ b/layout/style/Loader.cpp
@@ -356,19 +356,19 @@ SheetLoadData::SheetLoadData(Loader* aLo
       mPreloadEncoding(aPreloadEncoding) {
   MOZ_ASSERT(mLoader, "Must have a loader!");
   MOZ_ASSERT(!mUseSystemPrincipal || mSyncLoad,
              "Shouldn't use system principal for async loads");
 }
 
 SheetLoadData::~SheetLoadData() {
   // Do this iteratively to avoid blowing up the stack.
-  RefPtr<SheetLoadData> next = mNext.forget();
+  RefPtr<SheetLoadData> next = std::move(mNext);
   while (next) {
-    next = next->mNext.forget();
+    next = std::move(next->mNext);
   }
 }
 
 NS_IMETHODIMP
 SheetLoadData::Run() {
   mLoader->HandleLoadEvent(*this);
   return NS_OK;
 }
--- a/layout/style/StyleSheet.cpp
+++ b/layout/style/StyleSheet.cpp
@@ -646,17 +646,17 @@ void StyleSheet::ReplaceSync(const nsACS
   if (Servo_StyleSheet_HasImportRules(rawContent)) {
     return aRv.ThrowNotAllowedError(
         "@import rules are not allowed. Use the async replace() method "
         "instead.");
   }
 
   // 5. Set sheet's rules to the new rules.
   DropRuleList();
-  Inner().mContents = rawContent.forget();
+  Inner().mContents = std::move(rawContent);
   FinishParse();
 }
 
 nsresult StyleSheet::DeleteRuleFromGroup(css::GroupRule* aGroup,
                                          uint32_t aIndex) {
   NS_ENSURE_ARG_POINTER(aGroup);
   NS_ASSERTION(IsComplete(), "No deleting from an incomplete sheet!");
   RefPtr<css::Rule> rule = aGroup->GetStyleRuleAt(aIndex);
--- a/layout/style/nsFontFaceLoader.cpp
+++ b/layout/style/nsFontFaceLoader.cpp
@@ -338,17 +338,17 @@ void nsFontFaceLoader::Cancel() {
   mUserFontEntry->LoadCanceled();
   mUserFontEntry = nullptr;
   mFontFaceSet->Document()->UnblockOnload(false);
   mFontFaceSet = nullptr;
   if (mLoadTimer) {
     mLoadTimer->Cancel();
     mLoadTimer = nullptr;
   }
-  if (nsCOMPtr<nsIChannel> channel = mChannel.forget()) {
+  if (nsCOMPtr<nsIChannel> channel = std::move(mChannel)) {
     channel->Cancel(NS_BINDING_ABORTED);
   }
 }
 
 StyleFontDisplay nsFontFaceLoader::GetFontDisplay() {
   if (!StaticPrefs::layout_css_font_display_enabled()) {
     return StyleFontDisplay::Auto;
   }
--- a/layout/svg/SVGImageContext.cpp
+++ b/layout/svg/SVGImageContext.cpp
@@ -67,13 +67,13 @@ void SVGImageContext::MaybeStoreContextP
     haveContextPaint = true;
     contextPaint->SetStrokeOpacity(style->mStrokeOpacity);
   }
 
   if (haveContextPaint) {
     if (!aContext) {
       aContext.emplace();
     }
-    aContext->mContextPaint = contextPaint.forget();
+    aContext->mContextPaint = std::move(contextPaint);
   }
 }
 
 }  // namespace mozilla
--- a/layout/svg/nsSVGImageFrame.cpp
+++ b/layout/svg/nsSVGImageFrame.cpp
@@ -572,17 +572,17 @@ nsSVGImageListener::Notify(imgIRequest* 
   }
 
   if (aType == imgINotificationObserver::SIZE_AVAILABLE) {
     // Called once the resource's dimensions have been obtained.
     nsCOMPtr<imgIContainer> image;
     aRequest->GetImage(getter_AddRefs(image));
     if (image) {
       image->SetAnimationMode(mFrame->PresContext()->ImageAnimationMode());
-      mFrame->mImageContainer = image.forget();
+      mFrame->mImageContainer = std::move(image);
     }
     mFrame->InvalidateFrame();
     nsLayoutUtils::PostRestyleEvent(mFrame->GetContent()->AsElement(),
                                     RestyleHint{0},
                                     nsChangeHint_InvalidateRenderingObservers);
     nsSVGUtils::ScheduleReflowSVG(mFrame);
   }
 
--- a/layout/svg/nsSVGMaskFrame.cpp
+++ b/layout/svg/nsSVGMaskFrame.cpp
@@ -103,26 +103,26 @@ already_AddRefed<SourceSurface> nsSVGMas
       luminanceType = LuminanceType::LINEARRGB;
     }
 
     RefPtr<SourceSurface> maskSnapshot =
         maskDT->IntoLuminanceSource(luminanceType, aParams.opacity);
     if (!maskSnapshot) {
       return nullptr;
     }
-    surface = maskSnapshot.forget();
+    surface = std::move(maskSnapshot);
   } else {
     maskDT->FillRect(maskSurfaceRect,
                      ColorPattern(Color(1.0f, 1.0f, 1.0f, aParams.opacity)),
                      DrawOptions(1, CompositionOp::OP_IN));
     RefPtr<SourceSurface> maskSnapshot = maskDT->Snapshot();
     if (!maskSnapshot) {
       return nullptr;
     }
-    surface = maskSnapshot.forget();
+    surface = std::move(maskSnapshot);
   }
 
   return surface.forget();
 }
 
 gfxRect nsSVGMaskFrame::GetMaskArea(nsIFrame* aMaskedFrame) {
   SVGMaskElement* maskElem = static_cast<SVGMaskElement*>(GetContent());
 
--- a/layout/xul/nsImageBoxFrame.cpp
+++ b/layout/xul/nsImageBoxFrame.cpp
@@ -188,17 +188,17 @@ void nsImageBoxFrame::DestroyFrom(nsIFra
 
   nsLeafBoxFrame::DestroyFrom(aDestructRoot, aPostDestroyData);
 }
 
 void nsImageBoxFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
                            nsIFrame* aPrevInFlow) {
   if (!mListener) {
     RefPtr<nsImageBoxListener> listener = new nsImageBoxListener(this);
-    mListener = listener.forget();
+    mListener = std::move(listener);
   }
 
   mSuppressStyleCheck = true;
   nsLeafBoxFrame::Init(aContent, aParent, aPrevInFlow);
   mSuppressStyleCheck = false;
 
   UpdateLoadFlags();
   UpdateImage();
--- a/layout/xul/tree/nsTreeContentView.cpp
+++ b/layout/xul/tree/nsTreeContentView.cpp
@@ -515,17 +515,17 @@ nsTreeContentView::SetTree(XULTreeElemen
     Document* document = mTree->GetComposedDoc();
     if (document) {
       document->AddObserver(this);
       mDocument = document;
     }
 
     RefPtr<dom::Element> bodyElement = mTree->GetTreeBody();
     if (bodyElement) {
-      mBody = bodyElement.forget();
+      mBody = std::move(bodyElement);
       int32_t index = 0;
       Serialize(mBody, -1, &index, mRows);
     }
   }
 
   return NS_OK;
 }
 
--- a/media/mtransport/dtlsidentity.cpp
+++ b/media/mtransport/dtlsidentity.cpp
@@ -262,19 +262,18 @@ RefPtr<DtlsIdentity> DtlsIdentity::Gener
   rv = SEC_DerSignData(arena, signedCert, innerDER.data, innerDER.len,
                        private_key.get(),
                        SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE);
   if (rv != SECSuccess) {
     return nullptr;
   }
   certificate->derCert = *signedCert;
 
-  RefPtr<DtlsIdentity> identity = new DtlsIdentity(
-      std::move(private_key), std::move(certificate), ssl_kea_ecdh);
-  return identity.forget();
+  return new DtlsIdentity(std::move(private_key), std::move(certificate),
+                          ssl_kea_ecdh);
 }
 
 const std::string DtlsIdentity::DEFAULT_HASH_ALGORITHM = "sha-256";
 
 nsresult DtlsIdentity::ComputeFingerprint(DtlsDigest* digest) const {
   const UniqueCERTCertificate& c = cert();
   MOZ_ASSERT(c);
 
--- a/media/mtransport/test/buffered_stun_socket_unittest.cpp
+++ b/media/mtransport/test/buffered_stun_socket_unittest.cpp
@@ -45,17 +45,17 @@ class BufferedStunSocketTest : public Mt
     MtransportTest::SetUp();
 
     RefPtr<DummySocket> dummy(new DummySocket());
 
     int r =
         nr_socket_buffered_stun_create(dummy->get_nr_socket(), kStunMessageLen,
                                        TURN_TCP_FRAMING, &test_socket_);
     ASSERT_EQ(0, r);
-    dummy_ = dummy.forget();  // Now owned by test_socket_.
+    dummy_ = std::move(dummy);  // Now owned by test_socket_.
 
     r = nr_str_port_to_transport_addr((char*)"192.0.2.133", 3333, IPPROTO_TCP,
                                       &remote_addr_);
     ASSERT_EQ(0, r);
 
     r = nr_socket_connect(test_socket_, &remote_addr_);
     ASSERT_EQ(0, r);
   }
--- a/media/webrtc/signaling/src/media-conduit/WebrtcMediaDataDecoderCodec.cpp
+++ b/media/webrtc/signaling/src/media-conduit/WebrtcMediaDataDecoderCodec.cpp
@@ -145,17 +145,17 @@ int32_t WebrtcMediaDataDecoder::Decode(
 int32_t WebrtcMediaDataDecoder::RegisterDecodeCompleteCallback(
     webrtc::DecodedImageCallback* aCallback) {
   mCallback = aCallback;
   return WEBRTC_VIDEO_CODEC_OK;
 }
 
 int32_t WebrtcMediaDataDecoder::Release() {
   if (mDecoder) {
-    RefPtr<MediaDataDecoder> decoder = mDecoder.forget();
+    RefPtr<MediaDataDecoder> decoder = std::move(mDecoder);
     decoder->Flush()->Then(mTaskQueue, __func__,
                            [decoder]() { decoder->Shutdown(); });
   }
 
   mNeedKeyframe = true;
   mError = NS_OK;
 
   return WEBRTC_VIDEO_CODEC_OK;
--- a/media/webrtc/signaling/src/media-conduit/WebrtcMediaDataEncoderCodec.cpp
+++ b/media/webrtc/signaling/src/media-conduit/WebrtcMediaDataEncoderCodec.cpp
@@ -165,17 +165,17 @@ int32_t WebrtcMediaDataEncoder::Register
   return WEBRTC_VIDEO_CODEC_OK;
 }
 
 int32_t WebrtcMediaDataEncoder::Shutdown() {
   LOG("Release encoder");
   OwnerThread()->Dispatch(NS_NewRunnableFunction(
       "WebrtcMediaDataEncoder::Shutdown",
       [self = RefPtr<WebrtcMediaDataEncoder>(this),
-       encoder = RefPtr<MediaDataEncoder>(mEncoder.forget())]() {
+       encoder = RefPtr<MediaDataEncoder>(std::move(mEncoder))]() {
         self->mCallback = nullptr;
         self->mError = NS_OK;
         encoder->Shutdown();
       }));
   return WEBRTC_VIDEO_CODEC_OK;
 }
 
 RefPtr<MediaData> WebrtcMediaDataEncoder::CreateVideoDataFromWebrtcVideoFrame(
@@ -200,17 +200,17 @@ RefPtr<MediaData> WebrtcMediaDataEncoder
   RefPtr<PlanarYCbCrImage> image =
       new RecyclingPlanarYCbCrImage(new BufferRecycleBin());
   image->CopyData(yCbCrData);
 
   RefPtr<MediaData> data = VideoData::CreateFromImage(
       image->GetSize(), 0, TimeUnit::FromMicroseconds(aFrame.timestamp_us()),
       TimeUnit::FromSeconds(1.0 / mMaxFrameRate), image, aIsKeyFrame,
       TimeUnit::FromMicroseconds(aFrame.timestamp()));
-  return data.forget();
+  return data;
 }
 
 int32_t WebrtcMediaDataEncoder::Encode(
     const webrtc::VideoFrame& aInputFrame,
     const webrtc::CodecSpecificInfo* aCodecSpecificInfo,
     const std::vector<webrtc::FrameType>* aFrameTypes) {
   if (!mCallback || !mEncoder) {
     return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
--- a/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp
+++ b/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp
@@ -1669,17 +1669,17 @@ class MediaPipelineReceiveVideo::Pipelin
       // This isn't the best default.
       yuvData.mYUVColorSpace = gfx::YUVColorSpace::BT601;
 
       if (!yuvImage->CopyData(yuvData)) {
         MOZ_ASSERT(false);
         return;
       }
 
-      image = yuvImage.forget();
+      image = std::move(yuvImage);
     }
 
     VideoSegment segment;
     auto size = image->GetSize();
     segment.AppendFrame(image.forget(), size, principal);
     mSource->AppendData(&segment);
   }
 
--- a/mfbt/RefPtr.h
+++ b/mfbt/RefPtr.h
@@ -208,17 +208,19 @@ class MOZ_IS_REFPTR RefPtr {
   }
 
   RefPtr<T>& operator=(const nsQueryReferent& aQueryReferent);
   RefPtr<T>& operator=(const nsCOMPtr_helper& aHelper);
 #if defined(XP_WIN)
   RefPtr<T>& operator=(const mozilla::mscom::AgileReference& aAgileRef);
 #endif  // defined(XP_WIN)
 
-  RefPtr<T>& operator=(RefPtr<T>&& aRefPtr) {
+  template <typename I,
+            typename = std::enable_if_t<std::is_convertible_v<I*, T*>>>
+  RefPtr<T>& operator=(RefPtr<I>&& aRefPtr) {
     assign_assuming_AddRef(aRefPtr.forget().take());
     return *this;
   }
 
   // Defined in OwningNonNull.h
   template <class U>
   RefPtr<T>& operator=(const mozilla::OwningNonNull<U>& aOther);
 
--- a/modules/libjar/nsJAR.cpp
+++ b/modules/libjar/nsJAR.cpp
@@ -687,18 +687,20 @@ nsZipReaderCache::GetFd(nsIFile* zipFile
   mZips.Get(uri, getter_AddRefs(zip));
   if (!zip) {
     return NS_ERROR_FAILURE;
   }
 
   zip->ClearReleaseTime();
   rv = zip->GetNSPRFileDesc(aRetVal);
   // Do this to avoid possible deadlock on mLock with ReleaseZip().
-  MutexAutoUnlock unlock(mLock);
-  RefPtr<nsJAR> zipTemp = zip.forget();
+  {
+    MutexAutoUnlock unlock(mLock);
+    zip = nullptr;
+  }
   return rv;
 #endif /* XP_WIN */
 }
 
 nsresult nsZipReaderCache::ReleaseZip(nsJAR* zip) {
   nsresult rv;
   MutexAutoLock lock(mLock);
 
--- a/modules/libpref/Preferences.cpp
+++ b/modules/libpref/Preferences.cpp
@@ -3658,17 +3658,17 @@ void Preferences::InitializeUserPrefs() 
   sPreferences->ResetUserPrefs();
 
   nsCOMPtr<nsIFile> prefsFile = sPreferences->ReadSavedPrefs();
   sPreferences->ReadUserOverridePrefs();
 
   sPreferences->mDirty = false;
 
   // Don't set mCurrentFile until we're done so that dirty flags work properly.
-  sPreferences->mCurrentFile = prefsFile.forget();
+  sPreferences->mCurrentFile = std::move(prefsFile);
 }
 
 /* static */
 void Preferences::FinishInitializingUserPrefs() {
   sPreferences->NotifyServiceObservers(NS_PREFSERVICE_READ_TOPIC_ID);
 
   // At this point all the prefs files have been read and telemetry has been
   // initialized. Send all the file load measurements to telemetry.
--- a/netwerk/base/NetworkConnectivityService.cpp
+++ b/netwerk/base/NetworkConnectivityService.cpp
@@ -26,17 +26,17 @@ already_AddRefed<NetworkConnectivityServ
 NetworkConnectivityService::GetSingleton() {
   if (gConnService) {
     return do_AddRef(gConnService);
   }
 
   RefPtr<NetworkConnectivityService> service = new NetworkConnectivityService();
   service->Init();
 
-  gConnService = service.forget();
+  gConnService = std::move(service);
   ClearOnShutdown(&gConnService);
   return do_AddRef(gConnService);
 }
 
 nsresult NetworkConnectivityService::Init() {
   nsCOMPtr<nsIObserverService> observerService =
       mozilla::services::GetObserverService();
   observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
--- a/netwerk/base/TLSServerSocket.cpp
+++ b/netwerk/base/TLSServerSocket.cpp
@@ -276,17 +276,17 @@ TLSServerConnectionInfo::TLSServerConnec
       mMacLength(0),
       mLock("TLSServerConnectionInfo.mLock"),
       mSecurityObserver(nullptr) {}
 
 TLSServerConnectionInfo::~TLSServerConnectionInfo() {
   RefPtr<nsITLSServerSecurityObserver> observer;
   {
     MutexAutoLock lock(mLock);
-    observer = mSecurityObserver.forget();
+    observer = ToRefPtr(std::move(mSecurityObserver));
   }
 
   if (observer) {
     NS_ReleaseOnMainThreadSystemGroup(
         "TLSServerConnectionInfo::mSecurityObserver", observer.forget());
   }
 }
 
--- a/netwerk/base/nsFileStreams.cpp
+++ b/netwerk/base/nsFileStreams.cpp
@@ -276,17 +276,17 @@ nsresult nsFileStreamBase::MaybeOpen(nsI
   mOpenParams.perm = aPerm;
 
   if (aDeferred) {
     // Clone the file, as it may change between now and the deferred open
     nsCOMPtr<nsIFile> file;
     nsresult rv = aFile->Clone(getter_AddRefs(file));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    mOpenParams.localFile = file.forget();
+    mOpenParams.localFile = std::move(file);
     NS_ENSURE_TRUE(mOpenParams.localFile, NS_ERROR_UNEXPECTED);
 
     mState = eDeferredOpen;
     return NS_OK;
   }
 
   mOpenParams.localFile = aFile;
 
--- a/netwerk/base/nsIURIMutator.idl
+++ b/netwerk/base/nsIURIMutator.idl
@@ -50,28 +50,28 @@ protected:
 
   MOZ_MUST_USE nsresult InitFromInputStream(nsIObjectInputStream* aStream)
   {
     RefPtr<T> uri = Create();
     nsresult rv = uri->ReadPrivate(aStream);
     if (NS_FAILED(rv)) {
       return rv;
     }
-    mURI = uri.forget();
+    mURI = std::move(uri);
     return NS_OK;
   }
 
   MOZ_MUST_USE nsresult InitFromIPCParams(const mozilla::ipc::URIParams& aParams)
   {
     RefPtr<T> uri = Create();
     bool ret = uri->Deserialize(aParams);
     if (!ret) {
       return NS_ERROR_FAILURE;
     }
-    mURI = uri.forget();
+    mURI = std::move(uri);
     return NS_OK;
   }
 
   MOZ_MUST_USE nsresult InitFromSpec(const nsACString& aSpec)
   {
     nsresult rv = NS_OK;
     RefPtr<T> uri;
     if (mURI) {
@@ -80,17 +80,17 @@ protected:
     } else {
       uri = Create();
     }
 
     rv = uri->SetSpecInternal(aSpec);
     if (NS_FAILED(rv)) {
       return rv;
     }
-    mURI = uri.forget();
+    mURI = std::move(uri);
     return NS_OK;
   }
 
   RefPtr<T> mURI;
 };
 
 // Since most implementations of nsIURIMutator would extend BaseURIMutator,
 // some methods would have the same implementation. We provide a useful macro
--- a/netwerk/base/nsServerSocket.cpp
+++ b/netwerk/base/nsServerSocket.cpp
@@ -203,17 +203,17 @@ void nsServerSocket::OnSocketDetached(PR
 
   if (mListener) {
     mListener->OnStopListening(this, mCondition);
 
     // need to atomically clear mListener.  see our Close() method.
     RefPtr<nsIServerSocketListener> listener = nullptr;
     {
       MutexAutoLock lock(mLock);
-      listener = mListener.forget();
+      listener = ToRefPtr(std::move(mListener));
     }
 
     // XXX we need to proxy the release to the listener's target thread to work
     // around bug 337492.
     if (listener) {
       NS_ProxyRelease("nsServerSocket::mListener", mListenerTarget,
                       listener.forget());
     }
--- a/netwerk/base/nsSocketTransport2.cpp
+++ b/netwerk/base/nsSocketTransport2.cpp
@@ -272,17 +272,17 @@ void nsSocketInputStream::OnSocketReady(
     MutexAutoLock lock(mTransport->mLock);
 
     // update condition, but be careful not to erase an already
     // existing error condition.
     if (NS_SUCCEEDED(mCondition)) mCondition = condition;
 
     // ignore event if only waiting for closure and not closed.
     if (NS_FAILED(mCondition) || !(mCallbackFlags & WAIT_CLOSURE_ONLY)) {
-      callback = mCallback.forget();
+      callback = std::move(mCallback);
       mCallbackFlags = 0;
     }
   }
 
   if (callback) callback->OnInputStreamReady(this);
 }
 
 NS_IMPL_QUERY_INTERFACE(nsSocketInputStream, nsIInputStream,
@@ -504,17 +504,17 @@ void nsSocketOutputStream::OnSocketReady
     MutexAutoLock lock(mTransport->mLock);
 
     // update condition, but be careful not to erase an already
     // existing error condition.
     if (NS_SUCCEEDED(mCondition)) mCondition = condition;
 
     // ignore event if only waiting for closure and not closed.
     if (NS_FAILED(mCondition) || !(mCallbackFlags & WAIT_CLOSURE_ONLY)) {
-      callback = mCallback.forget();
+      callback = std::move(mCallback);
       mCallbackFlags = 0;
     }
   }
 
   if (callback) callback->OnOutputStreamReady(this);
 }
 
 NS_IMPL_QUERY_INTERFACE(nsSocketOutputStream, nsIOutputStream,
--- a/netwerk/base/nsStandardURL.h
+++ b/netwerk/base/nsStandardURL.h
@@ -364,17 +364,17 @@ class nsStandardURL : public nsIFileURL,
       } else {
         uri = Create();
       }
       nsresult rv =
           uri->Init(aURLType, aDefaultPort, aSpec, aCharset, aBaseURI);
       if (NS_FAILED(rv)) {
         return rv;
       }
-      BaseURIMutator<T>::mURI = uri.forget();
+      BaseURIMutator<T>::mURI = std::move(uri);
       return NS_OK;
     }
 
     MOZ_MUST_USE NS_IMETHODIMP
     SetDefaultPort(int32_t aNewDefaultPort, nsIURIMutator** aMutator) override {
       if (!BaseURIMutator<T>::mURI) {
         return NS_ERROR_NULL_POINTER;
       }
--- a/netwerk/base/nsUDPSocket.cpp
+++ b/netwerk/base/nsUDPSocket.cpp
@@ -456,17 +456,17 @@ void nsUDPSocket::OnSocketDetached(PRFil
     CloseSocket();
   }
 
   if (mListener) {
     // need to atomically clear mListener.  see our Close() method.
     RefPtr<nsIUDPSocketListener> listener = nullptr;
     {
       MutexAutoLock lock(mLock);
-      listener = mListener.forget();
+      listener = ToRefPtr(std::move(mListener));
     }
 
     if (listener) {
       listener->OnStopListening(this, mCondition);
       NS_ProxyRelease("nsUDPSocket::mListener", mListenerTarget,
                       listener.forget());
     }
   }
--- a/netwerk/cache2/CacheFile.cpp
+++ b/netwerk/cache2/CacheFile.cpp
@@ -312,17 +312,17 @@ nsresult CacheFile::OnChunkRead(nsresult
        this, static_cast<uint32_t>(aResult), aChunk, index));
 
   if (aChunk->mDiscardedChunk) {
     // We discard only unused chunks, so it must be still unused when reading
     // data finishes.
     MOZ_ASSERT(aChunk->mRefCnt == 2);
     aChunk->mActiveChunk = false;
     ReleaseOutsideLock(
-        RefPtr<CacheFileChunkListener>(aChunk->mFile.forget()).forget());
+        RefPtr<CacheFileChunkListener>(std::move(aChunk->mFile)));
 
     DebugOnly<bool> removed = mDiscardedChunks.RemoveElement(aChunk);
     MOZ_ASSERT(removed);
     return NS_OK;
   }
 
   if (NS_FAILED(aResult)) {
     SetError(aResult);
@@ -357,17 +357,17 @@ nsresult CacheFile::OnChunkWritten(nsres
   MOZ_ASSERT(mHandle);
 
   if (aChunk->mDiscardedChunk) {
     // We discard only unused chunks, so it must be still unused when writing
     // data finishes.
     MOZ_ASSERT(aChunk->mRefCnt == 2);
     aChunk->mActiveChunk = false;
     ReleaseOutsideLock(
-        RefPtr<CacheFileChunkListener>(aChunk->mFile.forget()).forget());
+        RefPtr<CacheFileChunkListener>(std::move(aChunk->mFile)));
 
     DebugOnly<bool> removed = mDiscardedChunks.RemoveElement(aChunk);
     MOZ_ASSERT(removed);
     return NS_OK;
   }
 
   if (NS_FAILED(aResult)) {
     SetError(aResult);
@@ -1704,17 +1704,17 @@ nsresult CacheFile::DeactivateChunk(Cach
 
       // somebody got the reference before the lock was acquired
       return NS_OK;
     }
 
     if (aChunk->mDiscardedChunk) {
       aChunk->mActiveChunk = false;
       ReleaseOutsideLock(
-          RefPtr<CacheFileChunkListener>(aChunk->mFile.forget()).forget());
+          RefPtr<CacheFileChunkListener>(std::move(aChunk->mFile)));
 
       DebugOnly<bool> removed = mDiscardedChunks.RemoveElement(aChunk);
       MOZ_ASSERT(removed);
       return NS_OK;
     }
 
 #ifdef DEBUG
     {
@@ -1786,18 +1786,17 @@ nsresult CacheFile::DeactivateChunk(Cach
 
   return NS_OK;
 }
 
 void CacheFile::RemoveChunkInternal(CacheFileChunk* aChunk, bool aCacheChunk) {
   AssertOwnsLock();
 
   aChunk->mActiveChunk = false;
-  ReleaseOutsideLock(
-      RefPtr<CacheFileChunkListener>(aChunk->mFile.forget()).forget());
+  ReleaseOutsideLock(RefPtr<CacheFileChunkListener>(std::move(aChunk->mFile)));
 
   if (aCacheChunk) {
     mCachedChunks.Put(aChunk->Index(), aChunk);
   }
 
   mChunks.Remove(aChunk->Index());
 }
 
@@ -2462,26 +2461,26 @@ nsresult CacheFile::PadChunkWithZeroes(u
 
   LOG(
       ("CacheFile::PadChunkWithZeroes() - Zeroing hole in chunk %d, range %d-%d"
        " [this=%p]",
        aChunkIdx, chunk->DataSize(), kChunkSize - 1, this));
 
   CacheFileChunkWriteHandle hnd = chunk->GetWriteHandle(kChunkSize);
   if (!hnd.Buf()) {
-    ReleaseOutsideLock(chunk.forget());
+    ReleaseOutsideLock(std::move(chunk));
     SetError(NS_ERROR_OUT_OF_MEMORY);
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   uint32_t offset = hnd.DataSize();
   memset(hnd.Buf() + offset, 0, kChunkSize - offset);
   hnd.UpdateDataSize(offset, kChunkSize - offset);
 
-  ReleaseOutsideLock(chunk.forget());
+  ReleaseOutsideLock(std::move(chunk));
 
   return NS_OK;
 }
 
 void CacheFile::SetError(nsresult aStatus) {
   AssertOwnsLock();
 
   if (NS_SUCCEEDED(mStatus)) {
--- a/netwerk/cache2/CacheFileIOManager.cpp
+++ b/netwerk/cache2/CacheFileIOManager.cpp
@@ -1127,17 +1127,17 @@ nsresult CacheFileIOManager::Init() {
     return NS_ERROR_ALREADY_INITIALIZED;
   }
 
   RefPtr<CacheFileIOManager> ioMan = new CacheFileIOManager();
 
   nsresult rv = ioMan->InitInternal();
   NS_ENSURE_SUCCESS(rv, rv);
 
-  gInstance = ioMan.forget();
+  gInstance = std::move(ioMan);
   return NS_OK;
 }
 
 nsresult CacheFileIOManager::InitInternal() {
   nsresult rv;
 
   mIOThread = new CacheIOThread();
 
--- a/netwerk/cache2/CacheFileInputStream.cpp
+++ b/netwerk/cache2/CacheFileInputStream.cpp
@@ -286,17 +286,17 @@ void CacheFileInputStream::CleanUp() {
   if (mChunk) {
     ReleaseChunk();
   }
 
   // TODO propagate error from input stream to other streams ???
 
   MaybeNotifyListener();
 
-  mFile->ReleaseOutsideLock(mCacheEntryHandle.forget());
+  mFile->ReleaseOutsideLock(std::move(mCacheEntryHandle));
 }
 
 NS_IMETHODIMP
 CacheFileInputStream::AsyncWait(nsIInputStreamCallback* aCallback,
                                 uint32_t aFlags, uint32_t aRequestedCount,
                                 nsIEventTarget* aEventTarget) {
   CacheFileAutoLock lock(mFile);
 
@@ -520,17 +520,17 @@ void CacheFileInputStream::ReleaseChunk(
         ("CacheFileInputStream::ReleaseChunk() - Canceling waiting for update. "
          "[this=%p]",
          this));
 
     mChunk->CancelWait(this);
     mWaitingForUpdate = false;
   }
 
-  mFile->ReleaseOutsideLock(mChunk.forget());
+  mFile->ReleaseOutsideLock(std::move(mChunk));
 }
 
 void CacheFileInputStream::EnsureCorrectChunk(bool aReleaseOnly) {
   mFile->AssertOwnsLock();
 
   LOG(("CacheFileInputStream::EnsureCorrectChunk() [this=%p, releaseOnly=%d]",
        this, aReleaseOnly));
 
--- a/netwerk/cache2/CacheFileOutputStream.cpp
+++ b/netwerk/cache2/CacheFileOutputStream.cpp
@@ -355,17 +355,17 @@ void CacheFileOutputStream::ReleaseChunk
   // that was added when the chunk was created in CacheFile::GetChunkLocked.
   if (mChunk->DataSize() == 0) {
     // It must be due to a failure, we don't create a new chunk when we don't
     // have data to write.
     MOZ_ASSERT(NS_FAILED(mChunk->GetStatus()));
     mFile->mMetadata->RemoveHash(mChunk->Index());
   }
 
-  mFile->ReleaseOutsideLock(mChunk.forget());
+  mFile->ReleaseOutsideLock(std::move(mChunk));
 }
 
 void CacheFileOutputStream::EnsureCorrectChunk(bool aReleaseOnly) {
   mFile->AssertOwnsLock();
 
   LOG(("CacheFileOutputStream::EnsureCorrectChunk() [this=%p, releaseOnly=%d]",
        this, aReleaseOnly));
 
--- a/netwerk/cache2/CacheIndex.cpp
+++ b/netwerk/cache2/CacheIndex.cpp
@@ -288,17 +288,17 @@ nsresult CacheIndex::Init(nsIFile* aCach
     return NS_ERROR_ALREADY_INITIALIZED;
   }
 
   RefPtr<CacheIndex> idx = new CacheIndex();
 
   nsresult rv = idx->InitInternal(aCacheDirectory);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  gInstance = idx.forget();
+  gInstance = std::move(idx);
   return NS_OK;
 }
 
 nsresult CacheIndex::InitInternal(nsIFile* aCacheDirectory) {
   nsresult rv;
 
   rv = aCacheDirectory->Clone(getter_AddRefs(mCacheDirectory));
   NS_ENSURE_SUCCESS(rv, rv);
--- a/netwerk/cache2/OldWrappers.cpp
+++ b/netwerk/cache2/OldWrappers.cpp
@@ -723,19 +723,19 @@ NS_IMETHODIMP
         mozilla::Telemetry::AccumulateTimeDelta(
             mozilla::Telemetry::NETWORK_CACHE_V1_HIT_TIME_MS, mLoadStart);
       }
     }
 
     if (!(mFlags & CHECK_MULTITHREADED)) Check();
 
     // break cycles
-    nsCOMPtr<nsICacheEntryOpenCallback> cb = mCallback.forget();
+    nsCOMPtr<nsICacheEntryOpenCallback> cb = std::move(mCallback);
     mCacheThread = nullptr;
-    nsCOMPtr<nsICacheEntry> entry = mCacheEntry.forget();
+    nsCOMPtr<nsICacheEntry> entry = std::move(mCacheEntry);
 
     rv = cb->OnCacheEntryAvailable(entry, mNew, mAppCache, mStatus);
 
     if (NS_FAILED(rv) && entry) {
       LOG(("  cb->OnCacheEntryAvailable failed with rv=0x%08" PRIx32,
            static_cast<uint32_t>(rv)));
       if (mNew)
         entry->AsyncDoom(nullptr);
--- a/netwerk/dns/nsHostResolver.cpp
+++ b/netwerk/dns/nsHostResolver.cpp
@@ -640,17 +640,17 @@ nsresult nsHostResolver::Init() {
 
   nsCOMPtr<nsIThreadPool> threadPool = new nsThreadPool();
   MOZ_ALWAYS_SUCCEEDS(threadPool->SetThreadLimit(MAX_RESOLVER_THREADS));
   MOZ_ALWAYS_SUCCEEDS(threadPool->SetIdleThreadLimit(MAX_RESOLVER_THREADS));
   MOZ_ALWAYS_SUCCEEDS(threadPool->SetIdleThreadTimeout(poolTimeoutMs));
   MOZ_ALWAYS_SUCCEEDS(
       threadPool->SetThreadStackSize(nsIThreadManager::kThreadPoolStackSize));
   MOZ_ALWAYS_SUCCEEDS(threadPool->SetName(NS_LITERAL_CSTRING("DNS Resolver")));
-  mResolverThreads = threadPool.forget();
+  mResolverThreads = ToRefPtr(std::move(threadPool));
 
   return NS_OK;
 }
 
 void nsHostResolver::ClearPendingQueue(
     LinkedList<RefPtr<nsHostRecord>>& aPendingQ) {
   // loop through pending queue, erroring out pending lookups.
   if (!aPendingQ.isEmpty()) {
@@ -1871,26 +1871,26 @@ nsHostResolver::LookupStatus nsHostResol
   // previous lookup result expired and we're reresolving it or we get
   // a late second TRR response.
   if (!mShutdown) {
     MutexAutoLock lock(addrRec->addr_info_lock);
     RefPtr<AddrInfo> old_addr_info;
     if (different_rrset(addrRec->addr_info, newRRSet)) {
       LOG(("nsHostResolver record %p new gencnt\n", addrRec.get()));
       old_addr_info = addrRec->addr_info;
-      addrRec->addr_info = newRRSet.forget();
+      addrRec->addr_info = std::move(newRRSet);
       addrRec->addr_info_gencnt++;
     } else {
       if (addrRec->addr_info && newRRSet) {
         addrRec->addr_info->ttl = newRRSet->ttl;
         // Update trr timings
         addrRec->addr_info->SetTrrFetchDuration(newRRSet->GetTrrFetchDuration());
         addrRec->addr_info->SetTrrFetchDurationNetworkOnly(newRRSet->GetTrrFetchDurationNetworkOnly());
       }
-      old_addr_info = newRRSet.forget();
+      old_addr_info = std::move(newRRSet);
     }
     addrRec->negative = !addrRec->addr_info;
     PrepareRecordExpirationAddrRecord(addrRec);
   }
 
   bool doCallbacks = true;
 
   if (trrResult && addrRec->mDidCallbacks) {
--- a/netwerk/protocol/file/nsFileChannel.cpp
+++ b/netwerk/protocol/file/nsFileChannel.cpp
@@ -363,17 +363,17 @@ nsresult nsFileChannel::OpenContentStrea
     if (NS_FAILED(rv)) return rv;
 
     RefPtr<nsFileUploadContentStream> uploadStream =
         new nsFileUploadContentStream(async, fileStream, mUploadStream,
                                       mUploadLength, this);
     if (!uploadStream || !uploadStream->IsInitialized()) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
-    stream = uploadStream.forget();
+    stream = std::move(uploadStream);
 
     mContentLength = 0;
 
     // Since there isn't any content to speak of we just set the content-type
     // to something other than "unknown" to avoid triggering the content-type
     // sniffer code in nsBaseChannel.
     // However, don't override explicitly set types.
     if (!HasContentTypeHint())
--- a/netwerk/protocol/http/HttpBackgroundChannelChild.cpp
+++ b/netwerk/protocol/http/HttpBackgroundChannelChild.cpp
@@ -246,26 +246,27 @@ void HttpBackgroundChannelChild::ActorDe
   // remove the HttpChannelChild reference and notify background channel
   // destroyed immediately.
   if (aWhy == Deletion && !mQueuedRunnables.IsEmpty()) {
     LOG(("  > pending until queued messages are flushed\n"));
     RefPtr<HttpBackgroundChannelChild> self = this;
     mQueuedRunnables.AppendElement(NS_NewRunnableFunction(
         "HttpBackgroundChannelChild::ActorDestroy", [self]() {
           MOZ_ASSERT(OnSocketThread());
-          RefPtr<HttpChannelChild> channelChild = self->mChannelChild.forget();
+          RefPtr<HttpChannelChild> channelChild =
+              std::move(self->mChannelChild);
 
           if (channelChild) {
             channelChild->OnBackgroundChildDestroyed(self);
           }
         }));
     return;
   }
 
   if (mChannelChild) {
-    RefPtr<HttpChannelChild> channelChild = mChannelChild.forget();
+    RefPtr<HttpChannelChild> channelChild = std::move(mChannelChild);
 
     channelChild->OnBackgroundChildDestroyed(this);
   }
 }
 
 }  // namespace net
 }  // namespace mozilla
--- a/netwerk/protocol/http/HttpBackgroundChannelParent.cpp
+++ b/netwerk/protocol/http/HttpBackgroundChannelParent.cpp
@@ -270,17 +270,18 @@ void HttpBackgroundChannelParent::ActorD
 
   mIPCOpened = false;
 
   RefPtr<HttpBackgroundChannelParent> self = this;
   DebugOnly<nsresult> rv = NS_DispatchToMainThread(NS_NewRunnableFunction(
       "net::HttpBackgroundChannelParent::ActorDestroy", [self]() {
         MOZ_ASSERT(NS_IsMainThread());
 
-        RefPtr<HttpChannelParent> channelParent = self->mChannelParent.forget();
+        RefPtr<HttpChannelParent> channelParent =
+            std::move(self->mChannelParent);
 
         if (channelParent) {
           channelParent->OnBackgroundParentDestroyed();
         }
       }));
   MOZ_ASSERT(NS_SUCCEEDED(rv));
 }
 
--- a/netwerk/protocol/http/HttpChannelChild.cpp
+++ b/netwerk/protocol/http/HttpChannelChild.cpp
@@ -215,17 +215,17 @@ void HttpChannelChild::ReleaseMainThread
     // take care of releasing references
     return;
   }
 
   nsTArray<nsCOMPtr<nsISupports>> arrayToRelease;
   arrayToRelease.AppendElement(mRedirectChannelChild.forget());
 
   // To solve multiple inheritence of nsISupports in InterceptStreamListener
-  nsCOMPtr<nsIStreamListener> listener = mInterceptListener.forget();
+  nsCOMPtr<nsIStreamListener> listener = std::move(mInterceptListener);
   arrayToRelease.AppendElement(listener.forget());
 
   arrayToRelease.AppendElement(mInterceptedRedirectListener.forget());
   arrayToRelease.AppendElement(mInterceptedRedirectContext.forget());
 
   NS_DispatchToMainThread(new ProxyReleaseRunnable(std::move(arrayToRelease)));
 }
 //-----------------------------------------------------------------------------
@@ -335,17 +335,17 @@ void HttpChannelChild::OnBackgroundChild
 
     // mBgChild might be removed or replaced while the original background
     // channel is destroyed on STS thread.
     if (aBgChild != mBgChild) {
       return;
     }
 
     mBgChild = nullptr;
-    callback = mBgInitFailCallback.forget();
+    callback = std::move(mBgInitFailCallback);
   }
 
   if (callback) {
     nsCOMPtr<nsIEventTarget> neckoTarget = GetNeckoTarget();
     neckoTarget->Dispatch(callback, NS_DISPATCH_NORMAL);
   }
 }
 
@@ -1327,17 +1327,17 @@ void HttpChannelChild::CleanupBackground
        this, mBgChild.get()));
 
   mBgInitFailCallback = nullptr;
 
   if (!mBgChild) {
     return;
   }
 
-  RefPtr<HttpBackgroundChannelChild> bgChild = mBgChild.forget();
+  RefPtr<HttpBackgroundChannelChild> bgChild = std::move(mBgChild);
 
   MOZ_RELEASE_ASSERT(gSocketTransportService);
   if (!OnSocketThread()) {
     gSocketTransportService->Dispatch(
         NewRunnableMethod("HttpBackgroundChannelChild::OnChannelClosed",
                           bgChild,
                           &HttpBackgroundChannelChild::OnChannelClosed),
         NS_DISPATCH_NORMAL);
@@ -2043,17 +2043,17 @@ HttpChannelChild::ConnectParent(uint32_t
             "HttpBackgroundChannelChild::Init", bgChild,
             &HttpBackgroundChannelChild::Init, std::move(self)),
         NS_DISPATCH_NORMAL);
 
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
 
-    mBgChild = bgChild.forget();
+    mBgChild = std::move(bgChild);
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HttpChannelChild::CompleteRedirectSetup(nsIStreamListener* aListener,
                                         nsISupports* aContext) {
@@ -2157,17 +2157,17 @@ HttpChannelChild::OnRedirectVerifyCallba
 
     RefPtr<InterceptStreamListener> streamListener =
         new InterceptStreamListener(redirectedChannel, nullptr);
 
     nsCOMPtr<nsIEventTarget> neckoTarget = GetNeckoTarget();
     MOZ_ASSERT(neckoTarget);
 
     nsCOMPtr<nsIInterceptedBodyCallback> callback =
-        mSynthesizedCallback.forget();
+        std::move(mSynthesizedCallback);
 
     Unused << neckoTarget->Dispatch(
         new OverrideRunnable(this, redirectedChannel, streamListener,
                              mSynthesizedInput, callback,
                              std::move(mResponseHead), mSynthesizedCacheInfo),
         NS_DISPATCH_NORMAL);
 
     return NS_OK;
@@ -2783,17 +2783,17 @@ nsresult HttpChannelChild::ContinueAsync
 
     MOZ_RELEASE_ASSERT(gSocketTransportService);
 
     // Service worker might use the same HttpChannelChild to do async open
     // twice. Need to disconnect with previous background channel before
     // creating the new one, to prevent receiving further notification
     // from it.
     if (mBgChild) {
-      RefPtr<HttpBackgroundChannelChild> prevBgChild = mBgChild.forget();
+      RefPtr<HttpBackgroundChannelChild> prevBgChild = std::move(mBgChild);
       gSocketTransportService->Dispatch(
           NewRunnableMethod("HttpBackgroundChannelChild::OnChannelClosed",
                             prevBgChild,
                             &HttpBackgroundChannelChild::OnChannelClosed),
           NS_DISPATCH_NORMAL);
     }
 
     MOZ_ASSERT(!mBgInitFailCallback);
@@ -2811,17 +2811,17 @@ nsresult HttpChannelChild::ContinueAsync
             "HttpBackgroundChannelChild::Init", bgChild,
             &HttpBackgroundChannelChild::Init, self),
         NS_DISPATCH_NORMAL);
 
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
 
-    mBgChild = bgChild.forget();
+    mBgChild = std::move(bgChild);
   }
 
   return NS_OK;
 }
 
 //-----------------------------------------------------------------------------
 // HttpChannelChild::nsIHttpChannel
 //-----------------------------------------------------------------------------
--- a/netwerk/protocol/http/HttpChannelParent.cpp
+++ b/netwerk/protocol/http/HttpChannelParent.cpp
@@ -221,17 +221,17 @@ void HttpChannelParent::OnBackgroundPare
 }
 
 void HttpChannelParent::CleanupBackgroundChannel() {
   LOG(("HttpChannelParent::CleanupBackgroundChannel [this=%p bgParent=%p]\n",
        this, mBgParent.get()));
   MOZ_ASSERT(NS_IsMainThread());
 
   if (mBgParent) {
-    RefPtr<HttpBackgroundChannelParent> bgParent = mBgParent.forget();
+    RefPtr<HttpBackgroundChannelParent> bgParent = std::move(mBgParent);
     bgParent->OnChannelClosed();
     return;
   }
 
   // The nsHttpChannel may have a reference to this parent, release it
   // to avoid circular references.
   RefPtr<nsHttpChannel> httpChannelImpl = do_QueryObject(mChannel);
   if (httpChannelImpl) {
@@ -642,18 +642,18 @@ bool HttpChannelParent::DoAsyncOpen(
     }
   }
 
   httpChannel->SetRequestContextID(aRequestContextID);
 
   // Store the strong reference of channel and parent listener object until
   // all the initialization procedure is complete without failure, to remove
   // cycle reference in fail case and to avoid memory leakage.
-  mChannel = httpChannel.forget();
-  mParentListener = parentListener.forget();
+  mChannel = std::move(httpChannel);
+  mParentListener = std::move(parentListener);
   mChannel->SetNotificationCallbacks(mParentListener);
 
   mSuspendAfterSynthesizeResponse = aSuspendAfterSynthesizeResponse;
 
   MOZ_ASSERT(!mBgParent);
   MOZ_ASSERT(mPromise.IsEmpty());
   // Wait for HttpBackgrounChannel to continue the async open procedure.
   ++mAsyncOpenBarrier;
@@ -2327,17 +2327,17 @@ void HttpChannelParent::StartDiversion()
   // After OnStartRequest has been called, setup content decoders if needed.
   //
   // Create a content conversion chain based on mDivertListener and update
   // mDivertListener.
   nsCOMPtr<nsIStreamListener> converterListener;
   Unused << mChannel->DoApplyContentConversions(
       mDivertListener, getter_AddRefs(converterListener));
   if (converterListener) {
-    mDivertListener = converterListener.forget();
+    mDivertListener = std::move(converterListener);
   }
 
   // Now mParentListener can be diverted to mDivertListener.
   mParentListener->DivertTo(mDivertListener);
   mDivertListener = nullptr;
 
   // Either IPC channel is closed or background channel
   // is ready to send FlushedForDiversion and DivertMessages.
--- a/netwerk/protocol/http/InterceptedHttpChannel.cpp
+++ b/netwerk/protocol/http/InterceptedHttpChannel.cpp
@@ -199,17 +199,17 @@ nsresult InterceptedHttpChannel::FollowS
                              nullptr,  // aCallbacks
                              mLoadFlags, ioService);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = SetupReplacementChannel(redirectURI, newChannel, !rewriteToGET,
                                redirectFlags);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  mRedirectChannel = newChannel.forget();
+  mRedirectChannel = std::move(newChannel);
 
   rv = gHttpHandler->AsyncOnChannelRedirect(this, mRedirectChannel,
                                             redirectFlags);
 
   if (NS_WARN_IF(NS_FAILED(rv))) {
     OnRedirectVerifyCallback(rv);
   }
 
@@ -225,17 +225,17 @@ nsresult InterceptedHttpChannel::Redirec
   // extra redirect is performed so that listeners treat the result as unsafe
   // cross-origin data.
 
   nsresult rv = NS_OK;
 
   // We want to pass ownership of the body callback to the new synthesized
   // channel.  We need to hold a reference to the callbacks on the stack
   // as well, though, so we can call them if a failure occurs.
-  nsCOMPtr<nsIInterceptedBodyCallback> bodyCallback = mBodyCallback.forget();
+  nsCOMPtr<nsIInterceptedBodyCallback> bodyCallback = std::move(mBodyCallback);
 
   RefPtr<InterceptedHttpChannel> newChannel = CreateForSynthesis(
       mResponseHead.get(), mBodyReader, bodyCallback, mChannelCreationTime,
       mChannelCreationTimestamp, mAsyncOpenTime);
 
   // If the response has been redirected, propagate all the URLs to content.
   // Thus, the exact value of the redirect flag does not matter as long as it's
   // not REDIRECT_INTERNAL.
@@ -413,17 +413,17 @@ void InterceptedHttpChannel::MaybeCallSt
                           mStatusHost.get());
 
   mProgressSink->OnProgress(this, nullptr, progress, mSynthesizedStreamLength);
 
   mProgressReported = progress;
 }
 
 void InterceptedHttpChannel::MaybeCallBodyCallback() {
-  nsCOMPtr<nsIInterceptedBodyCallback> callback = mBodyCallback.forget();
+  nsCOMPtr<nsIInterceptedBodyCallback> callback = std::move(mBodyCallback);
   if (callback) {
     callback->BodyComplete(mStatus);
   }
 }
 
 // static
 already_AddRefed<InterceptedHttpChannel>
 InterceptedHttpChannel::CreateForInterception(
@@ -646,17 +646,17 @@ InterceptedHttpChannel::ResetInterceptio
     nsLoadFlags loadFlags = nsIRequest::LOAD_NORMAL;
     rv = newChannel->GetLoadFlags(&loadFlags);
     NS_ENSURE_SUCCESS(rv, rv);
     loadFlags |= nsIChannel::LOAD_BYPASS_SERVICE_WORKER;
     rv = newChannel->SetLoadFlags(loadFlags);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  mRedirectChannel = newChannel.forget();
+  mRedirectChannel = std::move(newChannel);
 
   rv = gHttpHandler->AsyncOnChannelRedirect(this, mRedirectChannel, flags);
 
   if (NS_FAILED(rv)) {
     OnRedirectVerifyCallback(rv);
   }
 
   return rv;
--- a/netwerk/protocol/http/nsCORSListenerProxy.cpp
+++ b/netwerk/protocol/http/nsCORSListenerProxy.cpp
@@ -628,17 +628,17 @@ nsresult nsCORSListenerProxy::CheckReque
 }
 
 NS_IMETHODIMP
 nsCORSListenerProxy::OnStopRequest(nsIRequest* aRequest, nsresult aStatusCode) {
   MOZ_ASSERT(mInited, "nsCORSListenerProxy has not been initialized properly");
   nsCOMPtr<nsIStreamListener> listener;
   {
     MutexAutoLock lock(mMutex);
-    listener = mOuterListener.forget();
+    listener = std::move(mOuterListener);
   }
   nsresult rv = listener->OnStopRequest(aRequest, aStatusCode);
   mOuterNotificationCallbacks = nullptr;
   mHttpChannel = nullptr;
   return rv;
 }
 
 NS_IMETHODIMP
--- a/netwerk/protocol/http/nsHttpTransaction.cpp
+++ b/netwerk/protocol/http/nsHttpTransaction.cpp
@@ -193,17 +193,17 @@ void nsHttpTransaction::SetClassOfServic
     if (mReadingStopped && !isThrottling) {
       ResumeReading();
     }
   }
 }
 
 class ReleaseH2WSTrans final : public Runnable {
  public:
-  explicit ReleaseH2WSTrans(already_AddRefed<SpdyConnectTransaction>&& trans)
+  explicit ReleaseH2WSTrans(RefPtr<SpdyConnectTransaction>&& trans)
       : Runnable("ReleaseH2WSTrans"), mTrans(std::move(trans)) {}
 
   NS_IMETHOD Run() override {
     mTrans = nullptr;
     return NS_OK;
   }
 
   void Dispatch() {
@@ -234,17 +234,17 @@ nsHttpTransaction::~nsHttpTransaction() 
   mConnection = nullptr;
 
   delete mResponseHead;
   delete mChunkedDecoder;
   ReleaseBlockingTransaction();
 
   if (mH2WSTransaction) {
     RefPtr<ReleaseH2WSTrans> r =
-        new ReleaseH2WSTrans(mH2WSTransaction.forget());
+        new ReleaseH2WSTrans(std::move(mH2WSTransaction));
     r->Dispatch();
   }
 }
 
 nsresult nsHttpTransaction::Init(
     uint32_t caps, nsHttpConnectionInfo* cinfo, nsHttpRequestHead* requestHead,
     nsIInputStream* requestBody, uint64_t requestContentLength,
     bool requestBodyHasHeaders, nsIEventTarget* target,
--- a/netwerk/protocol/res/ExtensionProtocolHandler.cpp
+++ b/netwerk/protocol/res/ExtensionProtocolHandler.cpp
@@ -277,17 +277,17 @@ void ExtensionStreamGetter::OnStream(alr
   MOZ_ASSERT(IsNeckoChild());
   MOZ_ASSERT(mListener);
   MOZ_ASSERT(mMainThreadEventTarget);
 
   nsCOMPtr<nsIInputStream> stream = std::move(aStream);
 
   // We must keep an owning reference to the listener
   // until we pass it on to AsyncRead.
-  nsCOMPtr<nsIStreamListener> listener = mListener.forget();
+  nsCOMPtr<nsIStreamListener> listener = std::move(mListener);
 
   MOZ_ASSERT(mChannel);
 
   if (!stream) {
     // The parent didn't send us back a stream.
     CancelRequest(listener, mChannel, NS_ERROR_FILE_ACCESS_DENIED);
     return;
   }
@@ -314,17 +314,17 @@ void ExtensionStreamGetter::OnFD(const F
 
   if (!aFD.IsValid()) {
     OnStream(nullptr);
     return;
   }
 
   // We must keep an owning reference to the listener
   // until we pass it on to AsyncOpen.
-  nsCOMPtr<nsIStreamListener> listener = mListener.forget();
+  nsCOMPtr<nsIStreamListener> listener = std::move(mListener);
 
   RefPtr<FileDescriptorFile> fdFile = new FileDescriptorFile(aFD, mJarFile);
   mJarChannel->SetJarFile(fdFile);
   nsresult rv = mJarChannel->AsyncOpen(listener);
   if (NS_FAILED(rv)) {
     CancelRequest(listener, mChannel, rv);
   }
 }
--- a/netwerk/url-classifier/UrlClassifierCommon.cpp
+++ b/netwerk/url-classifier/UrlClassifierCommon.cpp
@@ -479,17 +479,17 @@ bool UrlClassifierCommon::IsAllowListed(
                      nullptr, nullptr, getter_AddRefs(uri));
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return false;
     }
 
     nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
     RefPtr<BasePrincipal> bp = BasePrincipal::CreateContentPrincipal(
         uri, loadInfo->GetOriginAttributes());
-    cbAllowListPrincipal = bp.forget();
+    cbAllowListPrincipal = std::move(bp);
   }
 
   bool isAllowListed = false;
   rv = AntiTrackingCommon::IsOnContentBlockingAllowList(
       cbAllowListPrincipal, NS_UsePrivateBrowsing(aChannel), isAllowListed);
   if (NS_FAILED(rv)) {  // normal for some loads, no need to print a warning
     return false;
   }
--- a/parser/html/nsHtml5AtomTable.cpp
+++ b/parser/html/nsHtml5AtomTable.cpp
@@ -22,11 +22,11 @@ nsAtom* nsHtml5AtomTable::GetAtom(const 
   if (nsAtom* atom = mRecentlyUsedParserAtoms[index]) {
     if (atom->Equals(aKey)) {
       return atom;
     }
   }
 
   RefPtr<nsAtom> atom = NS_Atomize(aKey);
   nsAtom* ret = atom.get();
-  mRecentlyUsedParserAtoms[index] = atom.forget();
+  mRecentlyUsedParserAtoms[index] = std::move(atom);
   return ret;
 }
--- a/parser/html/nsHtml5StreamParser.cpp
+++ b/parser/html/nsHtml5StreamParser.cpp
@@ -890,17 +890,17 @@ nsresult nsHtml5StreamParser::WriteStrea
     mLastBuffer->AdvanceEnd(written);
     if (result == kOutputFull) {
       RefPtr<nsHtml5OwningUTF16Buffer> newBuf =
           nsHtml5OwningUTF16Buffer::FalliblyCreate(READ_BUFFER_SIZE);
       if (!newBuf) {
         MarkAsBroken(NS_ERROR_OUT_OF_MEMORY);
         return NS_ERROR_OUT_OF_MEMORY;
       }
-      mLastBuffer = (mLastBuffer->next = newBuf.forget());
+      mLastBuffer = (mLastBuffer->next = std::move(newBuf));
     } else {
       MOZ_ASSERT(totalRead == aFromSegment.Length(),
                  "The Unicode decoder consumed the wrong number of bytes.");
       if (mDecodingLocalFileWithoutTokenizing &&
           mLocalFileBytesBuffered == LOCAL_FILE_UTF_8_BUFFER_SIZE) {
         auto encoding = mEncoding;
         GuessEncoding(false, false);
         if (encoding == mEncoding) {
@@ -1274,17 +1274,17 @@ void nsHtml5StreamParser::DoStopRequest(
     mLastBuffer->AdvanceEnd(written);
     if (result == kOutputFull) {
       RefPtr<nsHtml5OwningUTF16Buffer> newBuf =
           nsHtml5OwningUTF16Buffer::FalliblyCreate(READ_BUFFER_SIZE);
       if (!newBuf) {
         MarkAsBroken(NS_ERROR_OUT_OF_MEMORY);
         return;
       }
-      mLastBuffer = (mLastBuffer->next = newBuf.forget());
+      mLastBuffer = (mLastBuffer->next = std::move(newBuf));
     } else {
       if (mDecodingLocalFileWithoutTokenizing) {
         MOZ_ASSERT(mLocalFileBytesBuffered < LOCAL_FILE_UTF_8_BUFFER_SIZE);
         MOZ_ASSERT(mGuessEncoding);
         auto encoding = mEncoding;
         GuessEncoding(true, false);
         if (encoding == mEncoding) {
           CommitLocalFileToEncoding();
--- a/security/manager/ssl/nsNSSCertHelper.cpp
+++ b/security/manager/ssl/nsNSSCertHelper.cpp
@@ -153,17 +153,17 @@ static nsresult ProcessSerialNumberDER(
   }
 
   rv = printableItem->SetDisplayValue(
       NS_ConvertASCIItoUTF16(serialNumber.get()));
   if (NS_FAILED(rv)) {
     return rv;
   }
 
-  retItem = printableItem.forget();
+  retItem = std::move(printableItem);
   return NS_OK;
 }
 
 static nsresult GetDefaultOIDFormat(SECItem* oid, nsAString& outString,
                                     char separator) {
   outString.Truncate();
   int invalidCount = 0;
 
--- a/services/crypto/component/IdentityCryptoService.cpp
+++ b/services/crypto/component/IdentityCryptoService.cpp
@@ -125,17 +125,17 @@ class IdentityCryptoService final : publ
     nsCOMPtr<nsISupports> dummyUsedToEnsureNSSIsInitialized =
         do_GetService("@mozilla.org/psm;1", &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsCOMPtr<nsIThread> thread;
     rv = NS_NewNamedThread("IdentityCrypto", getter_AddRefs(thread));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    mThread = thread.forget();
+    mThread = std::move(thread);
 
     return NS_OK;
   }
 
  private:
   ~IdentityCryptoService() = default;
   IdentityCryptoService(const KeyPair&) = delete;
   void operator=(const IdentityCryptoService&) = delete;
--- a/storage/mozStorageAsyncStatementExecution.cpp
+++ b/storage/mozStorageAsyncStatementExecution.cpp
@@ -347,17 +347,17 @@ nsresult AsyncExecuteStatements::notifyC
 
 nsresult AsyncExecuteStatements::notifyCompleteOnCallingThread() {
   MOZ_ASSERT(mCallingThread->IsOnCurrentThread());
   // Take ownership of mCallback and responsibility for freeing it when we
   // release it.  Any notifyResultsOnCallingThread and
   // notifyErrorOnCallingThread calls on the stack spinning the event loop have
   // guaranteed their safety by creating their own strong reference before
   // invoking the callback.
-  nsCOMPtr<mozIStorageStatementCallback> callback = mCallback.forget();
+  nsCOMPtr<mozIStorageStatementCallback> callback = std::move(mCallback);
   if (callback) {
     Unused << callback->HandleCompletion(mState);
   }
   return NS_OK;
 }
 
 nsresult AsyncExecuteStatements::notifyError(int32_t aErrorCode,
                                              const char* aMessage) {
--- a/storage/mozStorageService.cpp
+++ b/storage/mozStorageService.cpp
@@ -264,17 +264,17 @@ void Service::unregisterConnection(Conne
     MutexAutoLock mutex(mRegistrationMutex);
 
     for (uint32_t i = 0; i < mConnections.Length(); ++i) {
       if (mConnections[i] == aConnection) {
         // Because dropping the final reference can potentially result in
         // spinning a nested event loop if the connection was not properly
         // shutdown, we want to do that outside this loop so that we can finish
         // mutating the array and drop our mutex.
-        forgettingRef = mConnections[i].forget();
+        forgettingRef = std::move(mConnections[i]);
         mConnections.RemoveElementAt(i);
         break;
       }
     }
   }
 
   MOZ_ASSERT(forgettingRef,
              "Attempt to unregister unknown storage connection!");
@@ -574,17 +574,17 @@ Service::OpenAsyncDatabase(nsIVariant* a
     storageFile = do_QueryInterface(dbStore, &rv);
     if (NS_FAILED(rv)) {
       return NS_ERROR_INVALID_ARG;
     }
 
     nsCOMPtr<nsIFile> cloned;
     rv = storageFile->Clone(getter_AddRefs(cloned));
     MOZ_ASSERT(NS_SUCCEEDED(rv));
-    storageFile = cloned.forget();
+    storageFile = std::move(cloned);
 
     if (!readOnly) {
       // Ensure that SQLITE_OPEN_CREATE is passed in for compatibility reasons.
       flags |= SQLITE_OPEN_CREATE;
     }
 
     // Apply the shared-cache option.
     flags |= shared ? SQLITE_OPEN_SHAREDCACHE : SQLITE_OPEN_PRIVATECACHE;
--- a/storage/test/gtest/test_asyncStatementExecution_transaction.cpp
+++ b/storage/test/gtest/test_asyncStatementExecution_transaction.cpp
@@ -88,18 +88,18 @@ TEST(storage_asyncStatementExecution_tra
   db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"),
                            getter_AddRefs(stmt1));
 
   nsCOMPtr<mozIStorageAsyncStatement> stmt2;
   db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"),
                            getter_AddRefs(stmt2));
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt1.forget(),
-      stmt2.forget(),
+      ToRefPtr(std::move(stmt1)),
+      ToRefPtr(std::move(stmt2)),
   };
 
   check_transaction(db, nsTArray<RefPtr<mozIStorageBaseStatement>>(stmts),
                     false);
 }
 
 /**
  * Test that executing multiple readonly Statements doesn't create a
@@ -114,18 +114,18 @@ TEST(storage_asyncStatementExecution_tra
   db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"),
                       getter_AddRefs(stmt1));
 
   nsCOMPtr<mozIStorageStatement> stmt2;
   db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"),
                       getter_AddRefs(stmt2));
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt1.forget(),
-      stmt2.forget(),
+      ToRefPtr(std::move(stmt1)),
+      ToRefPtr(std::move(stmt2)),
   };
 
   check_transaction(db, stmts, false);
 }
 
 /**
  * Test that executing multiple AsyncStatements causing writes creates a
  * transaction.
@@ -141,18 +141,18 @@ TEST(storage_asyncStatementExecution_tra
                            getter_AddRefs(stmt1));
 
   nsCOMPtr<mozIStorageAsyncStatement> stmt2;
   db->CreateAsyncStatement(
       NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"),
       getter_AddRefs(stmt2));
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt1.forget(),
-      stmt2.forget(),
+      ToRefPtr(std::move(stmt1)),
+      ToRefPtr(std::move(stmt2)),
   };
 
   check_transaction(db, stmts, true);
 }
 
 /**
  * Test that executing multiple Statements causing writes creates a transaction.
  */
@@ -166,18 +166,18 @@ TEST(storage_asyncStatementExecution_tra
                       getter_AddRefs(stmt1));
 
   nsCOMPtr<mozIStorageStatement> stmt2;
   db->CreateStatement(
       NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"),
       getter_AddRefs(stmt2));
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt1.forget(),
-      stmt2.forget(),
+      ToRefPtr(std::move(stmt1)),
+      ToRefPtr(std::move(stmt2)),
   };
 
   check_transaction(db, stmts, true);
 }
 
 /**
  * Test that executing multiple AsyncStatements causing writes creates a
  * single transaction.
@@ -193,18 +193,18 @@ TEST(storage_asyncStatementExecution_tra
       getter_AddRefs(stmt1));
 
   nsCOMPtr<mozIStorageAsyncStatement> stmt2;
   db->CreateAsyncStatement(
       NS_LITERAL_CSTRING("CREATE TABLE test2 (id INTEGER PRIMARY KEY)"),
       getter_AddRefs(stmt2));
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt1.forget(),
-      stmt2.forget(),
+      ToRefPtr(std::move(stmt1)),
+      ToRefPtr(std::move(stmt2)),
   };
 
   check_transaction(db, stmts, true);
 }
 
 /**
  * Test that executing multiple Statements causing writes creates a
  * single transaction.
@@ -220,18 +220,18 @@ TEST(storage_asyncStatementExecution_tra
       getter_AddRefs(stmt1));
 
   nsCOMPtr<mozIStorageStatement> stmt2;
   db->CreateStatement(
       NS_LITERAL_CSTRING("CREATE TABLE test2 (id INTEGER PRIMARY KEY)"),
       getter_AddRefs(stmt2));
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt1.forget(),
-      stmt2.forget(),
+      ToRefPtr(std::move(stmt1)),
+      ToRefPtr(std::move(stmt2)),
   };
 
   check_transaction(db, stmts, true);
 }
 
 /**
  * Test that executing a single read-only AsyncStatement doesn't create a
  * transaction.
@@ -241,17 +241,17 @@ TEST(storage_asyncStatementExecution_tra
   nsCOMPtr<mozIStorageConnection> db(getMemoryDatabase());
 
   // -- create statements and execute them
   nsCOMPtr<mozIStorageAsyncStatement> stmt;
   db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"),
                            getter_AddRefs(stmt));
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt.forget(),
+      ToRefPtr(std::move(stmt)),
   };
 
   check_transaction(db, stmts, false);
 }
 
 /**
  * Test that executing a single read-only Statement doesn't create a
  * transaction.
@@ -261,17 +261,17 @@ TEST(storage_asyncStatementExecution_tra
   nsCOMPtr<mozIStorageConnection> db(getMemoryDatabase());
 
   // -- create statements and execute them
   nsCOMPtr<mozIStorageStatement> stmt;
   db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"),
                       getter_AddRefs(stmt));
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt.forget(),
+      ToRefPtr(std::move(stmt)),
   };
 
   check_transaction(db, stmts, false);
 }
 
 /**
  * Test that executing a single AsyncStatement causing writes creates a
  * transaction.
@@ -282,17 +282,17 @@ TEST(storage_asyncStatementExecution_tra
 
   // -- create statements and execute them
   nsCOMPtr<mozIStorageAsyncStatement> stmt;
   db->CreateAsyncStatement(
       NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"),
       getter_AddRefs(stmt));
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt.forget(),
+      ToRefPtr(std::move(stmt)),
   };
 
   check_transaction(db, stmts, true);
 }
 
 /**
  * Test that executing a single Statement causing writes creates a transaction.
  */
@@ -302,17 +302,17 @@ TEST(storage_asyncStatementExecution_tra
 
   // -- create statements and execute them
   nsCOMPtr<mozIStorageStatement> stmt;
   db->CreateStatement(
       NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"),
       getter_AddRefs(stmt));
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt.forget(),
+      ToRefPtr(std::move(stmt)),
   };
 
   check_transaction(db, stmts, true);
 }
 
 /**
  * Test that executing a single read-only AsyncStatement with multiple params
  * doesn't create a transaction.
@@ -336,17 +336,17 @@ TEST(storage_asyncStatementExecution_tra
     paramsArray->NewBindingParams(getter_AddRefs(params));
     params->BindInt32ByName(NS_LITERAL_CSTRING("param"), 1);
     paramsArray->AddParams(params);
   }
   stmt->BindParameters(paramsArray);
   paramsArray = nullptr;
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt.forget(),
+      ToRefPtr(std::move(stmt)),
   };
 
   check_transaction(db, stmts, false);
 }
 
 /**
  * Test that executing a single read-only Statement with multiple params
  * doesn't create a transaction.
@@ -368,17 +368,17 @@ TEST(storage_asyncStatementExecution_tra
     paramsArray->NewBindingParams(getter_AddRefs(params));
     params->BindInt32ByName(NS_LITERAL_CSTRING("param"), 1);
     paramsArray->AddParams(params);
   }
   stmt->BindParameters(paramsArray);
   paramsArray = nullptr;
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt.forget(),
+      ToRefPtr(std::move(stmt)),
   };
 
   check_transaction(db, stmts, false);
 }
 
 /**
  * Test that executing a single write AsyncStatement with multiple params
  * creates a transaction.
@@ -410,17 +410,17 @@ TEST(storage_asyncStatementExecution_tra
     paramsArray->NewBindingParams(getter_AddRefs(params));
     params->BindInt32ByName(NS_LITERAL_CSTRING("param"), 1);
     paramsArray->AddParams(params);
   }
   stmt->BindParameters(paramsArray);
   paramsArray = nullptr;
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt.forget(),
+      ToRefPtr(std::move(stmt)),
   };
 
   check_transaction(db, stmts, true);
 }
 
 /**
  * Test that executing a single write Statement with multiple params
  * creates a transaction.
@@ -450,13 +450,13 @@ TEST(storage_asyncStatementExecution_tra
     paramsArray->NewBindingParams(getter_AddRefs(params));
     params->BindInt32ByName(NS_LITERAL_CSTRING("param"), 1);
     paramsArray->AddParams(params);
   }
   stmt->BindParameters(paramsArray);
   paramsArray = nullptr;
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      stmt.forget(),
+      ToRefPtr(std::move(stmt)),
   };
 
   check_transaction(db, stmts, true);
 }
--- a/toolkit/components/alerts/AlertNotification.cpp
+++ b/toolkit/components/alerts/AlertNotification.cpp
@@ -304,31 +304,31 @@ nsresult AlertImageRequest::Start() {
 }
 
 nsresult AlertImageRequest::NotifyMissing() {
   if (mTimer) {
     mTimer->Cancel();
     mTimer = nullptr;
   }
   if (nsCOMPtr<nsIAlertNotificationImageListener> listener =
-          mListener.forget()) {
+          std::move(mListener)) {
     nsresult rv = listener->OnImageMissing(mUserData);
     NS_RELEASE_THIS();
     return rv;
   }
   return NS_OK;
 }
 
 nsresult AlertImageRequest::NotifyComplete() {
   if (mTimer) {
     mTimer->Cancel();
     mTimer = nullptr;
   }
   if (nsCOMPtr<nsIAlertNotificationImageListener> listener =
-          mListener.forget()) {
+          std::move(mListener)) {
     nsresult rv = listener->OnImageReady(mUserData, mRequest);
     NS_RELEASE_THIS();
     return rv;
   }
   return NS_OK;
 }
 
 }  // namespace mozilla
--- a/toolkit/components/alerts/AlertNotificationIPCSerializer.h
+++ b/toolkit/components/alerts/AlertNotificationIPCSerializer.h
@@ -104,17 +104,17 @@ struct IPDLParamTraits<nsIAlertNotificat
     }
     nsresult rv = alert->Init(name, imageURL, title, text, textClickable,
                               cookie, dir, lang, data, principal,
                               inPrivateBrowsing, requireInteraction);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       *aResult = nullptr;
       return true;
     }
-    *aResult = alert.forget();
+    *aResult = ToRefPtr(std::move(alert));
     return true;
   }
 };
 
 }  // namespace ipc
 }  // namespace mozilla
 
 #endif /* mozilla_AlertNotificationIPCSerializer_h__ */
--- a/toolkit/components/places/Database.cpp
+++ b/toolkit/components/places/Database.cpp
@@ -2593,17 +2593,17 @@ int64_t Database::CreateMobileRoot() {
 void Database::Shutdown() {
   // As the last step in the shutdown path, finalize the database handle.
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(!mClosed);
 
   // Break cycles with the shutdown blockers.
   mClientsShutdown = nullptr;
   nsCOMPtr<mozIStorageCompletionCallback> connectionShutdown =
-      mConnectionShutdown.forget();
+      std::move(mConnectionShutdown);
 
   if (!mMainConn) {
     // The connection has never been initialized. Just mark it as closed.
     mClosed = true;
     (void)connectionShutdown->Complete(NS_OK, nullptr);
     return;
   }
 
--- a/toolkit/components/places/nsAnnoProtocolHandler.cpp
+++ b/toolkit/components/places/nsAnnoProtocolHandler.cpp
@@ -270,17 +270,17 @@ nsresult nsAnnoProtocolHandler::NewFavic
         auto fallback = [&]() -> RequestOrReason {
           nsCOMPtr<nsIChannel> chan;
           nsresult rv = GetDefaultIcon(channel, getter_AddRefs(chan));
           NS_ENSURE_SUCCESS(rv, Err(rv));
 
           rv = chan->AsyncOpen(listener);
           NS_ENSURE_SUCCESS(rv, Err(rv));
 
-          return RequestOrReason(chan.forget());
+          return RequestOrReason(std::move(chan));
         };
 
         // Now we go ahead and get our data asynchronously for the favicon.
         // Ignore the ref part of the URI before querying the database because
         // we may have added a size fragment for rendering purposes.
         nsFaviconService* faviconService =
             nsFaviconService::GetFaviconService();
         nsAutoCString faviconSpec;
--- a/toolkit/components/places/nsFaviconService.cpp
+++ b/toolkit/components/places/nsFaviconService.cpp
@@ -174,20 +174,20 @@ nsFaviconService::ExpireAllFavicons() {
   NS_ENSURE_STATE(removePagesStmt);
   nsCOMPtr<mozIStorageAsyncStatement> removeIconsStmt =
       mDB->GetAsyncStatement("DELETE FROM moz_icons");
   NS_ENSURE_STATE(removeIconsStmt);
   nsCOMPtr<mozIStorageAsyncStatement> unlinkIconsStmt =
       mDB->GetAsyncStatement("DELETE FROM moz_icons_to_pages");
   NS_ENSURE_STATE(unlinkIconsStmt);
 
-  nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {removePagesStmt.forget(),
-
-                                                      removeIconsStmt.forget(),
-                                                      unlinkIconsStmt.forget()};
+  nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
+      ToRefPtr(std::move(removePagesStmt)),
+      ToRefPtr(std::move(removeIconsStmt)),
+      ToRefPtr(std::move(unlinkIconsStmt))};
   nsCOMPtr<mozIStorageConnection> conn = mDB->MainConn();
   if (!conn) {
     return NS_ERROR_UNEXPECTED;
   }
   nsCOMPtr<mozIStoragePendingStatement> ps;
   RefPtr<ExpireFaviconsStatementCallbackNotifier> callback =
       new ExpireFaviconsStatementCallbackNotifier();
   return conn->ExecuteAsync(stmts, callback, getter_AddRefs(ps));
--- a/toolkit/components/places/nsNavHistory.cpp
+++ b/toolkit/components/places/nsNavHistory.cpp
@@ -3358,18 +3358,18 @@ nsresult nsNavHistory::UpdateFrecency(in
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<mozIStorageConnection> conn = mDB->MainConn();
   if (!conn) {
     return NS_ERROR_UNEXPECTED;
   }
 
   nsTArray<RefPtr<mozIStorageBaseStatement>> stmts = {
-      updateFrecencyStmt.forget(),
-      updateHiddenStmt.forget(),
+      ToRefPtr(std::move(updateFrecencyStmt)),
+      ToRefPtr(std::move(updateHiddenStmt)),
   };
   nsCOMPtr<mozIStoragePendingStatement> ps;
   rv = conn->ExecuteAsync(stmts, nullptr, getter_AddRefs(ps));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Trigger frecency updates for all affected origins.
   nsCOMPtr<mozIStorageAsyncStatement> updateOriginFrecenciesStmt =
       mDB->GetAsyncStatement("DELETE FROM moz_updateoriginsupdate_temp");
--- a/toolkit/components/telemetry/core/TelemetryScalar.cpp
+++ b/toolkit/components/telemetry/core/TelemetryScalar.cpp
@@ -587,17 +587,17 @@ nsresult ScalarUnsigned::GetValue(const 
   if (!HasValueInStore(storeIndex)) {
     return NS_ERROR_NO_CONTENT;
   }
   nsCOMPtr<nsIWritableVariant> outVar(new nsVariant());
   rv = outVar->SetAsUint32(mStorage[storeIndex]);
   if (NS_FAILED(rv)) {
     return rv;
   }
-  aResult = outVar.forget();
+  aResult = std::move(outVar);
   if (aClearStore) {
     mStorage[storeIndex] = 0;
     ClearValueInStore(storeIndex);
   }
   return NS_OK;
 }
 
 size_t ScalarUnsigned::SizeOfIncludingThis(
@@ -707,17 +707,17 @@ nsresult ScalarString::GetValue(const ns
   }
   rv = outVar->SetAsAString(mStorage[storeIndex]);
   if (NS_FAILED(rv)) {
     return rv;
   }
   if (aClearStore) {
     ClearValueInStore(storeIndex);
   }
-  aResult = outVar.forget();
+  aResult = std::move(outVar);
   return NS_OK;
 }
 
 size_t ScalarString::SizeOfIncludingThis(
     mozilla::MallocSizeOf aMallocSizeOf) const {
   size_t n = aMallocSizeOf(this);
   n += ScalarBase::SizeOfExcludingThis(aMallocSizeOf);
   n += mStorage.ShallowSizeOfExcludingThis(aMallocSizeOf);
@@ -801,17 +801,17 @@ nsresult ScalarBoolean::GetValue(const n
   }
   if (aClearStore) {
     ClearValueInStore(storeIndex);
   }
   rv = outVar->SetAsBool(mStorage[storeIndex]);
   if (NS_FAILED(rv)) {
     return rv;
   }
-  aResult = outVar.forget();
+  aResult = std::move(outVar);
   return NS_OK;
 }
 
 size_t ScalarBoolean::SizeOfIncludingThis(
     mozilla::MallocSizeOf aMallocSizeOf) const {
   size_t n = aMallocSizeOf(this);
   n += ScalarBase::SizeOfExcludingThis(aMallocSizeOf);
   n += mStorage.ShallowSizeOfExcludingThis(aMallocSizeOf);
--- a/toolkit/components/telemetry/geckoview/TelemetryGeckoViewPersistence.cpp
+++ b/toolkit/components/telemetry/geckoview/TelemetryGeckoViewPersistence.cpp
@@ -520,17 +520,17 @@ void TelemetryGeckoViewPersistence::Init
   // We just spawn it once and re-use it later.
   nsCOMPtr<nsIThread> thread;
   nsresult rv = NS_NewNamedThread("TelemetryGVIO", getter_AddRefs(thread));
   if (NS_WARN_IF(NS_FAILED(rv))) {
     ANDROID_LOG("InitPersistence -  Failed to instantiate the worker thread.");
     return;
   }
 
-  gPersistenceThread = thread.forget();
+  gPersistenceThread = ToRefPtr(std::move(thread));
 
   // From now on all scalar operations should be recorded.
   TelemetryScalar::DeserializationStarted();
 
   // Trigger the loading of the persistence data. After the function
   // completes it will automatically arm the persistence timer.
   gPersistenceThread->Dispatch(NS_NewRunnableFunction(
       "PersistenceThreadLoadData", &PersistenceThreadLoadData));
--- a/uriloader/exthandler/nsExternalHelperAppService.cpp
+++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
@@ -2157,17 +2157,17 @@ nsresult nsExternalAppHandler::CreateFai
   rv = NS_NewFileURI(getter_AddRefs(pseudoTarget), pseudoFile);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = transfer->Init(mSourceUrl, pseudoTarget, EmptyString(), mMimeInfo,
                       mTimeDownloadStarted, nullptr, this, aIsPrivateBrowsing);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Our failed transfer is ready.
-  mTransfer = transfer.forget();
+  mTransfer = std::move(transfer);
 
   return NS_OK;
 }
 
 nsresult nsExternalAppHandler::SaveDestinationAvailable(nsIFile* aFile) {
   if (aFile)
     ContinueSave(aFile);
   else
--- a/uriloader/prefetch/OfflineCacheUpdateChild.cpp
+++ b/uriloader/prefetch/OfflineCacheUpdateChild.cpp
@@ -344,17 +344,17 @@ OfflineCacheUpdateChild::GetByteProgress
 
 NS_IMETHODIMP
 OfflineCacheUpdateChild::Schedule() {
   LOG(("OfflineCacheUpdateChild::Schedule [%p]", this));
 
   NS_ASSERTION(mWindow,
                "Window must be provided to the offline cache update child");
 
-  nsCOMPtr<nsPIDOMWindowInner> window = mWindow.forget();
+  nsCOMPtr<nsPIDOMWindowInner> window = std::move(mWindow);
   nsCOMPtr<nsIDocShell> docshell = window->GetDocShell();
   if (!docshell) {
     NS_WARNING("doc shell tree item is null");
     return NS_ERROR_FAILURE;
   }
 
   nsCOMPtr<nsIBrowserChild> tabchild = docshell->GetBrowserChild();
   // because owner implements nsIBrowserChild, we can assume that it is
--- a/uriloader/prefetch/nsPrefetchService.cpp
+++ b/uriloader/prefetch/nsPrefetchService.cpp
@@ -392,17 +392,17 @@ void nsPrefetchService::ProcessNextPrefe
   }
 
   nsresult rv;
 
   do {
     if (mPrefetchQueue.empty()) {
       break;
     }
-    RefPtr<nsPrefetchNode> node = mPrefetchQueue.front().forget();
+    RefPtr<nsPrefetchNode> node = std::move(mPrefetchQueue.front());
     mPrefetchQueue.pop_front();
 
     if (LOG_ENABLED()) {
       LOG(("ProcessNextPrefetchURI [%s]\n",
            node->mURI->GetSpecOrDefault().get()));
     }
 
     //
--- a/widget/PuppetWidget.cpp
+++ b/widget/PuppetWidget.cpp
@@ -580,17 +580,17 @@ bool PuppetWidget::CreateRemoteLayerMana
     return false;
   }
 
   // Force the old LM to self destruct, otherwise if the reference dangles we
   // could fail to revoke the most recent transaction. We only want to replace
   // it if we successfully create its successor because a partially initialized
   // layer manager is worse than a fully initialized but shutdown layer manager.
   DestroyLayerManager();
-  mLayerManager = lm.forget();
+  mLayerManager = std::move(lm);
   return true;
 }
 
 nsresult PuppetWidget::RequestIMEToCommitComposition(bool aCancel) {
   if (!mBrowserChild) {
     return NS_ERROR_FAILURE;
   }
 
--- a/widget/gtk/nsDragService.cpp
+++ b/widget/gtk/nsDragService.cpp
@@ -1838,17 +1838,17 @@ gboolean nsDragService::RunScheduledTask
   // Now we collect the pending state because, from this point on, we want
   // to use the same state for all events dispatched.  All state is updated
   // so that when other tasks are scheduled during dispatch here, this
   // task is considered to have already been run.
   bool positionHasChanged = mPendingWindow != mTargetWindow ||
                             mPendingWindowPoint != mTargetWindowPoint;
   DragTask task = mScheduledTask;
   mScheduledTask = eDragTaskNone;
-  mTargetWindow = mPendingWindow.forget();
+  mTargetWindow = std::move(mPendingWindow);
   mTargetWindowPoint = mPendingWindowPoint;
 
   if (task == eDragTaskLeave || task == eDragTaskSourceEnd) {
     if (task == eDragTaskSourceEnd) {
       // Dispatch drag end events.
       EndDragSession(true, GetCurrentModifiers());
     }
 
@@ -1863,17 +1863,17 @@ gboolean nsDragService::RunScheduledTask
 
   // mTargetWidget may be nullptr if the window has been destroyed.
   // (The leave event is not scheduled if a drop task is still scheduled.)
   // We still reply appropriately to indicate that the drop will or didn't
   // succeeed.
   mTargetWidget = mTargetWindow->GetMozContainerWidget();
   mTargetDragContext.steal(mPendingDragContext);
 #ifdef MOZ_WAYLAND
-  mTargetWaylandDragContext = mPendingWaylandDragContext.forget();
+  mTargetWaylandDragContext = std::move(mPendingWaylandDragContext);
 #endif
   mTargetTime = mPendingTime;
 
   // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#drag-and-drop-processing-model
   // (as at 27 December 2010) indicates that a "drop" event should only be
   // fired (at the current target element) if the current drag operation is
   // not none.  The current drag operation will only be set to a non-none
   // value during a "dragover" event.
--- a/widget/gtk/nsWidgetFactory.cpp
+++ b/widget/gtk/nsWidgetFactory.cpp
@@ -41,17 +41,17 @@ NS_IMPL_COMPONENT_FACTORY(nsIClipboard) 
   nsCOMPtr<nsIClipboard> inst;
   if (gfxPlatform::IsHeadless()) {
     inst = new HeadlessClipboard();
   } else {
     auto clipboard = MakeRefPtr<nsClipboard>();
     if (NS_FAILED(clipboard->Init())) {
       return nullptr;
     }
-    inst = clipboard.forget();
+    inst = std::move(clipboard);
   }
 
   return inst.forget().downcast<nsISupports>();
 }
 #endif
 
 nsresult nsWidgetGtk2ModuleCtor() { return nsAppShellInit(); }
 
--- a/widget/gtk/nsWindow.cpp
+++ b/widget/gtk/nsWindow.cpp
@@ -3699,17 +3699,17 @@ gboolean nsWindow::OnTouchEvent(GdkEvent
   if (aEvent->type == GDK_TOUCH_BEGIN || aEvent->type == GDK_TOUCH_UPDATE) {
     mTouches.Put(aEvent->sequence, touch.forget());
     // add all touch points to event object
     for (auto iter = mTouches.Iter(); !iter.Done(); iter.Next()) {
       event.mTouches.AppendElement(new dom::Touch(*iter.UserData()));
     }
   } else if (aEvent->type == GDK_TOUCH_END ||
              aEvent->type == GDK_TOUCH_CANCEL) {
-    *event.mTouches.AppendElement() = touch.forget();
+    *event.mTouches.AppendElement() = std::move(touch);
   }
 
   DispatchInputEvent(&event);
   return TRUE;
 }
 #endif
 
 static GdkWindow* CreateGdkWindow(GdkWindow* parent, GtkWidget* widget) {
--- a/widget/nsBaseWidget.cpp
+++ b/widget/nsBaseWidget.cpp
@@ -304,17 +304,17 @@ void nsBaseWidget::DestroyCompositor() {
   if (mCompositorSession) {
     ReleaseContentController();
     mAPZC = nullptr;
     SetCompositorWidgetDelegate(nullptr);
     mCompositorBridgeChild = nullptr;
 
     // XXX CompositorBridgeChild and CompositorBridgeParent might be re-created
     // in ClientLayerManager destructor. See bug 1133426.
-    RefPtr<CompositorSession> session = mCompositorSession.forget();
+    RefPtr<CompositorSession> session = std::move(mCompositorSession);
     session->Shutdown();
   }
 }
 
 // This prevents the layer manager from starting a new transaction during
 // shutdown.
 void nsBaseWidget::RevokeTransactionIdAllocator() {
   if (!mLayerManager) {
@@ -1131,17 +1131,17 @@ nsEventStatus nsBaseWidget::DispatchInpu
         return result.mStatus;
       }
       return ProcessUntransformedAPZEvent(aEvent, result);
     }
     WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent();
     if (wheelEvent) {
       RefPtr<Runnable> r =
           new DispatchWheelInputOnControllerThread(*wheelEvent, mAPZC, this);
-      APZThreadUtils::RunOnControllerThread(r.forget());
+      APZThreadUtils::RunOnControllerThread(std::move(r));
       return nsEventStatus_eConsumeDoDefault;
     }
     // Allow dispatching keyboard events on Gecko thread.
     MOZ_ASSERT(aEvent->AsKeyboardEvent());
   }
 
   nsEventStatus status;
   DispatchEvent(aEvent, status);
@@ -1338,17 +1338,17 @@ void nsBaseWidget::CreateCompositor(int 
     if (WidgetTypeSupportsAcceleration()) {
       ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
       gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
     }
   }
 
   WindowUsesOMTC();
 
-  mLayerManager = lm.forget();
+  mLayerManager = std::move(lm);
 
   // Only track compositors for top-level windows, since other window types
   // may use the basic compositor.  Except on the OS X - see bug 1306383
 #if defined(XP_MACOSX)
   bool getCompositorFromThisWindow = true;
 #else
   bool getCompositorFromThisWindow = (mWindowType == eWindowType_toplevel);
 #endif
--- a/xpcom/base/CycleCollectedJSContext.cpp
+++ b/xpcom/base/CycleCollectedJSContext.cpp
@@ -396,17 +396,17 @@ CycleCollectedJSContext::GetDebuggerMicr
 void CycleCollectedJSContext::ProcessStableStateQueue() {
   MOZ_ASSERT(mJSContext);
   MOZ_RELEASE_ASSERT(!mDoingStableStates);
   mDoingStableStates = true;
 
   // When run, one event can add another event to the mStableStateEvents, as
   // such you can't use iterators here.
   for (uint32_t i = 0; i < mStableStateEvents.Length(); ++i) {
-    nsCOMPtr<nsIRunnable> event = mStableStateEvents[i].forget();
+    nsCOMPtr<nsIRunnable> event = std::move(mStableStateEvents[i]);
     event->Run();
   }
 
   mStableStateEvents.Clear();
   mDoingStableStates = false;
 }
 
 void CycleCollectedJSContext::CleanupIDBTransactions(uint32_t aRecursionDepth) {
@@ -419,17 +419,17 @@ void CycleCollectedJSContext::CleanupIDB
 
   for (uint32_t i = 0; i < localQueue.Length(); ++i) {
     PendingIDBTransactionData& data = localQueue[i];
     if (data.mRecursionDepth != aRecursionDepth) {
       continue;
     }
 
     {
-      nsCOMPtr<nsIRunnable> transaction = data.mTransaction.forget();
+      nsCOMPtr<nsIRunnable> transaction = std::move(data.mTransaction);
       transaction->Run();
     }
 
     localQueue.RemoveElementAt(i--);
   }
 
   // If the queue has events in it now, they were added from something we
   // called, so they belong at the end of the queue.
@@ -556,17 +556,17 @@ void CycleCollectedJSContext::AddPending
 void CycleCollectedJSContext::DispatchToMicroTask(
     already_AddRefed<MicroTaskRunnable> aRunnable) {
   RefPtr<MicroTaskRunnable> runnable(aRunnable);
 
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(runnable);
 
   JS::JobQueueMayNotBeEmpty(Context());
-  mPendingMicroTaskRunnables.push(runnable.forget());
+  mPendingMicroTaskRunnables.push(std::move(runnable));
 }
 
 class AsyncMutationHandler final : public mozilla::Runnable {
  public:
   AsyncMutationHandler() : mozilla::Runnable("AsyncMutationHandler") {}
 
   // MOZ_CAN_RUN_SCRIPT_BOUNDARY until Runnable::Run is MOZ_CAN_RUN_SCRIPT.  See
   // bug 1535398.
@@ -612,20 +612,20 @@ bool CycleCollectedJSContext::PerformMic
 
   bool didProcess = false;
   AutoSlowOperation aso;
 
   std::queue<RefPtr<MicroTaskRunnable>> suppressed;
   for (;;) {
     RefPtr<MicroTaskRunnable> runnable;
     if (!mDebuggerMicroTaskQueue.empty()) {
-      runnable = mDebuggerMicroTaskQueue.front().forget();
+      runnable = std::move(mDebuggerMicroTaskQueue.front());
       mDebuggerMicroTaskQueue.pop();
     } else if (!mPendingMicroTaskRunnables.empty()) {
-      runnable = mPendingMicroTaskRunnables.front().forget();
+      runnable = std::move(mPendingMicroTaskRunnables.front());
       mPendingMicroTaskRunnables.pop();
     } else {
       break;
     }
 
     if (runnable->Suppressed()) {
       // Microtasks in worker shall never be suppressed.
       // Otherwise, mPendingMicroTaskRunnables will be replaced later with
@@ -664,17 +664,17 @@ void CycleCollectedJSContext::PerformDeb
     // queue.
     std::queue<RefPtr<MicroTaskRunnable>>* microtaskQueue =
         &GetDebuggerMicroTaskQueue();
 
     if (microtaskQueue->empty()) {
       break;
     }
 
-    RefPtr<MicroTaskRunnable> runnable = microtaskQueue->front().forget();
+    RefPtr<MicroTaskRunnable> runnable = std::move(microtaskQueue->front());
     MOZ_ASSERT(runnable);
 
     // This function can re-enter, so we remove the element before calling.
     microtaskQueue->pop();
 
     if (mPendingMicroTaskRunnables.empty() && mDebuggerMicroTaskQueue.empty()) {
       JS::JobQueueIsEmpty(Context());
     }
--- a/xpcom/base/nsCOMPtr.h
+++ b/xpcom/base/nsCOMPtr.h
@@ -217,24 +217,24 @@ inline nsQueryInterfaceISupports do_Quer
 template <class T>
 inline nsQueryInterfaceISupportsWithError do_QueryInterface(T aPtr,
                                                             nsresult* aError) {
   return nsQueryInterfaceISupportsWithError(
       ToSupports(static_cast<mozilla::PointedToType<T>*>(aPtr)), aError);
 }
 #else
 template <class T>
-inline nsQueryInterface<mozilla::PointedToType<T> > do_QueryInterface(T aPtr) {
-  return nsQueryInterface<mozilla::PointedToType<T> >(aPtr);
+inline nsQueryInterface<mozilla::PointedToType<T>> do_QueryInterface(T aPtr) {
+  return nsQueryInterface<mozilla::PointedToType<T>>(aPtr);
 }
 
 template <class T>
-inline nsQueryInterfaceWithError<mozilla::PointedToType<T> > do_QueryInterface(
+inline nsQueryInterfaceWithError<mozilla::PointedToType<T>> do_QueryInterface(
     T aRawPtr, nsresult* aError) {
-  return nsQueryInterfaceWithError<mozilla::PointedToType<T> >(aRawPtr, aError);
+  return nsQueryInterfaceWithError<mozilla::PointedToType<T>>(aRawPtr, aError);
 }
 
 #endif  // ! #ifdef NSCAP_FEATURE_USE_BASE
 
 template <class T>
 inline void do_QueryInterface(already_AddRefed<T>&) {
   // This signature exists solely to _stop_ you from doing the bad thing.
   // Saying |do_QueryInterface()| on a pointer that is not otherwise owned by
@@ -530,17 +530,18 @@ class MOZ_IS_REFPTR nsCOMPtr final
     assert_validity();
     NSCAP_LOG_ASSIGNMENT(this, mRawPtr);
     NSCAP_ASSERT_NO_QUERY_NEEDED();
   }
 
   // Construct from |std::move(otherRefPtr)|.
   template <typename U>
   MOZ_IMPLICIT nsCOMPtr(RefPtr<U>&& aSmartPtr)
-      : NSCAP_CTOR_BASE(aSmartPtr.forget().take()) {
+      : NSCAP_CTOR_BASE(
+            static_cast<already_AddRefed<T>>(aSmartPtr.forget()).take()) {
     assert_validity();
     // Make sure that U actually inherits from T
     static_assert(std::is_base_of<T, U>::value, "U is not a subclass of T");
     NSCAP_LOG_ASSIGNMENT(this, mRawPtr);
     NSCAP_ASSERT_NO_QUERY_NEEDED();
   }
 
   // Construct from |already_AddRefed|.
--- a/xpcom/ds/nsAtomTable.cpp
+++ b/xpcom/ds/nsAtomTable.cpp
@@ -621,17 +621,17 @@ already_AddRefed<nsAtom> nsAtomTable::At
   AtomTableEntry* he = table.Add(key);
 
   if (he->mAtom) {
     retVal = he->mAtom;
   } else {
     RefPtr<nsAtom> newAtom =
         dont_AddRef(nsDynamicAtom::Create(aUTF16String, key.mHash));
     he->mAtom = newAtom;
-    retVal = newAtom.forget();
+    retVal = std::move(newAtom);
   }
 
   p.Set(retVal);
   return retVal.forget();
 }
 
 already_AddRefed<nsAtom> NS_AtomizeMainThread(const nsAString& aUTF16String) {
   MOZ_ASSERT(gAtomTable);
--- a/xpcom/io/nsMultiplexInputStream.cpp
+++ b/xpcom/io/nsMultiplexInputStream.cpp
@@ -244,17 +244,17 @@ nsMultiplexInputStream::AppendStream(nsI
   nsCOMPtr<nsIInputStream> stream = aStream;
 
   bool buffered = false;
   if (!NS_InputStreamIsBuffered(stream)) {
     nsCOMPtr<nsIInputStream> bufferedStream;
     nsresult rv = NS_NewBufferedInputStream(getter_AddRefs(bufferedStream),
                                             stream.forget(), 4096);
     NS_ENSURE_SUCCESS(rv, rv);
-    stream = bufferedStream.forget();
+    stream = std::move(bufferedStream);
     buffered = true;
   }
 
   MutexAutoLock lock(mLock);
 
   StreamData* streamData = mStreams.AppendElement(fallible);
   if (NS_WARN_IF(!streamData)) {
     return NS_ERROR_OUT_OF_MEMORY;
--- a/xpcom/io/nsPipe3.cpp
+++ b/xpcom/io/nsPipe3.cpp
@@ -969,18 +969,18 @@ void nsPipe::OnPipeException(nsresult aR
   }
 }
 
 nsresult nsPipe::CloneInputStream(nsPipeInputStream* aOriginal,
                                   nsIInputStream** aCloneOut) {
   ReentrantMonitorAutoEnter mon(mReentrantMonitor);
   RefPtr<nsPipeInputStream> ref = new nsPipeInputStream(*aOriginal);
   mInputList.AppendElement(ref);
-  nsCOMPtr<nsIAsyncInputStream> downcast = ref.forget();
-  downcast.forget(aCloneOut);
+  nsCOMPtr<nsIAsyncInputStream> upcast = std::move(ref);
+  upcast.forget(aCloneOut);
   return NS_OK;
 }
 
 uint32_t nsPipe::CountSegmentReferences(int32_t aSegment) {
   mReentrantMonitor.AssertCurrentThreadIn();
   uint32_t count = 0;
   for (uint32_t i = 0; i < mInputList.Length(); ++i) {
     if (aSegment >= mInputList[i]->ReadState().mSegment) {
--- a/xpcom/tests/gtest/TestCOMPtr.cpp
+++ b/xpcom/tests/gtest/TestCOMPtr.cpp
@@ -365,17 +365,17 @@ TEST(COMPtr, AssignmentHelpers)
 
   {
     nsCOMPtr<IFoo> fooP(do_QueryInterface(static_cast<nsISupports*>(new IFoo)));
     ASSERT_TRUE(fooP);
 
     ASSERT_EQ(IFoo::total_constructions_, 5);
     ASSERT_EQ(IFoo::total_destructions_, 4);
 
-    nsCOMPtr<IFoo> fooP2(fooP.forget());
+    nsCOMPtr<IFoo> fooP2(std::move(fooP));
     ASSERT_TRUE(fooP2);
 
     ASSERT_EQ(IFoo::total_constructions_, 5);
     ASSERT_EQ(IFoo::total_destructions_, 4);
   }
 
   ASSERT_EQ(IFoo::total_constructions_, 5);
   ASSERT_EQ(IFoo::total_destructions_, 5);
--- a/xpcom/tests/gtest/TestCloneInputStream.cpp
+++ b/xpcom/tests/gtest/TestCloneInputStream.cpp
@@ -121,17 +121,17 @@ TEST(CloneInputStream, NonCloneableInput
   rv = NS_CloneInputStream(stream, getter_AddRefs(clone),
                            getter_AddRefs(replacement));
   ASSERT_TRUE(NS_SUCCEEDED(rv));
   ASSERT_TRUE(clone != nullptr);
   ASSERT_TRUE(replacement != nullptr);
   ASSERT_TRUE(stream.get() != replacement.get());
   ASSERT_TRUE(clone.get() != replacement.get());
 
-  stream = replacement.forget();
+  stream = std::move(replacement);
 
   // The stream is being copied asynchronously on the STS event target.  Spin
   // a yield loop here until the data is available.  Yes, this is a bit hacky,
   // but AFAICT, gtest does not support async test completion.
   uint64_t available;
   do {
     mozilla::Unused << PR_Sleep(PR_INTERVAL_NO_WAIT);
     rv = stream->Available(&available);
--- a/xpcom/tests/gtest/TestNsRefPtr.cpp
+++ b/xpcom/tests/gtest/TestNsRefPtr.cpp
@@ -230,17 +230,18 @@ TEST(nsRefPtr, AddRefAndRelease)
 
   {
     RefPtr<Foo> fooP(do_QueryObject(new Foo));
     ASSERT_EQ(Foo::total_constructions_, 3);
     ASSERT_EQ(Foo::total_destructions_, 2);
     ASSERT_EQ(fooP->refcount_, 1);
 
     Foo::total_addrefs_ = 0;
-    RefPtr<Foo> fooP2(fooP.forget());
+    RefPtr<Foo> fooP2 = std::move(fooP);
+    mozilla::Unused << fooP2;
     ASSERT_EQ(Foo::total_addrefs_, 0);
   }
 }
 
 TEST(nsRefPtr, VirtualDestructor)
 {
   Bar::total_destructions_ = 0;
 
--- a/xpcom/threads/MozPromise.h
+++ b/xpcom/threads/MozPromise.h
@@ -254,37 +254,37 @@ class MozPromise : public MozPromiseBase
   static MOZ_MUST_USE RefPtr<MozPromise> CreateAndResolve(
       ResolveValueType_&& aResolveValue, const char* aResolveSite) {
     static_assert(IsConvertible<ResolveValueType_, ResolveValueT>::value,
                   "Resolve() argument must be implicitly convertible to "
                   "MozPromise's ResolveValueT");
     RefPtr<typename MozPromise::Private> p =
         new MozPromise::Private(aResolveSite);
     p->Resolve(std::forward<ResolveValueType_>(aResolveValue), aResolveSite);
-    return p.forget();
+    return p;
   }
 
   template <typename RejectValueType_>
   static MOZ_MUST_USE RefPtr<MozPromise> CreateAndReject(
       RejectValueType_&& aRejectValue, const char* aRejectSite) {
     static_assert(IsConvertible<RejectValueType_, RejectValueT>::value,
                   "Reject() argument must be implicitly convertible to "
                   "MozPromise's RejectValueT");
     RefPtr<typename MozPromise::Private> p =
         new MozPromise::Private(aRejectSite);
     p->Reject(std::forward<RejectValueType_>(aRejectValue), aRejectSite);
-    return p.forget();
+    return p;
   }
 
   template <typename ResolveOrRejectValueType_>
   static MOZ_MUST_USE RefPtr<MozPromise> CreateAndResolveOrReject(
       ResolveOrRejectValueType_&& aValue, const char* aSite) {
     RefPtr<typename MozPromise::Private> p = new MozPromise::Private(aSite);
     p->ResolveOrReject(std::forward<ResolveOrRejectValueType_>(aValue), aSite);
-    return p.forget();
+    return p;
   }
 
   typedef MozPromise<nsTArray<ResolveValueType>, RejectValueType, IsExclusive>
       AllPromiseType;
 
  private:
   class AllPromiseHolder : public MozPromiseRefcountable {
    public:
@@ -1129,17 +1129,17 @@ typedef MozPromise<bool, nsresult, /* Is
  * variable for a class whose method returns a promise.
  */
 template <typename PromiseType>
 class MozPromiseHolder {
  public:
   MozPromiseHolder() : mMonitor(nullptr) {}
 
   MozPromiseHolder(MozPromiseHolder&& aOther)
-      : mMonitor(nullptr), mPromise(aOther.mPromise.forget()) {}
+      : mMonitor(nullptr), mPromise(std::move(aOther.mPromise)) {}
 
   // Move semantics.
   MozPromiseHolder& operator=(MozPromiseHolder&& aOther) {
     MOZ_ASSERT(!mMonitor && !aOther.mMonitor);
     MOZ_DIAGNOSTIC_ASSERT(!mPromise);
     mPromise = std::move(aOther.mPromise);
     return *this;
   }
@@ -1369,17 +1369,17 @@ static RefPtr<PromiseType> InvokeAsyncIm
       ProxyRunnableType;
 
   MethodCallType* methodCall = new MethodCallType(
       aMethod, aThisVal, std::forward<ActualArgTypes>(aArgs)...);
   RefPtr<typename PromiseType::Private> p =
       new (typename PromiseType::Private)(aCallerName);
   RefPtr<ProxyRunnableType> r = new ProxyRunnableType(p, methodCall);
   aTarget->Dispatch(r.forget());
-  return p.forget();
+  return p;
 }
 
 constexpr bool Any() { return false; }
 
 template <typename T1>
 constexpr bool Any(T1 a) {
   return static_cast<bool>(a);
 }
@@ -1485,17 +1485,17 @@ static auto InvokeAsync(nsISerialEventTa
   MOZ_ASSERT(aTarget);
   typedef typename RemoveSmartPointer<decltype(aFunction())>::Type PromiseType;
   typedef detail::ProxyFunctionRunnable<Function, PromiseType>
       ProxyRunnableType;
 
   auto p = MakeRefPtr<typename PromiseType::Private>(aCallerName);
   auto r = MakeRefPtr<ProxyRunnableType>(p, std::forward<Function>(aFunction));
   aTarget->Dispatch(r.forget());
-  return p.forget();
+  return p;
 }
 
 }  // namespace detail
 
 // Invoke a function object (e.g., lambda) asynchronously.
 // Return a promise that the function should eventually resolve or reject.
 template <typename Function>
 static auto InvokeAsync(nsISerialEventTarget* aTarget, const char* aCallerName,
--- a/xpcom/threads/SchedulerGroup.cpp
+++ b/xpcom/threads/SchedulerGroup.cpp
@@ -273,17 +273,17 @@ SchedulerGroup::Runnable::GetName(nsACSt
 }
 #endif
 
 NS_IMETHODIMP
 SchedulerGroup::Runnable::Run() {
   MOZ_RELEASE_ASSERT(NS_IsMainThread());
   // The runnable's destructor can have side effects, so try to execute it in
   // the scope of the TabGroup.
-  nsCOMPtr<nsIRunnable> runnable(mRunnable.forget());
+  nsCOMPtr<nsIRunnable> runnable(std::move(mRunnable));
   return runnable->Run();
 }
 
 NS_IMETHODIMP
 SchedulerGroup::Runnable::GetPriority(uint32_t* aPriority) {
   *aPriority = nsIRunnablePriority::PRIORITY_NORMAL;
   nsCOMPtr<nsIRunnablePriority> runnablePrio = do_QueryInterface(mRunnable);
   return runnablePrio ? runnablePrio->GetPriority(aPriority) : NS_OK;
--- a/xpcom/threads/TaskQueue.cpp
+++ b/xpcom/threads/TaskQueue.cpp
@@ -99,17 +99,17 @@ nsresult TaskQueue::DispatchLocked(nsCOM
     MOZ_ASSERT(aFlags == NS_DISPATCH_NORMAL,
                "Tail dispatch doesn't support flags");
     return currentThread->TailDispatcher().AddTask(this, aRunnable.forget());
   }
 
   // If the task queue cares about individual flags, retain them in the struct.
   uint32_t retainFlags = mShouldRetainFlags ? aFlags : 0;
 
-  mTasks.push({aRunnable.forget(), retainFlags});
+  mTasks.push({std::move(aRunnable), retainFlags});
 
   if (mIsRunning) {
     return NS_OK;
   }
   RefPtr<nsIRunnable> runner(new Runner(this));
   nsresult rv = mTarget->Dispatch(runner.forget(), aFlags);
   if (NS_FAILED(rv)) {
     NS_WARNING("Failed to dispatch runnable to run TaskQueue");
--- a/xpcom/threads/ThreadEventTarget.cpp
+++ b/xpcom/threads/ThreadEventTarget.cpp
@@ -40,17 +40,17 @@ class DelayedRunnable : public Runnable,
   NS_DECL_ISUPPORTS_INHERITED
 
   nsresult Init() {
     return NS_NewTimerWithCallback(getter_AddRefs(mTimer), this, mDelay,
                                    nsITimer::TYPE_ONE_SHOT, mTarget);
   }
 
   nsresult DoRun() {
-    nsCOMPtr<nsIRunnable> r = mWrappedRunnable.forget();
+    nsCOMPtr<nsIRunnable> r = std::move(mWrappedRunnable);
     return r->Run();
   }
 
   NS_IMETHOD Run() override {
     // Already ran?
     if (!mWrappedRunnable) {
       return NS_OK;
     }
--- a/xpcom/threads/nsThreadManager.cpp
+++ b/xpcom/threads/nsThreadManager.cpp
@@ -387,17 +387,17 @@ nsresult nsThreadManager::Init() {
   AbstractThread::InitMainThread();
 
   // Initialize the background event target.
   RefPtr<BackgroundEventTarget> target(new BackgroundEventTarget());
 
   rv = target->Init();
   NS_ENSURE_SUCCESS(rv, rv);
 
-  mBackgroundEventTarget = target.forget();
+  mBackgroundEventTarget = std::move(target);
 
   mInitialized = true;
 
   return NS_OK;
 }
 
 void nsThreadManager::Shutdown() {
   MOZ_ASSERT(NS_IsMainThread(), "shutdown not called from main thread");
--- a/xpcom/threads/nsThreadUtils.cpp
+++ b/xpcom/threads/nsThreadUtils.cpp
@@ -317,17 +317,17 @@ class IdleRunnableWrapper final : public
   explicit IdleRunnableWrapper(already_AddRefed<nsIRunnable>&& aEvent)
       : mRunnable(std::move(aEvent)) {}
 
   NS_IMETHOD Run() override {
     if (!mRunnable) {
       return NS_OK;
     }
     CancelTimer();
-    nsCOMPtr<nsIRunnable> runnable = mRunnable.forget();
+    nsCOMPtr<nsIRunnable> runnable = std::move(mRunnable);
     return runnable->Run();
   }
 
   static void TimedOut(nsITimer* aTimer, void* aClosure) {
     RefPtr<IdleRunnableWrapper> runnable =
         static_cast<IdleRunnableWrapper*>(aClosure);
     runnable->Run();
   }