Bug 859817 - Remove implicit conversions from raw pointer to already_AddRefed; r=Ms2ger
authorAryeh Gregor <ayg@aryeh.name>
Mon, 22 Apr 2013 14:15:59 +0300
changeset 140998 447cf900cd4f9fed2997882d443739b962d3c1a6
parent 140997 57a0302a88b77893c544e12d4d18b8086a79a449
child 140999 dde0f2ca02d877b8c12fac0d8cb58878a386de84
push id2579
push userakeybl@mozilla.com
push dateMon, 24 Jun 2013 18:52:47 +0000
treeherdermozilla-beta@b69b7de8a05a [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersMs2ger
bugs859817
milestone23.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 859817 - Remove implicit conversions from raw pointer to already_AddRefed; r=Ms2ger
accessible/src/base/nsAccessibilityService.cpp
accessible/src/base/nsCoreUtils.cpp
accessible/src/generic/Accessible.cpp
accessible/src/generic/Accessible.h
accessible/src/xul/XULElementAccessibles.cpp
accessible/src/xul/XULFormControlAccessible.cpp
accessible/src/xul/XULSelectControlAccessible.cpp
accessible/src/xul/XULTreeAccessible.cpp
chrome/src/nsChromeRegistry.cpp
content/base/public/nsIDocument.h
content/base/src/Attr.cpp
content/base/src/Element.cpp
content/base/src/FragmentOrElement.cpp
content/base/src/nsAttrAndChildArray.cpp
content/base/src/nsAttrValue.cpp
content/base/src/nsContentAreaDragDrop.cpp
content/base/src/nsContentList.cpp
content/base/src/nsContentUtils.cpp
content/base/src/nsDocument.cpp
content/base/src/nsNodeInfoManager.cpp
content/base/src/nsObjectLoadingContent.cpp
content/base/src/nsRange.cpp
content/canvas/src/CanvasRenderingContext2D.cpp
content/canvas/src/WebGLContext.cpp
content/canvas/src/WebGLContextGL.cpp
content/events/src/nsDOMTextEvent.cpp
content/events/src/nsDOMUIEvent.cpp
content/events/src/nsEventStateManager.cpp
content/events/src/nsPrivateTextRange.cpp
content/html/content/src/HTMLAnchorElement.cpp
content/html/content/src/nsHTMLFormElement.cpp
content/html/document/src/nsHTMLContentSink.cpp
content/html/document/src/nsHTMLDocument.cpp
content/media/webspeech/synth/SpeechSynthesisUtterance.cpp
content/media/webspeech/synth/nsSynthVoiceRegistry.cpp
content/svg/content/src/SVGTests.cpp
content/svg/content/src/SVGTransformableElement.cpp
content/xbl/src/nsXBLPrototypeBinding.cpp
content/xbl/src/nsXBLPrototypeHandler.cpp
content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
content/xul/content/src/nsXULElement.cpp
content/xul/content/src/nsXULPopupListener.cpp
content/xul/document/src/XULDocument.cpp
dom/base/nsGlobalWindow.cpp
dom/base/nsJSEnvironment.cpp
dom/plugins/base/nsNPAPIPluginInstance.cpp
dom/plugins/base/nsPluginHost.cpp
editor/composer/src/nsComposerCommandsUpdater.cpp
editor/txmgr/src/nsTransactionStack.cpp
embedding/components/windowwatcher/src/nsWindowWatcher.cpp
gfx/layers/ImageContainer.cpp
gfx/layers/opengl/ImageLayerOGL.cpp
gfx/thebes/gfxASurface.cpp
gfx/thebes/gfxContext.cpp
gfx/thebes/gfxFont.cpp
gfx/thebes/gfxImageSurface.cpp
gfx/thebes/gfxPlatform.cpp
image/src/imgLoader.cpp
image/src/imgLoader.h
intl/locale/src/nsLanguageAtomService.cpp
js/jsd/jsd_xpc.cpp
layout/base/nsCSSFrameConstructor.cpp
layout/base/nsPresContext.cpp
layout/base/nsPresShell.cpp
layout/forms/nsListControlFrame.cpp
layout/generic/nsFrame.cpp
layout/generic/nsTextFrameThebes.cpp
layout/printing/nsPrintEngine.cpp
layout/style/StyleRule.cpp
layout/style/nsCSSStyleSheet.cpp
layout/style/nsComputedDOMStyle.cpp
layout/style/nsHTMLStyleSheet.cpp
layout/style/nsRuleNode.cpp
layout/style/nsStyleContext.cpp
layout/style/nsStyleSet.cpp
layout/svg/nsSVGFilterInstance.cpp
layout/svg/nsSVGGradientFrame.cpp
layout/svg/nsSVGMaskFrame.cpp
layout/tools/layout-debug/src/nsLayoutDebuggingTools.cpp
layout/xul/base/src/nsListBoxLayout.cpp
layout/xul/base/src/nsSliderFrame.cpp
layout/xul/grid/nsGridRowGroupLayout.cpp
layout/xul/grid/nsGridRowLeafLayout.cpp
layout/xul/tree/nsTreeBodyFrame.h
media/webrtc/signaling/test/FakeMediaStreams.h
netwerk/base/public/nsNetUtil.h
netwerk/base/src/nsSocketTransportService2.cpp
parser/html/nsHtml5Module.cpp
rdf/base/src/nsRDFXMLSerializer.cpp
security/manager/boot/src/nsSecureBrowserUIImpl.cpp
security/manager/ssl/src/nsCertTree.cpp
toolkit/components/places/tests/cpp/places_test_harness.h
toolkit/components/telemetry/Telemetry.cpp
toolkit/components/typeaheadfind/nsTypeAheadFind.cpp
toolkit/system/dbus/nsDBusService.cpp
toolkit/xre/nsAppRunner.cpp
uriloader/base/nsDocLoader.cpp
uriloader/exthandler/unix/nsGNOMERegistry.cpp
uriloader/exthandler/unix/nsOSHelperAppService.cpp
widget/gtk2/nsWindow.cpp
xpcom/base/nsAutoPtr.h
xpcom/build/Services.cpp
xpcom/build/nsXPComInit.cpp
xpcom/components/nsComponentManager.cpp
xpcom/glue/nsCOMPtr.h
xpcom/glue/nsIWeakReferenceUtils.h
xpcom/tests/TestRacingServiceManager.cpp
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -298,21 +298,20 @@ nsAccessibilityService::CreatePluginAcce
       return nullptr;
 
     // Note this calls into the plugin, so crazy things may happen and aFrame
     // may go away.
     nsCString plugId;
     nsresult rv = pluginInstance->GetValueFromPlugin(
       NPPVpluginNativeAccessibleAtkPlugId, &plugId);
     if (NS_SUCCEEDED(rv) && !plugId.IsEmpty()) {
-      AtkSocketAccessible* socketAccessible =
+      nsRefPtr<AtkSocketAccessible> socketAccessible =
         new AtkSocketAccessible(aContent, aContext->Document(), plugId);
 
-      NS_ADDREF(socketAccessible);
-      return socketAccessible;
+      return socketAccessible.forget();
     }
 #endif
   }
 #endif
 
   return nullptr;
 }
 
@@ -1127,22 +1126,21 @@ nsAccessibilityService::CreateAccessible
     return nullptr;
 
   int32_t type;
   nsresult rv = accessibleProvider->GetAccessibleType(&type);
   if (NS_FAILED(rv))
     return nullptr;
 
   if (type == nsIAccessibleProvider::OuterDoc) {
-    Accessible* accessible = new OuterDocAccessible(aContent, aDoc);
-    NS_ADDREF(accessible);
-    return accessible;
+    nsRefPtr<Accessible> accessible = new OuterDocAccessible(aContent, aDoc);
+    return accessible.forget();
   }
 
-  Accessible* accessible = nullptr;
+  nsRefPtr<Accessible> accessible;
   switch (type)
   {
 #ifdef MOZ_XUL
     case nsIAccessibleProvider::NoAccessible:
       return nullptr;
 
     // XUL controls
     case nsIAccessibleProvider::XULAlert:
@@ -1317,109 +1315,106 @@ nsAccessibilityService::CreateAccessible
       break;
 
 #endif // MOZ_XUL
 
     default:
       return nullptr;
   }
 
-  NS_IF_ADDREF(accessible);
-  return accessible;
+  return accessible.forget();
 }
 
 already_AddRefed<Accessible>
 nsAccessibilityService::CreateHTMLAccessibleByMarkup(nsIFrame* aFrame,
                                                      nsIContent* aContent,
                                                      Accessible* aContext)
 {
   DocAccessible* document = aContext->Document();
   if (aContext->IsTableRow()) {
     if (nsCoreUtils::IsHTMLTableHeader(aContent) &&
         aContext->GetContent() == aContent->GetParent()) {
-      Accessible* accessible = new HTMLTableHeaderCellAccessibleWrap(aContent,
-                                                                     document);
-      NS_ADDREF(accessible);
-      return accessible;
+      nsRefPtr<Accessible> accessible =
+        new HTMLTableHeaderCellAccessibleWrap(aContent, document);
+      return accessible.forget();
     }
 
     return nullptr;
   }
 
   // This method assumes we're in an HTML namespace.
   nsIAtom* tag = aContent->Tag();
   if (tag == nsGkAtoms::figcaption) {
-    Accessible* accessible = new HTMLFigcaptionAccessible(aContent, document);
-    NS_ADDREF(accessible);
-    return accessible;
+    nsRefPtr<Accessible> accessible =
+      new HTMLFigcaptionAccessible(aContent, document);
+    return accessible.forget();
   }
 
   if (tag == nsGkAtoms::figure) {
-    Accessible* accessible = new HTMLFigureAccessible(aContent, document);
-    NS_ADDREF(accessible);
-    return accessible;
+    nsRefPtr<Accessible> accessible =
+      new HTMLFigureAccessible(aContent, document);
+    return accessible.forget();
   }
 
   if (tag == nsGkAtoms::legend) {
-    Accessible* accessible = new HTMLLegendAccessible(aContent, document);
-    NS_ADDREF(accessible);
-    return accessible;
+    nsRefPtr<Accessible> accessible =
+      new HTMLLegendAccessible(aContent, document);
+    return accessible.forget();
   }
 
   if (tag == nsGkAtoms::option) {
-    Accessible* accessible = new HTMLSelectOptionAccessible(aContent, document);
-    NS_ADDREF(accessible);
-    return accessible;
+    nsRefPtr<Accessible> accessible =
+      new HTMLSelectOptionAccessible(aContent, document);
+    return accessible.forget();
   }
 
   if (tag == nsGkAtoms::optgroup) {
-    Accessible* accessible =
+    nsRefPtr<Accessible> accessible =
       new HTMLSelectOptGroupAccessible(aContent, document);
-    NS_ADDREF(accessible);
-    return accessible;
+    return accessible.forget();
   }
 
   if (tag == nsGkAtoms::ul || tag == nsGkAtoms::ol ||
       tag == nsGkAtoms::dl) {
-    Accessible* accessible = new HTMLListAccessible(aContent, document);
-    NS_ADDREF(accessible);
-    return accessible;
+    nsRefPtr<Accessible> accessible =
+      new HTMLListAccessible(aContent, document);
+    return accessible.forget();
   }
 
   if (tag == nsGkAtoms::a) {
     // Only some roles truly enjoy life as HTMLLinkAccessibles, for details
     // see closed bug 494807.
     nsRoleMapEntry* roleMapEntry = aria::GetRoleMap(aContent);
     if (roleMapEntry && roleMapEntry->role != roles::NOTHING &&
         roleMapEntry->role != roles::LINK) {
-      Accessible* accessible = new HyperTextAccessibleWrap(aContent, document);
-      NS_ADDREF(accessible);
-      return accessible;
+      nsRefPtr<Accessible> accessible =
+        new HyperTextAccessibleWrap(aContent, document);
+      return accessible.forget();
     }
 
-    Accessible* accessible = new HTMLLinkAccessible(aContent, document);
-    NS_ADDREF(accessible);
-    return accessible;
+    nsRefPtr<Accessible> accessible =
+      new HTMLLinkAccessible(aContent, document);
+    return accessible.forget();
   }
 
   if (aContext->IsList()) {
     // If list item is a child of accessible list then create an accessible for
     // it unconditionally by tag name. nsBlockFrame creates the list item
     // accessible for other elements styled as list items.
     if (aContext->GetContent() == aContent->GetParent()) {
       if (tag == nsGkAtoms::dt || tag == nsGkAtoms::li) {
-        Accessible* accessible = new HTMLLIAccessible(aContent, document);
-        NS_ADDREF(accessible);
-        return accessible;
+        nsRefPtr<Accessible> accessible =
+          new HTMLLIAccessible(aContent, document);
+        return accessible.forget();
       }
 
       if (tag == nsGkAtoms::dd) {
-        Accessible* accessible = new HyperTextAccessibleWrap(aContent, document);
-        NS_ADDREF(accessible);
-        return accessible;
+        nsRefPtr<Accessible> accessible =
+          new HyperTextAccessibleWrap(aContent, document);
+        return accessible.forget();
       }
     }
 
     return nullptr;
   }
 
   if (tag == nsGkAtoms::abbr ||
       tag == nsGkAtoms::acronym ||
@@ -1427,32 +1422,31 @@ nsAccessibilityService::CreateHTMLAccess
       tag == nsGkAtoms::form ||
       tag == nsGkAtoms::h1 ||
       tag == nsGkAtoms::h2 ||
       tag == nsGkAtoms::h3 ||
       tag == nsGkAtoms::h4 ||
       tag == nsGkAtoms::h5 ||
       tag == nsGkAtoms::h6 ||
       tag == nsGkAtoms::q) {
-    Accessible* accessible = new HyperTextAccessibleWrap(aContent, document);
-    NS_ADDREF(accessible);
-    return accessible;
+    nsRefPtr<Accessible> accessible =
+      new HyperTextAccessibleWrap(aContent, document);
+    return accessible.forget();
   }
 
   if (tag == nsGkAtoms::output) {
-    Accessible* accessible = new HTMLOutputAccessible(aContent, document);
-    NS_ADDREF(accessible);
-    return accessible;
+    nsRefPtr<Accessible> accessible =
+      new HTMLOutputAccessible(aContent, document);
+    return accessible.forget();
   }
 
   if (tag == nsGkAtoms::progress) {
-    Accessible* accessible =
+    nsRefPtr<Accessible> accessible =
       new HTMLProgressMeterAccessible(aContent, document);
-    NS_ADDREF(accessible);
-    return accessible;
+    return accessible.forget();
   }
 
   return nullptr;
  }
 
 already_AddRefed<Accessible>
 nsAccessibilityService::CreateAccessibleByFrameType(nsIFrame* aFrame,
                                                     nsIContent* aContent,
@@ -1658,25 +1652,25 @@ nsAccessibilityService::CreateAccessible
     return nullptr;
 
   nsRefPtr<nsTreeColumns> treeCols = treeFrame->Columns();
   int32_t count = 0;
   treeCols->GetCount(&count);
 
   // Outline of list accessible.
   if (count == 1) {
-    Accessible* accessible = new XULTreeAccessible(aContent, aDoc, treeFrame);
-    NS_ADDREF(accessible);
-    return accessible;
+    nsRefPtr<Accessible> accessible =
+      new XULTreeAccessible(aContent, aDoc, treeFrame);
+    return accessible.forget();
   }
 
   // Table or tree table accessible.
-  Accessible* accessible = new XULTreeGridAccessibleWrap(aContent, aDoc, treeFrame);
-  NS_ADDREF(accessible);
-  return accessible;
+  nsRefPtr<Accessible> accessible =
+    new XULTreeGridAccessibleWrap(aContent, aDoc, treeFrame);
+  return accessible.forget();
 }
 #endif
 
 ////////////////////////////////////////////////////////////////////////////////
 // Services
 ////////////////////////////////////////////////////////////////////////////////
 
 namespace mozilla {
--- a/accessible/src/base/nsCoreUtils.cpp
+++ b/accessible/src/base/nsCoreUtils.cpp
@@ -512,19 +512,19 @@ already_AddRefed<nsIBoxObject>
 nsCoreUtils::GetTreeBodyBoxObject(nsITreeBoxObject *aTreeBoxObj)
 {
   nsCOMPtr<nsIDOMElement> tcElm;
   aTreeBoxObj->GetTreeBody(getter_AddRefs(tcElm));
   nsCOMPtr<nsIDOMXULElement> tcXULElm(do_QueryInterface(tcElm));
   if (!tcXULElm)
     return nullptr;
 
-  nsIBoxObject *boxObj = nullptr;
-  tcXULElm->GetBoxObject(&boxObj);
-  return boxObj;
+  nsCOMPtr<nsIBoxObject> boxObj;
+  tcXULElm->GetBoxObject(getter_AddRefs(boxObj));
+  return boxObj.forget();
 }
 
 already_AddRefed<nsITreeBoxObject>
 nsCoreUtils::GetTreeBoxObject(nsIContent *aContent)
 {
   // Find DOMNode's parents recursively until reach the <tree> tag
   nsIContent* currentContent = aContent;
   while (currentContent) {
--- a/accessible/src/generic/Accessible.cpp
+++ b/accessible/src/generic/Accessible.cpp
@@ -2842,19 +2842,17 @@ Accessible::SelectedItems()
   if (!selectedItems)
     return nullptr;
 
   AccIterator iter(this, filters::GetSelected);
   nsIAccessible* selected = nullptr;
   while ((selected = iter.Next()))
     selectedItems->AppendElement(selected, false);
 
-  nsIMutableArray* items = nullptr;
-  selectedItems.forget(&items);
-  return items;
+  return selectedItems.forget();
 }
 
 uint32_t
 Accessible::SelectedItemCount()
 {
   uint32_t count = 0;
   AccIterator iter(this, filters::GetSelected);
   Accessible* selected = nullptr;
--- a/accessible/src/generic/Accessible.h
+++ b/accessible/src/generic/Accessible.h
@@ -145,20 +145,18 @@ public:
    */
   virtual ENameValueFlag Name(nsString& aName);
 
   /**
    * Return DOM node associated with this accessible.
    */
   inline already_AddRefed<nsIDOMNode> DOMNode() const
   {
-    nsIDOMNode *DOMNode = nullptr;
-    if (GetNode())
-      CallQueryInterface(GetNode(), &DOMNode);
-    return DOMNode;
+    nsCOMPtr<nsIDOMNode> DOMNode = do_QueryInterface(GetNode());
+    return DOMNode.forget();
   }
 
   /**
    * Maps ARIA state attributes to state of accessible. Note the given state
    * argument should hold states for accessible before you pass it into this
    * method.
    *
    * @param  [in/out] where to fill the states into.
--- a/accessible/src/xul/XULElementAccessibles.cpp
+++ b/accessible/src/xul/XULElementAccessibles.cpp
@@ -295,15 +295,15 @@ XULLinkAccessible::AnchorURIAt(uint32_t 
     return nullptr;
 
   nsAutoString href;
   mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::href, href);
 
   nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
   nsIDocument* document = mContent->OwnerDoc();
 
-  nsIURI* anchorURI = nullptr;
-  NS_NewURI(&anchorURI, href,
+  nsCOMPtr<nsIURI> anchorURI;
+  NS_NewURI(getter_AddRefs(anchorURI), href,
             document->GetDocumentCharacterSet().get(),
             baseURI);
 
-  return anchorURI;
+  return anchorURI.forget();
 }
--- a/accessible/src/xul/XULFormControlAccessible.cpp
+++ b/accessible/src/xul/XULFormControlAccessible.cpp
@@ -859,14 +859,11 @@ XULTextFieldAccessible::GetInputField() 
     // <xul:menulist droppable="false">
     nsCOMPtr<nsIDOMXULMenuListElement> menuList = do_QueryInterface(mContent);
     if (menuList)
       menuList->GetInputField(getter_AddRefs(inputFieldDOMNode));
   }
 
   NS_ASSERTION(inputFieldDOMNode, "No input field for XULTextFieldAccessible");
 
-  nsIContent* inputField = nullptr;
-  if (inputFieldDOMNode)
-    CallQueryInterface(inputFieldDOMNode, &inputField);
-
-  return inputField;
+  nsCOMPtr<nsIContent> inputField = do_QueryInterface(inputFieldDOMNode);
+  return inputField.forget();
 }
--- a/accessible/src/xul/XULSelectControlAccessible.cpp
+++ b/accessible/src/xul/XULSelectControlAccessible.cpp
@@ -78,19 +78,17 @@ XULSelectControlAccessible::SelectedItem
     if (itemNode) {
       Accessible* item = mDoc->GetAccessible(itemNode);
       if (item)
         selectedItems->AppendElement(static_cast<nsIAccessible*>(item),
                                    false);
     }
   }
 
-  nsIMutableArray* items = nullptr;
-  selectedItems.forget(&items);
-  return items;
+  return selectedItems.forget();
 }
 
 Accessible*
 XULSelectControlAccessible::GetSelectedItem(uint32_t aIndex)
 {
   nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelectControl =
     do_QueryInterface(mSelectControl);
 
--- a/accessible/src/xul/XULTreeAccessible.cpp
+++ b/accessible/src/xul/XULTreeAccessible.cpp
@@ -270,19 +270,17 @@ XULTreeAccessible::SelectedItems()
     selection->GetRangeAt(rangeIdx, &firstIdx, &lastIdx);
     for (int32_t rowIdx = firstIdx; rowIdx <= lastIdx; rowIdx++) {
       nsIAccessible* item = GetTreeItemAccessible(rowIdx);
       if (item)
         selectedItems->AppendElement(item, false);
     }
   }
 
-  nsIMutableArray* items = nullptr;
-  selectedItems.forget(&items);
-  return items;
+  return selectedItems.forget();
 }
 
 uint32_t
 XULTreeAccessible::SelectedItemCount()
 {
   if (!mTreeView)
     return 0;
 
--- a/chrome/src/nsChromeRegistry.cpp
+++ b/chrome/src/nsChromeRegistry.cpp
@@ -128,18 +128,18 @@ nsChromeRegistry::GetService()
   {
     // We don't actually want this ref, we just want the service to
     // initialize if it hasn't already.
     nsCOMPtr<nsIChromeRegistry> reg(
         do_GetService(NS_CHROMEREGISTRY_CONTRACTID));
     if (!gChromeRegistry)
       return nullptr;
   }
-  NS_ADDREF(gChromeRegistry);
-  return gChromeRegistry;
+  nsCOMPtr<nsIChromeRegistry> registry = gChromeRegistry;
+  return registry.forget();
 }
 
 nsresult
 nsChromeRegistry::Init()
 {
   mOverrideTable.Init();
 
   // This initialization process is fairly complicated and may cause reentrant
@@ -627,18 +627,18 @@ nsChromeRegistry::WrappersEnabled(nsIURI
   rv = GetFlagsFromPackage(package, &flags);
   return NS_SUCCEEDED(rv) && (flags & XPCNATIVEWRAPPERS);
 }
 
 already_AddRefed<nsChromeRegistry>
 nsChromeRegistry::GetSingleton()
 {
   if (gChromeRegistry) {
-    NS_ADDREF(gChromeRegistry);
-    return gChromeRegistry;
+    nsRefPtr<nsChromeRegistry> registry = gChromeRegistry;
+    return registry.forget();
   }
 
   nsRefPtr<nsChromeRegistry> cr;
   if (GeckoProcessType_Content == XRE_GetProcessType())
     cr = new nsChromeRegistryContent();
   else
     cr = new nsChromeRegistryChrome();
 
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -242,21 +242,18 @@ public:
    */
   virtual void SetPrincipal(nsIPrincipal *aPrincipal) = 0;
 
   /**
    * Return the LoadGroup for the document. May return null.
    */
   already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const
   {
-    nsILoadGroup *group = nullptr;
-    if (mDocumentLoadGroup)
-      CallQueryReferent(mDocumentLoadGroup.get(), &group);
-
-    return group;
+    nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
+    return group.forget();
   }
 
   /**
    * Return the base URI for relative URIs in the document (the document uri
    * unless it's overridden by SetBaseURI, HTML <base> tags, etc.).  The
    * returned URI could be null if there is no document URI.
    */
   nsIURI* GetDocBaseURI() const
@@ -1075,21 +1072,18 @@ public:
    */
   virtual void SetContainer(nsISupports *aContainer);
 
   /**
    * Get the container (docshell) for this document.
    */
   already_AddRefed<nsISupports> GetContainer() const
   {
-    nsISupports* container = nullptr;
-    if (mDocumentContainer)
-      CallQueryReferent(mDocumentContainer.get(), &container);
-
-    return container;
+    nsCOMPtr<nsISupports> container = do_QueryReferent(mDocumentContainer);
+    return container.forget();
   }
 
   /**
    * Get the container's load context for this document.
    */
   nsILoadContext* GetLoadContext() const
   {
     nsCOMPtr<nsISupports> container = GetContainer();
--- a/content/base/src/Attr.cpp
+++ b/content/base/src/Attr.cpp
@@ -128,32 +128,28 @@ Attr::GetName(nsAString& aName)
 {
   aName = NodeName();
   return NS_OK;
 }
 
 already_AddRefed<nsIAtom>
 Attr::GetNameAtom(nsIContent* aContent)
 {
-  nsIAtom* result = nullptr;
   if (!mNsAware &&
       mNodeInfo->NamespaceID() == kNameSpaceID_None &&
       aContent->IsInHTMLDocument() &&
       aContent->IsHTML()) {
     nsString name;
     mNodeInfo->GetName(name);
     nsAutoString lowercaseName;
     nsContentUtils::ASCIIToLower(name, lowercaseName);
-    nsCOMPtr<nsIAtom> nameAtom = do_GetAtom(lowercaseName);
-    nameAtom.swap(result);
-  } else {
-    nsCOMPtr<nsIAtom> nameAtom = mNodeInfo->NameAtom();
-    nameAtom.swap(result);
+    return do_GetAtom(lowercaseName);
   }
-  return result;
+  nsCOMPtr<nsIAtom> nameAtom = mNodeInfo->NameAtom();
+  return nameAtom.forget();
 }
 
 NS_IMETHODIMP
 Attr::GetValue(nsAString& aValue)
 {
   nsIContent* content = GetContentInternal();
   if (content) {
     nsCOMPtr<nsIAtom> nameAtom = GetNameAtom(content);
--- a/content/base/src/Element.cpp
+++ b/content/base/src/Element.cpp
@@ -1438,27 +1438,27 @@ Element::FindAttributeDependence(const n
 already_AddRefed<nsINodeInfo>
 Element::GetExistingAttrNameFromQName(const nsAString& aStr) const
 {
   const nsAttrName* name = InternalGetExistingAttrNameFromQName(aStr);
   if (!name) {
     return nullptr;
   }
 
-  nsINodeInfo* nodeInfo;
+  nsCOMPtr<nsINodeInfo> nodeInfo;
   if (name->IsAtom()) {
     nodeInfo = mNodeInfo->NodeInfoManager()->
       GetNodeInfo(name->Atom(), nullptr, kNameSpaceID_None,
-                  nsIDOMNode::ATTRIBUTE_NODE).get();
+                  nsIDOMNode::ATTRIBUTE_NODE);
   }
   else {
-    NS_ADDREF(nodeInfo = name->NodeInfo());
+    nodeInfo = name->NodeInfo();
   }
 
-  return nodeInfo;
+  return nodeInfo.forget();
 }
 
 // static
 bool
 Element::ShouldBlur(nsIContent *aContent)
 {
   // Determine if the current element is focused, if it is not focused
   // then we should not try to blur
--- a/content/base/src/FragmentOrElement.cpp
+++ b/content/base/src/FragmentOrElement.cpp
@@ -686,19 +686,17 @@ FragmentOrElement::GetChildren(uint32_t 
 
     // Append :after generated content.
     nsIFrame *afterFrame = nsLayoutUtils::GetAfterFrame(frame);
     if (afterFrame) {
       list->AppendElement(afterFrame->GetContent());
     }
   }
 
-  nsINodeList* returnList = nullptr;
-  list.forget(&returnList);
-  return returnList;
+  return list.forget();
 }
 
 static nsIContent*
 FindChromeAccessOnlySubtreeOwner(nsIContent* aContent)
 {
   if (aContent->ChromeOnlyAccess()) {
     bool chromeAccessOnly = false;
     while (aContent && !chromeAccessOnly) {
--- a/content/base/src/nsAttrAndChildArray.cpp
+++ b/content/base/src/nsAttrAndChildArray.cpp
@@ -204,17 +204,17 @@ nsAttrAndChildArray::TakeChildAt(uint32_
   if (child->mNextSibling) {
     child->mNextSibling->mPreviousSibling = child->mPreviousSibling;
   }
   child->mPreviousSibling = child->mNextSibling = nullptr;
 
   memmove(pos, pos + 1, (childCount - aPos - 1) * sizeof(nsIContent*));
   SetChildCount(childCount - 1);
 
-  return child;
+  return dont_AddRef(child);
 }
 
 int32_t
 nsAttrAndChildArray::IndexOfChild(const nsINode* aPossibleChild) const
 {
   if (!mImpl) {
     return -1;
   }
--- a/content/base/src/nsAttrValue.cpp
+++ b/content/base/src/nsAttrValue.cpp
@@ -734,19 +734,18 @@ already_AddRefed<nsIAtom>
 nsAttrValue::GetAsAtom() const
 {
   switch (Type()) {
     case eString:
       return do_GetAtom(GetStringValue());
 
     case eAtom:
       {
-        nsIAtom* atom = GetAtomValue();
-        NS_ADDREF(atom);
-        return atom;
+        nsCOMPtr<nsIAtom> atom = GetAtomValue();
+        return atom.forget();
       }
 
     default:
       {
         nsAutoString val;
         ToString(val);
         return do_GetAtom(val);
       }
--- a/content/base/src/nsContentAreaDragDrop.cpp
+++ b/content/base/src/nsContentAreaDragDrop.cpp
@@ -269,18 +269,18 @@ DragDataProducer::FindParentLinkNode(nsI
   nsIContent* content = inNode;
   if (!content) {
     // That must have been the document node; nothing else to do here;
     return nullptr;
   }
 
   for (; content; content = content->GetParent()) {
     if (nsContentUtils::IsDraggableLink(content)) {
-      NS_ADDREF(content);
-      return content;
+      nsCOMPtr<nsIContent> ret = content;
+      return ret.forget();
     }
   }
 
   return nullptr;
 }
 
 
 //
--- a/content/base/src/nsContentList.cpp
+++ b/content/base/src/nsContentList.cpp
@@ -191,17 +191,17 @@ ContentListHashtableMatchEntry(PLDHashTa
 already_AddRefed<nsContentList>
 NS_GetContentList(nsINode* aRootNode, 
                   int32_t  aMatchNameSpaceId,
                   const nsAString& aTagname)
                   
 {
   NS_ASSERTION(aRootNode, "content list has to have a root");
 
-  nsContentList* list = nullptr;
+  nsRefPtr<nsContentList> list;
 
   static PLDHashTableOps hash_table_ops =
   {
     PL_DHashAllocTable,
     PL_DHashFreeTable,
     ContentListHashtableHashKey,
     ContentListHashtableMatchEntry,
     PL_DHashMoveEntryStub,
@@ -250,19 +250,17 @@ NS_GetContentList(nsINode* aRootNode,
     }
     list = new nsContentList(aRootNode, aMatchNameSpaceId,
                              htmlAtom, xmlAtom);
     if (entry) {
       entry->mContentList = list;
     }
   }
 
-  NS_ADDREF(list);
-
-  return list;
+  return list.forget();
 }
 
 #ifdef DEBUG
 const nsCacheableFuncStringContentList::ContentListType
   nsCacheableFuncStringNodeList::sType = nsCacheableFuncStringContentList::eNodeList;
 const nsCacheableFuncStringContentList::ContentListType
   nsCacheableFuncStringHTMLCollection::sType = nsCacheableFuncStringContentList::eHTMLCollection;
 #endif
@@ -314,17 +312,17 @@ already_AddRefed<nsContentList>
 GetFuncStringContentList(nsINode* aRootNode,
                          nsContentListMatchFunc aFunc,
                          nsContentListDestroyFunc aDestroyFunc,
                          nsFuncStringContentListDataAllocator aDataAllocator,
                          const nsAString& aString)
 {
   NS_ASSERTION(aRootNode, "content list has to have a root");
 
-  nsCacheableFuncStringContentList* list = nullptr;
+  nsRefPtr<nsCacheableFuncStringContentList> list;
 
   static PLDHashTableOps hash_table_ops =
   {
     PL_DHashAllocTable,
     PL_DHashFreeTable,
     FuncStringContentListHashtableHashKey,
     FuncStringContentListHashtableMatchEntry,
     PL_DHashMoveEntryStub,
@@ -368,21 +366,19 @@ GetFuncStringContentList(nsINode* aRootN
     // we have an entry
     list = new ListType(aRootNode, aFunc, aDestroyFunc, aDataAllocator,
                         aString);
     if (entry) {
       entry->mContentList = list;
     }
   }
 
-  NS_ADDREF(list);
-
   // Don't cache these lists globally
 
-  return list;
+  return list.forget();
 }
 
 already_AddRefed<nsContentList>
 NS_GetFuncStringNodeList(nsINode* aRootNode,
                          nsContentListMatchFunc aFunc,
                          nsContentListDestroyFunc aDestroyFunc,
                          nsFuncStringContentListDataAllocator aDataAllocator,
                          const nsAString& aString)
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -5256,22 +5256,22 @@ nsContentUtils::HidePopupsInDocument(nsI
   }
 #endif
 }
 
 /* static */
 already_AddRefed<nsIDragSession>
 nsContentUtils::GetDragSession()
 {
-  nsIDragSession* dragSession = nullptr;
+  nsCOMPtr<nsIDragSession> dragSession;
   nsCOMPtr<nsIDragService> dragService =
     do_GetService("@mozilla.org/widget/dragservice;1");
   if (dragService)
-    dragService->GetCurrentSession(&dragSession);
-  return dragSession;
+    dragService->GetCurrentSession(getter_AddRefs(dragSession));
+  return dragSession.forget();
 }
 
 /* static */
 nsresult
 nsContentUtils::SetDataTransferInEvent(nsDragEvent* aDragEvent)
 {
   if (aDragEvent->dataTransfer || !aDragEvent->mFlags.mIsTrusted)
     return NS_OK;
@@ -5831,25 +5831,23 @@ nsContentUtils::GetUTFOrigin(nsIURI* aUR
 already_AddRefed<nsIDocument>
 nsContentUtils::GetDocumentFromScriptContext(nsIScriptContext *aScriptContext)
 {
   if (!aScriptContext)
     return nullptr;
 
   nsCOMPtr<nsIDOMWindow> window =
     do_QueryInterface(aScriptContext->GetGlobalObject());
-  nsIDocument *doc = nullptr;
+  nsCOMPtr<nsIDocument> doc;
   if (window) {
     nsCOMPtr<nsIDOMDocument> domdoc;
     window->GetDocument(getter_AddRefs(domdoc));
-    if (domdoc) {
-      CallQueryInterface(domdoc, &doc);
-    }
-  }
-  return doc;
+    doc = do_QueryInterface(domdoc);
+  }
+  return doc.forget();
 }
 
 /* static */
 bool
 nsContentUtils::CheckMayLoad(nsIPrincipal* aPrincipal, nsIChannel* aChannel, bool aAllowIfInheritsPrincipal)
 {
   nsCOMPtr<nsIURI> channelURI;
   nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(channelURI));
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -7659,27 +7659,27 @@ nsDocument::RemovedFromDocShell()
   for (i = 0; i < count; ++i) {
     mChildren.ChildAt(i)->SaveSubtreeState();
   }
 }
 
 already_AddRefed<nsILayoutHistoryState>
 nsDocument::GetLayoutHistoryState() const
 {
-  nsILayoutHistoryState* state = nullptr;
+  nsCOMPtr<nsILayoutHistoryState> state;
   if (!mScriptGlobalObject) {
-    NS_IF_ADDREF(state = mLayoutHistoryState);
+    state = mLayoutHistoryState;
   } else {
     nsCOMPtr<nsIDocShell> docShell(do_QueryReferent(mDocumentContainer));
     if (docShell) {
-      docShell->GetLayoutHistoryState(&state);
-    }
-  }
-
-  return state;
+      docShell->GetLayoutHistoryState(getter_AddRefs(state));
+    }
+  }
+
+  return state.forget();
 }
 
 void
 nsDocument::EnsureOnloadBlocker()
 {
   // If mScriptGlobalObject is null, we shouldn't be messing with the loadgroup
   // -- it's not ours.
   if (mOnloadBlockCount != 0 && mScriptGlobalObject) {
--- a/content/base/src/nsNodeInfoManager.cpp
+++ b/content/base/src/nsNodeInfoManager.cpp
@@ -237,41 +237,36 @@ nsNodeInfoManager::GetNodeInfo(nsIAtom *
   CheckValidNodeInfo(aNodeType, aName, aNamespaceID, aExtraName);
 
   nsINodeInfo::nsNodeInfoInner tmpKey(aName, aPrefix, aNamespaceID, aNodeType,
                                       aExtraName);
 
   void *node = PL_HashTableLookup(mNodeInfoHash, &tmpKey);
 
   if (node) {
-    nsINodeInfo* nodeInfo = static_cast<nsINodeInfo *>(node);
+    nsCOMPtr<nsINodeInfo> nodeInfo = static_cast<nsINodeInfo*>(node);
 
-    NS_ADDREF(nodeInfo);
-
-    return nodeInfo;
+    return nodeInfo.forget();
   }
 
   nsRefPtr<nsNodeInfo> newNodeInfo =
     new nsNodeInfo(aName, aPrefix, aNamespaceID, aNodeType, aExtraName, this);
 
   PLHashEntry *he;
   he = PL_HashTableAdd(mNodeInfoHash, &newNodeInfo->mInner, newNodeInfo);
   MOZ_ASSERT(he, "PL_HashTableAdd() failed");
 
   // Have to do the swap thing, because already_AddRefed<nsNodeInfo>
   // doesn't cast to already_AddRefed<nsINodeInfo>
   ++mNonDocumentNodeInfos;
   if (mNonDocumentNodeInfos == 1) {
     NS_IF_ADDREF(mDocument);
   }
 
-  nsNodeInfo *nodeInfo = nullptr;
-  newNodeInfo.swap(nodeInfo);
-
-  return nodeInfo;
+  return newNodeInfo.forget();
 }
 
 
 nsresult
 nsNodeInfoManager::GetNodeInfo(const nsAString& aName, nsIAtom *aPrefix,
                                int32_t aNamespaceID, uint16_t aNodeType,
                                nsINodeInfo** aNodeInfo)
 {
--- a/content/base/src/nsObjectLoadingContent.cpp
+++ b/content/base/src/nsObjectLoadingContent.cpp
@@ -981,19 +981,18 @@ nsObjectLoadingContent::GetFrameLoader(n
 {
   NS_IF_ADDREF(*aFrameLoader = mFrameLoader);
   return NS_OK;
 }
 
 NS_IMETHODIMP_(already_AddRefed<nsFrameLoader>)
 nsObjectLoadingContent::GetFrameLoader()
 {
-  nsFrameLoader* loader = mFrameLoader;
-  NS_IF_ADDREF(loader);
-  return loader;
+  nsRefPtr<nsFrameLoader> loader = mFrameLoader;
+  return loader.forget();
 }
 
 NS_IMETHODIMP
 nsObjectLoadingContent::SwapFrameLoaders(nsIFrameLoaderOwner* aOtherLoader)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -1528,32 +1528,27 @@ RangeSubtreeIterator::Init(nsIDOMRange *
   First();
 
   return NS_OK;
 }
 
 already_AddRefed<nsIDOMNode>
 RangeSubtreeIterator::GetCurrentNode()
 {
-  nsIDOMNode *node = nullptr;
+  nsCOMPtr<nsIDOMNode> node;
 
   if (mIterState == eUseStart && mStart) {
-    NS_ADDREF(node = mStart);
-  } else if (mIterState == eUseEnd && mEnd)
-    NS_ADDREF(node = mEnd);
-  else if (mIterState == eUseIterator && mIter)
-  {
-    nsINode* n = mIter->GetCurrentNode();
-
-    if (n) {
-      CallQueryInterface(n, &node);
-    }
+    node = mStart;
+  } else if (mIterState == eUseEnd && mEnd) {
+    node = mEnd;
+  } else if (mIterState == eUseIterator && mIter) {
+    node = do_QueryInterface(mIter->GetCurrentNode());
   }
 
-  return node;
+  return node.forget();
 }
 
 void
 RangeSubtreeIterator::First()
 {
   if (mStart)
     mIterState = eUseStart;
   else if (mIter)
--- a/content/canvas/src/CanvasRenderingContext2D.cpp
+++ b/content/canvas/src/CanvasRenderingContext2D.cpp
@@ -3710,18 +3710,18 @@ CanvasRenderingContext2D::GetCanvasLayer
 
   mTarget->Flush();
 
   if (!mResetLayer && aOldLayer) {
     CanvasRenderingContext2DUserData* userData =
       static_cast<CanvasRenderingContext2DUserData*>(
         aOldLayer->GetUserData(&g2DContextLayerUserData));
     if (userData && userData->IsForContext(this)) {
-      NS_ADDREF(aOldLayer);
-      return aOldLayer;
+      nsRefPtr<CanvasLayer> ret = aOldLayer;
+      return ret.forget();
     }
   }
 
   nsRefPtr<CanvasLayer> canvasLayer = aManager->CreateCanvasLayer();
   if (!canvasLayer) {
     NS_WARNING("CreateCanvasLayer returned null!");
     // No DidTransactionCallback will be received, so mark the context clean
     // now so future invalidations will be dispatched.
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -832,18 +832,18 @@ WebGLContext::GetCanvasLayer(nsDisplayLi
                              CanvasLayer *aOldLayer,
                              LayerManager *aManager)
 {
     if (!IsContextStable())
         return nullptr;
 
     if (!mResetLayer && aOldLayer &&
         aOldLayer->HasUserData(&gWebGLLayerUserData)) {
-        NS_ADDREF(aOldLayer);
-        return aOldLayer;
+        nsRefPtr<layers::CanvasLayer> ret = aOldLayer;
+        return ret.forget();
     }
 
     nsRefPtr<CanvasLayer> canvasLayer = aManager->CreateCanvasLayer();
     if (!canvasLayer) {
         NS_WARNING("CreateCanvasLayer returned null!");
         return nullptr;
     }
     WebGLContextUserData *userData = nullptr;
@@ -875,17 +875,17 @@ WebGLContext::GetCanvasLayer(nsDisplayLi
 
     canvasLayer->Initialize(data);
     uint32_t flags = gl->Caps().alpha ? 0 : Layer::CONTENT_OPAQUE;
     canvasLayer->SetContentFlags(flags);
     canvasLayer->Updated();
 
     mResetLayer = false;
 
-    return canvasLayer.forget().get();
+    return canvasLayer.forget();
 }
 
 void
 WebGLContext::GetContextAttributes(Nullable<dom::WebGLContextAttributesInitializer> &retval)
 {
     retval.SetNull();
     if (!IsContextStable())
         return;
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -2811,26 +2811,25 @@ WebGLContext::GetUniformLocation(WebGLPr
     NS_LossyConvertUTF16toASCII cname(name);
     nsCString mappedName;
     prog->MapIdentifier(cname, &mappedName);
 
     WebGLuint progname = prog->GLName();
     MakeContextCurrent();
     GLint intlocation = gl->fGetUniformLocation(progname, mappedName.get());
 
-    WebGLUniformLocation *loc = nullptr;
+    nsRefPtr<WebGLUniformLocation> loc;
     if (intlocation >= 0) {
         WebGLUniformInfo info = prog->GetUniformInfoForMappedIdentifier(mappedName);
         loc = new WebGLUniformLocation(this,
                                        prog,
                                        intlocation,
                                        info);
-        NS_ADDREF(loc);
-    }
-    return loc;
+    }
+    return loc.forget();
 }
 
 JS::Value
 WebGLContext::GetVertexAttrib(JSContext* cx, WebGLuint index, WebGLenum pname,
                               ErrorResult& rv)
 {
     if (!IsContextStable())
         return JS::NullValue();
@@ -4669,20 +4668,19 @@ WebGLContext::GetShaderPrecisionFormat(W
             return nullptr;
     }
 
     MakeContextCurrent();
 
     GLint range[2], precision;
     gl->fGetShaderPrecisionFormat(shadertype, precisiontype, range, &precision);
 
-    WebGLShaderPrecisionFormat *retShaderPrecisionFormat
+    nsRefPtr<WebGLShaderPrecisionFormat> retShaderPrecisionFormat
         = new WebGLShaderPrecisionFormat(this, range[0], range[1], precision);
-    NS_ADDREF(retShaderPrecisionFormat);
-    return retShaderPrecisionFormat;
+    return retShaderPrecisionFormat.forget();
 }
 
 void
 WebGLContext::GetShaderSource(WebGLShader *shader, nsAString& retval)
 {
     if (!IsContextStable())
     {
         retval.SetIsVoid(true);
--- a/content/events/src/nsDOMTextEvent.cpp
+++ b/content/events/src/nsDOMTextEvent.cpp
@@ -62,19 +62,17 @@ NS_METHOD nsDOMTextEvent::GetText(nsStri
   aText = mText;
   return NS_OK;
 }
 
 NS_METHOD_(already_AddRefed<nsIPrivateTextRangeList>) nsDOMTextEvent::GetInputRange()
 {
   if (mEvent->message == NS_TEXT_TEXT) {
     nsRefPtr<nsPrivateTextRangeList> textRange = mTextRange;
-    nsPrivateTextRangeList *textRangePtr = nullptr;
-    textRange.swap(textRangePtr);
-    return textRangePtr;
+    return textRange.forget();
   }
   return nullptr;
 }
 
 nsresult NS_NewDOMTextEvent(nsIDOMEvent** aInstancePtrResult,
                             mozilla::dom::EventTarget* aOwner,
                             nsPresContext* aPresContext,
                             nsTextEvent *aEvent)
--- a/content/events/src/nsDOMUIEvent.cpp
+++ b/content/events/src/nsDOMUIEvent.cpp
@@ -269,17 +269,17 @@ nsDOMUIEvent::GetRangeParent()
     nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(mEvent,
                                                               targetFrame);
     nsCOMPtr<nsIContent> parent = targetFrame->GetContentOffsetsFromPoint(pt).content;
     if (parent) {
       if (parent->ChromeOnlyAccess() &&
           !nsContentUtils::CanAccessNativeAnon()) {
         return nullptr;
       }
-      return parent.forget().get();
+      return parent.forget();
     }
   }
 
   return nullptr;
 }
 
 NS_IMETHODIMP
 nsDOMUIEvent::GetRangeParent(nsIDOMNode** aRangeParent)
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -4611,30 +4611,30 @@ nsEventStateManager::GetEventTargetConte
     return content.forget();
   }
 
   if (mCurrentTargetContent) {
     nsCOMPtr<nsIContent> content = mCurrentTargetContent;
     return content.forget();
   }
 
-  nsIContent *content = nullptr;
+  nsCOMPtr<nsIContent> content;
 
   nsIPresShell *presShell = mPresContext->GetPresShell();
   if (presShell) {
-    content = presShell->GetEventTargetContent(aEvent).get();
+    content = presShell->GetEventTargetContent(aEvent);
   }
 
   // Some events here may set mCurrentTarget but not set the corresponding
   // event target in the PresShell.
   if (!content && mCurrentTarget) {
-    mCurrentTarget->GetContentForEvent(aEvent, &content);
-  }
-
-  return content;
+    mCurrentTarget->GetContentForEvent(aEvent, getter_AddRefs(content));
+  }
+
+  return content.forget();
 }
 
 static Element*
 GetLabelTarget(nsIContent* aPossibleLabel)
 {
   mozilla::dom::HTMLLabelElement* label =
     mozilla::dom::HTMLLabelElement::FromContent(aPossibleLabel);
   if (!label)
--- a/content/events/src/nsPrivateTextRange.cpp
+++ b/content/events/src/nsPrivateTextRange.cpp
@@ -55,16 +55,11 @@ void nsPrivateTextRangeList::AppendTextR
 NS_METHOD_(uint16_t) nsPrivateTextRangeList::GetLength()
 {
   return static_cast<uint16_t>(mList.Length());
 }
 
 NS_METHOD_(already_AddRefed<nsIPrivateTextRange>) nsPrivateTextRangeList::Item(uint16_t aIndex)
 {
   nsRefPtr<nsPrivateTextRange> ret = mList.ElementAt(aIndex);
-  if (ret) {
-    nsPrivateTextRange *retPtr = nullptr;
-    ret.swap(retPtr);
-    return retPtr;
-  }
-  return nullptr;
+  return ret.forget();
 }
 
--- a/content/html/content/src/HTMLAnchorElement.cpp
+++ b/content/html/content/src/HTMLAnchorElement.cpp
@@ -334,20 +334,19 @@ nsLinkState
 HTMLAnchorElement::GetLinkState() const
 {
   return Link::GetLinkState();
 }
 
 already_AddRefed<nsIURI>
 HTMLAnchorElement::GetHrefURI() const
 {
-  nsIURI* uri = Link::GetCachedURI();
+  nsCOMPtr<nsIURI> uri = Link::GetCachedURI();
   if (uri) {
-    NS_ADDREF(uri);
-    return uri;
+    return uri.forget();
   }
 
   return GetHrefURIForAnchors();
 }
 
 nsresult
 HTMLAnchorElement::SetAttr(int32_t aNameSpaceID, nsIAtom* aName,
                            nsIAtom* aPrefix, const nsAString& aValue,
--- a/content/html/content/src/nsHTMLFormElement.cpp
+++ b/content/html/content/src/nsHTMLFormElement.cpp
@@ -1383,19 +1383,19 @@ nsHTMLFormElement::FindNamedItem(const n
 
   return htmlDoc->ResolveName(aName, this, aCache);
 }
 
 already_AddRefed<nsISupports>
 nsHTMLFormElement::DoResolveName(const nsAString& aName,
                                  bool aFlushContent)
 {
-  nsISupports *result;
-  NS_IF_ADDREF(result = mControls->NamedItemInternal(aName, aFlushContent));
-  return result;
+  nsCOMPtr<nsISupports> result =
+    mControls->NamedItemInternal(aName, aFlushContent);
+  return result.forget();
 }
 
 void
 nsHTMLFormElement::OnSubmitClickBegin(nsIContent* aOriginatingElement)
 {
   mDeferSubmission = true;
 
   // Prepare to run NotifySubmitObservers early before the
--- a/content/html/document/src/nsHTMLContentSink.cpp
+++ b/content/html/document/src/nsHTMLContentSink.cpp
@@ -490,20 +490,19 @@ CreateHTMLElement(uint32_t aNodeType, al
                aNodeType == eHTMLTag_userdefined,
                "aNodeType is out of bounds");
 
   contentCreatorCallback cb = sContentCreatorCallbacks[aNodeType];
 
   NS_ASSERTION(cb != NS_NewHTMLNOTUSEDElement,
                "Don't know how to construct tag element!");
 
-  nsGenericHTMLElement* result = cb(aNodeInfo, aFromParser);
-  NS_IF_ADDREF(result);
+  nsRefPtr<nsGenericHTMLElement> result = cb(aNodeInfo, aFromParser);
 
-  return result;
+  return result.forget();
 }
 
 //----------------------------------------------------------------------
 
 SinkContext::SinkContext(HTMLContentSink* aSink)
   : mSink(aSink),
     mNotifyLevel(0),
     mLastTextNodeSize(0),
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -1465,45 +1465,45 @@ nsHTMLDocument::Open(JSContext* cx,
     // a script-created parser, and the insertion point associated with that
     // parser's input stream is not undefined (that is, it does point to
     // somewhere in the input stream), then the method does nothing. Abort
     // these steps and return the Document object on which the method was
     // invoked."
     // Note that aborting a parser leaves the parser "active" with its
     // insertion point "not undefined". We track this using mParserAborted,
     // because aborting a parser nulls out mParser.
-    NS_ADDREF_THIS();
-    return this;
+    nsCOMPtr<nsIDocument> ret = this;
+    return ret.forget();
   }
 
   // No calling document.open() without a script global object
   if (!mScriptGlobalObject) {
-    NS_ADDREF_THIS();
-    return this;
+    nsCOMPtr<nsIDocument> ret = this;
+    return ret.forget();
   }
 
   nsPIDOMWindow* outer = GetWindow();
   if (!outer || (GetInnerWindow() != outer->GetCurrentInnerWindow())) {
-    NS_ADDREF_THIS();
-    return this;
+    nsCOMPtr<nsIDocument> ret = this;
+    return ret.forget();
   }
 
   // check whether we're in the middle of unload.  If so, ignore this call.
   nsCOMPtr<nsIDocShell> shell = do_QueryReferent(mDocumentContainer);
   if (!shell) {
     // We won't be able to create a parser anyway.
-    NS_ADDREF_THIS();
-    return this;
+    nsCOMPtr<nsIDocument> ret = this;
+    return ret.forget();
   }
 
   bool inUnload;
   shell->GetIsInUnload(&inUnload);
   if (inUnload) {
-    NS_ADDREF_THIS();
-    return this;
+    nsCOMPtr<nsIDocument> ret = this;
+    return ret.forget();
   }
 
   // Note: We want to use GetDocumentFromContext here because this document
   // should inherit the security information of the document that's opening us,
   // (since if it's secure, then it's presumably trusted).
   nsCOMPtr<nsIDocument> callerDoc = nsContentUtils::GetDocumentFromContext();
   if (!callerDoc) {
     // If we're called from C++ or in some other way without an originating
@@ -1558,18 +1558,18 @@ nsHTMLDocument::Open(JSContext* cx,
     nsCOMPtr<nsIContentViewer> cv;
     shell->GetContentViewer(getter_AddRefs(cv));
 
     if (cv) {
       bool okToUnload;
       if (NS_SUCCEEDED(cv->PermitUnload(false, &okToUnload)) && !okToUnload) {
         // We don't want to unload, so stop here, but don't throw an
         // exception.
-        NS_ADDREF_THIS();
-        return this;
+        nsCOMPtr<nsIDocument> ret = this;
+        return ret.forget();
       }
     }
 
     nsCOMPtr<nsIWebNavigation> webnav(do_QueryInterface(shell));
     webnav->Stop(nsIWebNavigation::STOP_NETWORK);
 
     // The Stop call may have cancelled the onload blocker request or prevented
     // it from getting added, so we need to make sure it gets added to the
--- a/content/media/webspeech/synth/SpeechSynthesisUtterance.cpp
+++ b/content/media/webspeech/synth/SpeechSynthesisUtterance.cpp
@@ -66,20 +66,20 @@ SpeechSynthesisUtterance::Constructor(Gl
 {
   nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(aGlobal.Get());
 
   if (!win) {
     aRv.Throw(NS_ERROR_FAILURE);
   }
 
   MOZ_ASSERT(win->IsInnerWindow());
-  SpeechSynthesisUtterance* object = new SpeechSynthesisUtterance(aText);
-  NS_ADDREF(object);
+  nsRefPtr<SpeechSynthesisUtterance> object =
+    new SpeechSynthesisUtterance(aText);
   object->BindToOwner(win);
-  return object;
+  return object.forget();
 }
 
 void
 SpeechSynthesisUtterance::GetText(nsString& aResult) const
 {
   aResult = mText;
 }
 
--- a/content/media/webspeech/synth/nsSynthVoiceRegistry.cpp
+++ b/content/media/webspeech/synth/nsSynthVoiceRegistry.cpp
@@ -511,36 +511,35 @@ nsSynthVoiceRegistry::SpeakUtterance(Spe
 {
   nsString lang = nsString(aUtterance.mLang.IsEmpty() ? aDocLang : aUtterance.mLang);
   nsAutoString uri;
 
   if (aUtterance.mVoice) {
     aUtterance.mVoice->GetVoiceURI(uri);
   }
 
-  nsSpeechTask* task;
+  nsRefPtr<nsSpeechTask> task;
   if (XRE_GetProcessType() == GeckoProcessType_Content) {
     task = new SpeechTaskChild(&aUtterance);
     SpeechSynthesisRequestChild* actor =
-      new SpeechSynthesisRequestChild(static_cast<SpeechTaskChild*>(task));
+      new SpeechSynthesisRequestChild(static_cast<SpeechTaskChild*>(task.get()));
     mSpeechSynthChild->SendPSpeechSynthesisRequestConstructor(actor,
                                                               aUtterance.mText,
                                                               lang,
                                                               uri,
                                                               aUtterance.Volume(),
                                                               aUtterance.Rate(),
                                                               aUtterance.Pitch());
   } else {
     task = new nsSpeechTask(&aUtterance);
     Speak(aUtterance.mText, lang, uri,
           aUtterance.Rate(), aUtterance.Pitch(), task);
   }
 
-  NS_IF_ADDREF(task);
-  return task;
+  return task.forget();
 }
 
 void
 nsSynthVoiceRegistry::Speak(const nsAString& aText,
                             const nsAString& aLang,
                             const nsAString& aUri,
                             const float& aRate,
                             const float& aPitch,
--- a/content/svg/content/src/SVGTests.cpp
+++ b/content/svg/content/src/SVGTests.cpp
@@ -29,35 +29,35 @@ SVGTests::SVGTests()
 }
 
 already_AddRefed<DOMSVGStringList>
 SVGTests::RequiredFeatures()
 {
   nsCOMPtr<nsIDOMSVGElement> elem = do_QueryInterface(this);
   nsSVGElement* element = static_cast<nsSVGElement*>(elem.get());
   return DOMSVGStringList::GetDOMWrapper(
-           &mStringListAttributes[FEATURES], element, true, FEATURES).get();
+           &mStringListAttributes[FEATURES], element, true, FEATURES);
 }
 
 already_AddRefed<DOMSVGStringList>
 SVGTests::RequiredExtensions()
 {
   nsCOMPtr<nsIDOMSVGElement> elem = do_QueryInterface(this);
   nsSVGElement* element = static_cast<nsSVGElement*>(elem.get());
   return DOMSVGStringList::GetDOMWrapper(
-           &mStringListAttributes[EXTENSIONS], element, true, EXTENSIONS).get();
+           &mStringListAttributes[EXTENSIONS], element, true, EXTENSIONS);
 }
 
 already_AddRefed<DOMSVGStringList>
 SVGTests::SystemLanguage()
 {
   nsCOMPtr<nsIDOMSVGElement> elem = do_QueryInterface(this);
   nsSVGElement* element = static_cast<nsSVGElement*>(elem.get());
   return DOMSVGStringList::GetDOMWrapper(
-           &mStringListAttributes[LANGUAGE], element, true, LANGUAGE).get();
+           &mStringListAttributes[LANGUAGE], element, true, LANGUAGE);
 }
 
 bool
 SVGTests::HasExtension(const nsAString& aExtension)
 {
   return nsSVGFeatures::HasExtension(aExtension);
 }
 
--- a/content/svg/content/src/SVGTransformableElement.cpp
+++ b/content/svg/content/src/SVGTransformableElement.cpp
@@ -19,17 +19,17 @@ namespace mozilla {
 namespace dom {
 
 already_AddRefed<SVGAnimatedTransformList>
 SVGTransformableElement::Transform()
 {
   // We're creating a DOM wrapper, so we must tell GetAnimatedTransformList
   // to allocate the SVGAnimatedTransformList if it hasn't already done so:
   return SVGAnimatedTransformList::GetDOMWrapper(
-           GetAnimatedTransformList(DO_ALLOCATE), this).get();
+           GetAnimatedTransformList(DO_ALLOCATE), this);
 
 }
 
 //----------------------------------------------------------------------
 // nsIContent methods
 
 NS_IMETHODIMP_(bool)
 SVGTransformableElement::IsAttributeMapped(const nsIAtom* name) const
--- a/content/xbl/src/nsXBLPrototypeBinding.cpp
+++ b/content/xbl/src/nsXBLPrototypeBinding.cpp
@@ -312,19 +312,18 @@ nsXBLPrototypeBinding::SetBasePrototype(
   }
 
   mBaseBinding = aBinding;
 }
 
 already_AddRefed<nsIContent>
 nsXBLPrototypeBinding::GetBindingElement()
 {
-  nsIContent* result = mBinding;
-  NS_IF_ADDREF(result);
-  return result;
+  nsCOMPtr<nsIContent> result = mBinding;
+  return result.forget();
 }
 
 void
 nsXBLPrototypeBinding::SetBindingElement(nsIContent* aElement)
 {
   mBinding = aElement;
   if (mBinding->AttrValueIs(kNameSpaceID_None, nsGkAtoms::inheritstyle,
                             nsGkAtoms::_false, eCaseMatters))
--- a/content/xbl/src/nsXBLPrototypeHandler.cpp
+++ b/content/xbl/src/nsXBLPrototypeHandler.cpp
@@ -133,19 +133,17 @@ nsXBLPrototypeHandler::~nsXBLPrototypeHa
   NS_CONTENT_DELETE_LIST_MEMBER(nsXBLPrototypeHandler, this, mNextHandler);
 }
 
 already_AddRefed<nsIContent>
 nsXBLPrototypeHandler::GetHandlerElement()
 {
   if (mType & NS_HANDLER_TYPE_XUL) {
     nsCOMPtr<nsIContent> element = do_QueryReferent(mHandlerElement);
-    nsIContent* el = nullptr;
-    element.swap(el);
-    return el;
+    return element.forget();
   }
 
   return nullptr;
 }
 
 void
 nsXBLPrototypeHandler::AppendHandlerText(const nsAString& aText) 
 {
@@ -569,19 +567,18 @@ nsXBLPrototypeHandler::DispatchXULKeyCom
                                      nullptr, nullptr,
                                      isControl, isAlt, isShift, isMeta);
   return NS_OK;
 }
 
 already_AddRefed<nsIAtom>
 nsXBLPrototypeHandler::GetEventName()
 {
-  nsIAtom* eventName = mEventName;
-  NS_IF_ADDREF(eventName);
-  return eventName;
+  nsCOMPtr<nsIAtom> eventName = mEventName;
+  return eventName.forget();
 }
 
 already_AddRefed<nsIController>
 nsXBLPrototypeHandler::GetController(EventTarget* aTarget)
 {
   // XXX Fix this so there's a generic interface that describes controllers,
   // This code should have no special knowledge of what objects might have controllers.
   nsCOMPtr<nsIControllers> controllers;
@@ -606,23 +603,22 @@ nsXBLPrototypeHandler::GetController(Eve
     nsCOMPtr<nsIDOMWindow> domWindow(do_QueryInterface(aTarget));
     if (domWindow)
       domWindow->GetControllers(getter_AddRefs(controllers));
   }
 
   // Return the first controller.
   // XXX This code should be checking the command name and using supportscommand and
   // iscommandenabled.
-  nsIController* controller;
+  nsCOMPtr<nsIController> controller;
   if (controllers) {
-    controllers->GetControllerAt(0, &controller);  // return reference
+    controllers->GetControllerAt(0, getter_AddRefs(controller));
   }
-  else controller = nullptr;
 
-  return controller;
+  return controller.forget();
 }
 
 bool
 nsXBLPrototypeHandler::KeyEventMatched(nsIDOMKeyEvent* aKeyEvent,
                                        uint32_t aCharCode,
                                        bool aIgnoreShiftKey)
 {
   if (mDetail != -1) {
--- a/content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
+++ b/content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
@@ -341,38 +341,35 @@ already_AddRefed<nsIAtom>
 txXPathNodeUtils::getLocalName(const txXPathNode& aNode)
 {
     if (aNode.isDocument()) {
         return nullptr;
     }
 
     if (aNode.isContent()) {
         if (aNode.mNode->IsElement()) {
-            nsIAtom* localName = aNode.Content()->Tag();
-            NS_ADDREF(localName);
-
-            return localName;
+            nsCOMPtr<nsIAtom> localName = aNode.Content()->Tag();
+            return localName.forget();
         }
 
         if (aNode.mNode->IsNodeOfType(nsINode::ePROCESSING_INSTRUCTION)) {
             nsCOMPtr<nsIDOMNode> node = do_QueryInterface(aNode.mNode);
             nsAutoString target;
             node->GetNodeName(target);
 
             return NS_NewAtom(target);
         }
 
         return nullptr;
     }
 
-    nsIAtom* localName = aNode.Content()->
+    nsCOMPtr<nsIAtom> localName = aNode.Content()->
         GetAttrNameAt(aNode.mIndex)->LocalName();
-    NS_ADDREF(localName);
 
-    return localName;
+    return localName.forget();
 }
 
 nsIAtom*
 txXPathNodeUtils::getPrefix(const txXPathNode& aNode)
 {
     if (aNode.isDocument()) {
         return nullptr;
     }
--- a/content/xul/content/src/nsXULElement.cpp
+++ b/content/xul/content/src/nsXULElement.cpp
@@ -220,20 +220,18 @@ nsXULElement::MaybeUpdatePrivateLifetime
 }
 
 /* static */
 already_AddRefed<nsXULElement>
 nsXULElement::Create(nsXULPrototypeElement* aPrototype, nsINodeInfo *aNodeInfo,
                      bool aIsScriptable, bool aIsRoot)
 {
     nsCOMPtr<nsINodeInfo> ni = aNodeInfo;
-    nsXULElement *element = new nsXULElement(ni.forget());
+    nsRefPtr<nsXULElement> element = new nsXULElement(ni.forget());
     if (element) {
-        NS_ADDREF(element);
-
         if (aPrototype->mHasIdAttribute) {
             element->SetHasID();
         }
         if (aPrototype->mHasClassAttribute) {
             element->SetFlags(NODE_MAY_HAVE_CLASS);
         }
         if (aPrototype->mHasStyleAttribute) {
             element->SetMayHaveStyle();
@@ -254,17 +252,17 @@ nsXULElement::Create(nsXULPrototypeEleme
             for (uint32_t i = 0; i < aPrototype->mNumAttributes; ++i) {
                 if (aPrototype->mAttributes[i].mName.Equals(nsGkAtoms::windowtype)) {
                     element->MaybeUpdatePrivateLifetime();
                 }
             }
         }
     }
 
-    return element;
+    return element.forget();
 }
 
 nsresult
 nsXULElement::Create(nsXULPrototypeElement* aPrototype,
                      nsIDocument* aDocument,
                      bool aIsScriptable,
                      bool aIsRoot,
                      Element** aResult)
@@ -1469,19 +1467,18 @@ nsXULElement::GetFrameLoader(nsIFrameLoa
 
 already_AddRefed<nsFrameLoader>
 nsXULElement::GetFrameLoader()
 {
     nsXULSlots* slots = static_cast<nsXULSlots*>(GetExistingSlots());
     if (!slots)
         return nullptr;
 
-    nsFrameLoader* loader = slots->mFrameLoader;
-    NS_IF_ADDREF(loader);
-    return loader;
+    nsRefPtr<nsFrameLoader> loader = slots->mFrameLoader;
+    return loader.forget();
 }
 
 nsresult
 nsXULElement::SwapFrameLoaders(nsIFrameLoaderOwner* aOtherOwner)
 {
     nsCOMPtr<nsIContent> otherContent(do_QueryInterface(aOtherOwner));
     NS_ENSURE_TRUE(otherContent, NS_ERROR_NOT_IMPLEMENTED);
 
--- a/content/xul/content/src/nsXULPopupListener.cpp
+++ b/content/xul/content/src/nsXULPopupListener.cpp
@@ -295,18 +295,18 @@ nsXULPopupListener::ClosePopup()
 
 static already_AddRefed<nsIContent>
 GetImmediateChild(nsIContent* aContent, nsIAtom *aTag) 
 {
   for (nsIContent* child = aContent->GetFirstChild();
        child;
        child = child->GetNextSibling()) {
     if (child->Tag() == aTag) {
-      NS_ADDREF(child);
-      return child;
+      nsCOMPtr<nsIContent> ret = child;
+      return ret.forget();
     }
   }
 
   return nullptr;
 }
 
 //
 // LaunchPopup
--- a/content/xul/document/src/XULDocument.cpp
+++ b/content/xul/document/src/XULDocument.cpp
@@ -1244,26 +1244,25 @@ XULDocument::GetElementsByAttribute(cons
 }
 
 already_AddRefed<nsINodeList>
 XULDocument::GetElementsByAttribute(const nsAString& aAttribute,
                                     const nsAString& aValue)
 {
     nsCOMPtr<nsIAtom> attrAtom(do_GetAtom(aAttribute));
     void* attrValue = new nsString(aValue);
-    nsContentList *list = new nsContentList(this,
+    nsRefPtr<nsContentList> list = new nsContentList(this,
                                             MatchAttribute,
                                             nsContentUtils::DestroyMatchString,
                                             attrValue,
                                             true,
                                             attrAtom,
                                             kNameSpaceID_Unknown);
     
-    NS_ADDREF(list);
-    return list;
+    return list.forget();
 }
 
 NS_IMETHODIMP
 XULDocument::GetElementsByAttributeNS(const nsAString& aNamespaceURI,
                                       const nsAString& aAttribute,
                                       const nsAString& aValue,
                                       nsIDOMNodeList** aReturn)
 {
@@ -1288,25 +1287,24 @@ XULDocument::GetElementsByAttributeNS(co
         nsContentUtils::NameSpaceManager()->RegisterNameSpace(aNamespaceURI,
                                                               nameSpaceId);
       if (NS_FAILED(rv)) {
           aRv.Throw(rv);
           return nullptr;
       }
     }
 
-    nsContentList *list = new nsContentList(this,
+    nsRefPtr<nsContentList> list = new nsContentList(this,
                                             MatchAttribute,
                                             nsContentUtils::DestroyMatchString,
                                             attrValue,
                                             true,
                                             attrAtom,
                                             nameSpaceId);
-    NS_ADDREF(list);
-    return list;
+    return list.forget();
 }
 
 NS_IMETHODIMP
 XULDocument::Persist(const nsAString& aID,
                      const nsAString& aAttr)
 {
     // If we're currently reading persisted attributes out of the
     // localstore, _don't_ re-enter and try to set them again!
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -4823,28 +4823,26 @@ nsGlobalWindow::RefreshCompartmentPrinci
   JS_SetCompartmentPrincipals(js::GetObjectCompartment(mJSObject),
                               nsJSPrincipals::get(mDoc->NodePrincipal()));
 }
 
 static already_AddRefed<nsIDocShellTreeItem>
 GetCallerDocShellTreeItem()
 {
   JSContext *cx = nsContentUtils::GetCurrentJSContext();
-  nsIDocShellTreeItem *callerItem = nullptr;
+  nsCOMPtr<nsIDocShellTreeItem> callerItem;
 
   if (cx) {
     nsCOMPtr<nsIWebNavigation> callerWebNav =
       do_GetInterface(nsJSUtils::GetDynamicScriptGlobal(cx));
 
-    if (callerWebNav) {
-      CallQueryInterface(callerWebNav, &callerItem);
-    }
-  }
-
-  return callerItem;
+    callerItem = do_QueryInterface(callerWebNav);
+  }
+
+  return callerItem.forget();
 }
 
 bool
 nsGlobalWindow::WindowExists(const nsAString& aName,
                              bool aLookForCallerOnJSStack)
 {
   NS_PRECONDITION(IsOuterWindow(), "Must be outer window");
   NS_PRECONDITION(mDocShell, "Must have docshell");
@@ -4864,23 +4862,23 @@ nsGlobalWindow::WindowExists(const nsASt
   return namedItem != nullptr;
 }
 
 already_AddRefed<nsIWidget>
 nsGlobalWindow::GetMainWidget()
 {
   nsCOMPtr<nsIBaseWindow> treeOwnerAsWin = GetTreeOwnerWindow();
 
-  nsIWidget *widget = nullptr;
+  nsCOMPtr<nsIWidget> widget;
 
   if (treeOwnerAsWin) {
-    treeOwnerAsWin->GetMainWidget(&widget);
-  }
-
-  return widget;
+    treeOwnerAsWin->GetMainWidget(getter_AddRefs(widget));
+  }
+
+  return widget.forget();
 }
 
 nsIWidget*
 nsGlobalWindow::GetNearestWidget()
 {
   nsIDocShell* docShell = GetDocShell();
   NS_ENSURE_TRUE(docShell, nullptr);
   nsCOMPtr<nsIPresShell> presShell = docShell->GetPresShell();
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -674,23 +674,19 @@ static already_AddRefed<nsIPrompt>
 GetPromptFromContext(nsJSContext* ctx)
 {
   nsCOMPtr<nsPIDOMWindow> win(do_QueryInterface(ctx->GetGlobalObject()));
   NS_ENSURE_TRUE(win, nullptr);
 
   nsIDocShell *docShell = win->GetDocShell();
   NS_ENSURE_TRUE(docShell, nullptr);
 
-  nsCOMPtr<nsIInterfaceRequestor> ireq(do_QueryInterface(docShell));
-  NS_ENSURE_TRUE(ireq, nullptr);
-
   // Get the nsIPrompt interface from the docshell
-  nsIPrompt* prompt;
-  ireq->GetInterface(NS_GET_IID(nsIPrompt), (void**)&prompt);
-  return prompt;
+  nsCOMPtr<nsIPrompt> prompt = do_GetInterface(docShell);
+  return prompt.forget();
 }
 
 JSBool
 nsJSContext::DOMOperationCallback(JSContext *cx)
 {
   nsresult rv;
 
   // Get the native context
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -349,20 +349,19 @@ nsNPAPIPluginInstance::GetDOMWindow()
 
   nsRefPtr<nsPluginInstanceOwner> deathGrip(mOwner);
 
   nsCOMPtr<nsIDocument> doc;
   mOwner->GetDocument(getter_AddRefs(doc));
   if (!doc)
     return nullptr;
 
-  nsPIDOMWindow *window = doc->GetWindow();
-  NS_IF_ADDREF(window);
+  nsRefPtr<nsPIDOMWindow> window = doc->GetWindow();
 
-  return window;
+  return window.forget();
 }
 
 nsresult
 nsNPAPIPluginInstance::GetTagType(nsPluginTagType *result)
 {
   if (!mOwner) {
     return NS_ERROR_FAILURE;
   }
--- a/dom/plugins/base/nsPluginHost.cpp
+++ b/dom/plugins/base/nsPluginHost.cpp
@@ -331,18 +331,18 @@ nsPluginHost::GetInst()
 {
   if (!sInst) {
     sInst = new nsPluginHost();
     if (!sInst)
       return nullptr;
     NS_ADDREF(sInst);
   }
 
-  NS_ADDREF(sInst);
-  return sInst;
+  nsRefPtr<nsPluginHost> inst = sInst;
+  return inst.forget();
 }
 
 bool nsPluginHost::IsRunningPlugin(nsPluginTag * aPluginTag)
 {
   if (!aPluginTag || !aPluginTag->mPlugin) {
     return false;
   }
 
--- a/editor/composer/src/nsComposerCommandsUpdater.cpp
+++ b/editor/composer/src/nsComposerCommandsUpdater.cpp
@@ -357,19 +357,17 @@ nsComposerCommandsUpdater::SelectionIsCo
 
 already_AddRefed<nsPICommandUpdater>
 nsComposerCommandsUpdater::GetCommandUpdater()
 {
   nsCOMPtr<nsIDocShell> docShell = do_QueryReferent(mDocShell);
   NS_ENSURE_TRUE(docShell, nullptr);
   nsCOMPtr<nsICommandManager> manager = do_GetInterface(docShell);
   nsCOMPtr<nsPICommandUpdater> updater = do_QueryInterface(manager);
-  nsPICommandUpdater* retVal = nullptr;
-  updater.swap(retVal);
-  return retVal;
+  return updater.forget();
 }
 
 #if 0
 #pragma mark -
 #endif
 
 nsresult
 nsComposerCommandsUpdater::Notify(nsITimer *timer)
--- a/editor/txmgr/src/nsTransactionStack.cpp
+++ b/editor/txmgr/src/nsTransactionStack.cpp
@@ -52,34 +52,33 @@ nsTransactionStack::PopBottom()
    * the front of the deque.
    */
   return static_cast<nsTransactionItem*> (mQue.PopFront());
 }
 
 already_AddRefed<nsTransactionItem>
 nsTransactionStack::Peek()
 {
-  nsTransactionItem* transaction = nullptr;
+  nsRefPtr<nsTransactionItem> transaction;
   if (mQue.GetSize()) {
-    NS_IF_ADDREF(transaction = static_cast<nsTransactionItem*>(mQue.Last()));
+    transaction = static_cast<nsTransactionItem*>(mQue.Last());
   }
 
-  return transaction;
+  return transaction.forget();
 }
 
 already_AddRefed<nsTransactionItem>
 nsTransactionStack::GetItem(int32_t aIndex)
 {
-  nsTransactionItem* transaction = nullptr;
+  nsRefPtr<nsTransactionItem> transaction;
   if (aIndex >= 0 && aIndex < mQue.GetSize()) {
-    NS_IF_ADDREF(transaction =
-                 static_cast<nsTransactionItem*>(mQue.ObjectAt(aIndex)));
+    transaction = static_cast<nsTransactionItem*>(mQue.ObjectAt(aIndex));
   }
 
-  return transaction;
+  return transaction.forget();
 }
 
 void
 nsTransactionStack::Clear()
 {
   nsRefPtr<nsTransactionItem> tx;
 
   do {
--- a/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
+++ b/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
@@ -1713,32 +1713,30 @@ nsWindowWatcher::FindItemWithName(const 
 
   return rv;
 }
 
 already_AddRefed<nsIDocShellTreeItem>
 nsWindowWatcher::GetCallerTreeItem(nsIDocShellTreeItem* aParentItem)
 {
   JSContext *cx = nsContentUtils::GetCurrentJSContext();
-  nsIDocShellTreeItem* callerItem = nullptr;
+  nsCOMPtr<nsIDocShellTreeItem> callerItem;
 
   if (cx) {
     nsCOMPtr<nsIWebNavigation> callerWebNav =
       do_GetInterface(nsJSUtils::GetDynamicScriptGlobal(cx));
 
-    if (callerWebNav) {
-      CallQueryInterface(callerWebNav, &callerItem);
-    }
+    callerItem = do_QueryInterface(callerWebNav);
   }
 
   if (!callerItem) {
-    NS_IF_ADDREF(callerItem = aParentItem);
+    callerItem = aParentItem;
   }
 
-  return callerItem;
+  return callerItem.forget();
 }
 
 nsresult
 nsWindowWatcher::SafeGetWindowByName(const nsAString& aName,
                                      nsIDOMWindow* aCurrentWindow,
                                      nsIDOMWindow** aResult)
 {
   *aResult = nullptr;
--- a/gfx/layers/ImageContainer.cpp
+++ b/gfx/layers/ImageContainer.cpp
@@ -525,17 +525,17 @@ PlanarYCbCrImage::GetAsSurface()
     new gfxImageSurface(mSize, format);
 
   gfxUtils::ConvertYCbCrToRGB(mData, format, mSize,
                               imageSurface->Data(),
                               imageSurface->Stride());
 
   mSurface = imageSurface;
 
-  return imageSurface.forget().get();
+  return imageSurface.forget();
 }
 
 already_AddRefed<gfxASurface>
 RemoteBitmapImage::GetAsSurface()
 {
   nsRefPtr<gfxImageSurface> newSurf =
     new gfxImageSurface(mSize,
     mFormat == RemoteImageData::BGRX32 ? gfxASurface::ImageFormatRGB24 : gfxASurface::ImageFormatARGB32);
--- a/gfx/layers/opengl/ImageLayerOGL.cpp
+++ b/gfx/layers/opengl/ImageLayerOGL.cpp
@@ -92,20 +92,19 @@ GLTexture::Release()
     }
   }
 
   if (mTexture) {
     if (mContext->IsOwningThreadCurrent() || mContext->IsGlobalSharedContext()) {
       mContext->MakeCurrent();
       mContext->fDeleteTextures(1, &mTexture);
     } else {
-      nsCOMPtr<nsIRunnable> runnable =
-        new TextureDeleter(mContext.get(), mTexture);
-      mContext->DispatchToOwningThread(runnable);
-      mContext.forget();
+      already_AddRefed<GLContext> context = mContext.forget();
+      nsCOMPtr<nsIRunnable> runnable = new TextureDeleter(context, mTexture);
+      context.get()->DispatchToOwningThread(runnable);
     }
 
     mTexture = 0;
   }
 
   mContext = nullptr;
 }
 
--- a/gfx/thebes/gfxASurface.cpp
+++ b/gfx/thebes/gfxASurface.cpp
@@ -121,24 +121,23 @@ gfxASurface::SetSurfaceWrapper(cairo_sur
     if (!csurf)
         return;
     cairo_surface_set_user_data(csurf, &gfxasurface_pointer_key, asurf, SurfaceDestroyFunc);
 }
 
 already_AddRefed<gfxASurface>
 gfxASurface::Wrap (cairo_surface_t *csurf)
 {
-    gfxASurface *result;
+    nsRefPtr<gfxASurface> result;
 
     /* Do we already have a wrapper for this surface? */
     result = GetSurfaceWrapper(csurf);
     if (result) {
         // fprintf(stderr, "Existing wrapper for %p -> %p\n", csurf, result);
-        NS_ADDREF(result);
-        return result;
+        return result.forget();
     }
 
     /* No wrapper; figure out the surface type and create it */
     cairo_surface_type_t stype = cairo_surface_get_type(csurf);
 
     if (stype == CAIRO_SURFACE_TYPE_IMAGE) {
         result = new gfxImageSurface(csurf);
     }
@@ -172,18 +171,17 @@ gfxASurface::Wrap (cairo_surface_t *csur
     }
 #endif
     else {
         result = new gfxUnknownSurface(csurf);
     }
 
     // fprintf(stderr, "New wrapper for %p -> %p\n", csurf, result);
 
-    NS_ADDREF(result);
-    return result;
+    return result.forget();
 }
 
 void
 gfxASurface::Init(cairo_surface_t* surface, bool existingSurface)
 {
     SetSurfaceWrapper(surface, this);
 
     mSurface = surface;
--- a/gfx/thebes/gfxContext.cpp
+++ b/gfx/thebes/gfxContext.cpp
@@ -143,19 +143,18 @@ gfxContext::OriginalSurface()
 already_AddRefed<gfxASurface>
 gfxContext::CurrentSurface(gfxFloat *dx, gfxFloat *dy)
 {
   if (mCairo) {
     cairo_surface_t *s = cairo_get_group_target(mCairo);
     if (s == mSurface->CairoSurface()) {
         if (dx && dy)
             cairo_surface_get_device_offset(s, dx, dy);
-        gfxASurface *ret = mSurface;
-        NS_ADDREF(ret);
-        return ret;
+        nsRefPtr<gfxASurface> ret = mSurface;
+        return ret.forget();
     }
 
     if (dx && dy)
         cairo_surface_get_device_offset(s, dx, dy);
     return gfxASurface::Wrap(s);
   } else {
     if (dx && dy) {
       *dx = *dy = 0;
@@ -1369,24 +1368,23 @@ gfxContext::SetPattern(gfxPattern *patte
 
 already_AddRefed<gfxPattern>
 gfxContext::GetPattern()
 {
   if (mCairo) {
     cairo_pattern_t *pat = cairo_get_source(mCairo);
     NS_ASSERTION(pat, "I was told this couldn't be null");
 
-    gfxPattern *wrapper = nullptr;
+    nsRefPtr<gfxPattern> wrapper;
     if (pat)
         wrapper = new gfxPattern(pat);
     else
         wrapper = new gfxPattern(gfxRGBA(0,0,0,0));
 
-    NS_IF_ADDREF(wrapper);
-    return wrapper;
+    return wrapper.forget();
   } else {
     nsRefPtr<gfxPattern> pat;
     
     AzureState &state = CurrentState();
     if (state.pattern) {
       pat = state.pattern;
     } else if (state.sourceSurface) {
       NS_ASSERTION(false, "Ugh, this isn't good.");
@@ -1552,20 +1550,19 @@ gfxContext::PushGroupAndCopyBackground(g
   PushGroup(content);
 }
 
 already_AddRefed<gfxPattern>
 gfxContext::PopGroup()
 {
   if (mCairo) {
     cairo_pattern_t *pat = cairo_pop_group(mCairo);
-    gfxPattern *wrapper = new gfxPattern(pat);
+    nsRefPtr<gfxPattern> wrapper = new gfxPattern(pat);
     cairo_pattern_destroy(pat);
-    NS_IF_ADDREF(wrapper);
-    return wrapper;
+    return wrapper.forget();
   } else {
     RefPtr<SourceSurface> src = mDT->Snapshot();
     Point deviceOffset = CurrentState().deviceOffset;
 
     Restore();
 
     Matrix mat = mTransform;
     mat.Invert();
@@ -1659,20 +1656,19 @@ gfxContext::GetUserStrokeExtent()
     return ThebesRect(mPath->GetStrokedBounds(CurrentState().strokeOptions, mTransform));
   }
 }
 
 already_AddRefed<gfxFlattenedPath>
 gfxContext::GetFlattenedPath()
 {
   if (mCairo) {
-    gfxFlattenedPath *path =
+    nsRefPtr<gfxFlattenedPath> path =
         new gfxFlattenedPath(cairo_copy_path_flat(mCairo));
-    NS_IF_ADDREF(path);
-    return path;
+    return path.forget();
   } else {
     // XXX - Used by SVG, needs fixing.
     return NULL;
   }
 }
 
 bool
 gfxContext::HasError()
--- a/gfx/thebes/gfxFont.cpp
+++ b/gfx/thebes/gfxFont.cpp
@@ -197,19 +197,17 @@ gfxFontEntry::FindOrMakeFont(const gfxFo
             return nullptr;
         if (!newFont->Valid()) {
             delete newFont;
             return nullptr;
         }
         font = newFont;
         gfxFontCache::GetCache()->AddNew(font);
     }
-    gfxFont *f = nullptr;
-    font.swap(f);
-    return f;
+    return font.forget();
 }
 
 bool
 gfxFontEntry::HasSVGGlyph(uint32_t aGlyphId)
 {
     NS_ASSERTION(mSVGInitialized, "SVG data has not yet been loaded. TryGetSVGData() first.");
     return mSVGGlyphs->HasSVGGlyph(aGlyphId);
 }
@@ -1250,19 +1248,18 @@ gfxFontCache::Lookup(const gfxFontEntry 
 {
     Key key(aFontEntry, aStyle);
     HashEntry *entry = mFonts.GetEntry(key);
 
     Telemetry::Accumulate(Telemetry::FONT_CACHE_HIT, entry != nullptr);
     if (!entry)
         return nullptr;
 
-    gfxFont *font = entry->mFont;
-    NS_ADDREF(font);
-    return font;
+    nsRefPtr<gfxFont> font = entry->mFont;
+    return font.forget();
 }
 
 void
 gfxFontCache::AddNew(gfxFont *aFont)
 {
     Key key(aFont->GetFontEntry(), aFont->GetStyle());
     HashEntry *entry = mFonts.PutEntry(key);
     if (!entry)
@@ -4390,21 +4387,20 @@ gfxFontGroup::FindFontForChar(uint32_t a
     // To optimize common cases, try the first font in the font-group
     // before going into the more detailed checks below
     uint32_t nextIndex = 0;
     bool isJoinControl = gfxFontUtils::IsJoinControl(aCh);
     bool wasJoinCauser = gfxFontUtils::IsJoinCauser(aPrevCh);
     bool isVarSelector = gfxFontUtils::IsVarSelector(aCh);
 
     if (!isJoinControl && !wasJoinCauser && !isVarSelector) {
-        gfxFont *firstFont = mFonts[0].Font();
+        nsRefPtr<gfxFont> firstFont = mFonts[0].Font();
         if (firstFont->HasCharacter(aCh)) {
             *aMatchType = gfxTextRange::kFontGroup;
-            firstFont->AddRef();
-            return firstFont;
+            return firstFont.forget();
         }
         // It's possible that another font in the family (e.g. regular face,
         // where the requested style was italic) will support the character
         nsRefPtr<gfxFont> font = TryAllFamilyMembers(mFonts[0].Family(), aCh);
         if (font) {
             *aMatchType = gfxTextRange::kFontGroup;
             return font.forget();
         }
@@ -4413,37 +4409,37 @@ gfxFontGroup::FindFontForChar(uint32_t a
     }
 
     if (aPrevMatchedFont) {
         // Don't switch fonts for control characters, regardless of
         // whether they are present in the current font, as they won't
         // actually be rendered (see bug 716229)
         uint8_t category = GetGeneralCategory(aCh);
         if (category == HB_UNICODE_GENERAL_CATEGORY_CONTROL) {
-            aPrevMatchedFont->AddRef();
-            return aPrevMatchedFont;
+            nsRefPtr<gfxFont> ret = aPrevMatchedFont;
+            return ret.forget();
         }
 
         // if this character is a join-control or the previous is a join-causer,
         // use the same font as the previous range if we can
         if (isJoinControl || wasJoinCauser) {
             if (aPrevMatchedFont->HasCharacter(aCh)) {
-                aPrevMatchedFont->AddRef();
-                return aPrevMatchedFont;
+                nsRefPtr<gfxFont> ret = aPrevMatchedFont;
+                return ret.forget();
             }
         }
     }
 
     // if this character is a variation selector,
     // use the previous font regardless of whether it supports VS or not.
     // otherwise the text run will be divided.
     if (isVarSelector) {
         if (aPrevMatchedFont) {
-            aPrevMatchedFont->AddRef();
-            return aPrevMatchedFont;
+            nsRefPtr<gfxFont> ret = aPrevMatchedFont;
+            return ret.forget();
         }
         // VS alone. it's meaningless to search different fonts
         return nullptr;
     }
 
     // 1. check remaining fonts in the font group
     uint32_t fontListLength = FontListLength();
     for (uint32_t i = nextIndex; i < fontListLength; i++) {
@@ -4470,18 +4466,18 @@ gfxFontGroup::FindFontForChar(uint32_t a
         *aMatchType = gfxTextRange::kPrefsFallback;
         return font.forget();
     }
 
     // 3. use fallback fonts
     // -- before searching for something else check the font used for the previous character
     if (aPrevMatchedFont && aPrevMatchedFont->HasCharacter(aCh)) {
         *aMatchType = gfxTextRange::kSystemFallback;
-        aPrevMatchedFont->AddRef();
-        return aPrevMatchedFont;
+        nsRefPtr<gfxFont> ret = aPrevMatchedFont;
+        return ret.forget();
     }
 
     // never fall back for characters from unknown scripts
     if (aRunScript == HB_SCRIPT_UNKNOWN) {
         return nullptr;
     }
 
     // for known "space" characters, don't do a full system-fallback search;
@@ -4632,28 +4628,27 @@ struct PrefFontCallbackData {
         }
         return true;
     }
 };
 
 already_AddRefed<gfxFont>
 gfxFontGroup::WhichPrefFontSupportsChar(uint32_t aCh)
 {
-    gfxFont *font;
+    nsRefPtr<gfxFont> font;
 
     // get the pref font list if it hasn't been set up already
     uint32_t unicodeRange = FindCharUnicodeRange(aCh);
     eFontPrefLang charLang = gfxPlatform::GetPlatform()->GetFontPrefLangFor(unicodeRange);
 
     // if the last pref font was the first family in the pref list, no need to recheck through a list of families
     if (mLastPrefFont && charLang == mLastPrefLang &&
         mLastPrefFirstFont && mLastPrefFont->HasCharacter(aCh)) {
         font = mLastPrefFont;
-        NS_ADDREF(font);
-        return font;
+        return font.forget();
     }
 
     // based on char lang and page lang, set up list of pref lang fonts to check
     eFontPrefLang prefLangs[kMaxLenPrefLangList];
     uint32_t i, numLangs = 0;
 
     gfxPlatform::GetPlatform()->GetLangPrefs(prefLangs, numLangs, charLang, mPageLang);
 
@@ -4681,18 +4676,17 @@ gfxFontGroup::WhichPrefFontSupportsChar(
             if (!family) continue;
 
             // if a pref font is used, it's likely to be used again in the same text run.
             // the style doesn't change so the face lookup can be cached rather than calling
             // FindOrMakeFont repeatedly.  speeds up FindFontForChar lookup times for subsequent
             // pref font lookups
             if (family == mLastPrefFamily && mLastPrefFont->HasCharacter(aCh)) {
                 font = mLastPrefFont;
-                NS_ADDREF(font);
-                return font;
+                return font.forget();
             }
 
             bool needsBold;
             gfxFontEntry *fe = family->FindFontForStyle(mStyle, needsBold);
             // if ch in cmap, create and return a gfxFont
             if (fe && fe->TestCharacterMap(aCh)) {
                 nsRefPtr<gfxFont> prefFont = fe->FindOrMakeFont(&mStyle, needsBold);
                 if (!prefFont) continue;
--- a/gfx/thebes/gfxImageSurface.cpp
+++ b/gfx/thebes/gfxImageSurface.cpp
@@ -278,17 +278,17 @@ gfxImageSurface::GetSubimage(const gfxRe
     unsigned char* subData = Data() +
         (Stride() * (int)r.Y()) +
         (int)r.X() * gfxASurface::BytePerPixelFromFormat(Format());
 
     nsRefPtr<gfxSubimageSurface> image =
         new gfxSubimageSurface(this, subData,
                                gfxIntSize((int)r.Width(), (int)r.Height()));
 
-    return image.forget().get();
+    return image.forget();
 }
 
 gfxSubimageSurface::gfxSubimageSurface(gfxImageSurface* aParent,
                                        unsigned char* aData,
                                        const gfxIntSize& aSize)
   : gfxImageSurface(aData, aSize, aParent->Stride(), aParent->Format())
   , mParent(aParent)
 {
--- a/gfx/thebes/gfxPlatform.cpp
+++ b/gfx/thebes/gfxPlatform.cpp
@@ -508,19 +508,17 @@ gfxPlatform::OptimizeImage(gfxImageSurfa
     if (!optSurface || optSurface->CairoStatus() != 0)
         return nullptr;
 
     gfxContext tmpCtx(optSurface);
     tmpCtx.SetOperator(gfxContext::OPERATOR_SOURCE);
     tmpCtx.SetSource(aSurface);
     tmpCtx.Paint();
 
-    gfxASurface *ret = optSurface;
-    NS_ADDREF(ret);
-    return ret;
+    return optSurface.forget();
 }
 
 cairo_user_data_key_t kDrawTarget;
 
 RefPtr<DrawTarget>
 gfxPlatform::CreateDrawTargetForSurface(gfxASurface *aSurface, const IntSize& aSize)
 {
   RefPtr<DrawTarget> drawTarget = Factory::CreateDrawTargetForCairoSurface(aSurface->CairoSurface(), aSize);
--- a/image/src/imgLoader.cpp
+++ b/image/src/imgLoader.cpp
@@ -606,19 +606,17 @@ already_AddRefed<imgCacheEntry> imgCache
   if (IsDirty())
     Refresh();
 
   nsRefPtr<imgCacheEntry> entry = mQueue[0];
   std::pop_heap(mQueue.begin(), mQueue.end(), imgLoader::CompareCacheEntries);
   mQueue.pop_back();
 
   mSize -= entry->GetDataSize();
-  imgCacheEntry *ret = entry;
-  NS_ADDREF(ret);
-  return ret;
+  return entry.forget();
 }
 
 void imgCacheQueue::Refresh()
 {
   std::make_heap(mQueue.begin(), mQueue.end(), imgLoader::CompareCacheEntries);
   mDirty = false;
 }
 
--- a/image/src/imgLoader.h
+++ b/image/src/imgLoader.h
@@ -98,19 +98,18 @@ public:
   void SetMustValidate(bool aValidate)
   {
     mMustValidate = aValidate;
     Touch();
   }
 
   already_AddRefed<imgRequest> GetRequest() const
   {
-    imgRequest *req = mRequest;
-    NS_ADDREF(req);
-    return req;
+    nsRefPtr<imgRequest> req = mRequest;
+    return req.forget();
   }
 
   bool Evicted() const
   {
     return mEvicted;
   }
 
   nsExpirationState *GetExpirationState()
--- a/intl/locale/src/nsLanguageAtomService.cpp
+++ b/intl/locale/src/nsLanguageAtomService.cpp
@@ -63,24 +63,20 @@ nsLanguageAtomService::LookupCharSet(con
   mCharSets->GetCharsetLangGroup(aCharSet, getter_AddRefs(langGroup));
   if (!langGroup) {
     if (aError)
       *aError = NS_ERROR_FAILURE;
 
     return nullptr;
   }
 
-  // transfer reference to raw pointer
-  nsIAtom *raw = nullptr;
-  langGroup.swap(raw);
-
   if (aError)
     *aError = NS_OK;
 
-  return raw;
+  return langGroup.forget();
 }
 
 nsIAtom*
 nsLanguageAtomService::GetLocaleLanguage(nsresult *aError)
 {
   nsresult res = NS_OK;
 
   do {
--- a/js/jsd/jsd_xpc.cpp
+++ b/js/jsd/jsd_xpc.cpp
@@ -146,18 +146,18 @@ jsds_FindEphemeral (LiveEphemeral **list
     
     LiveEphemeral *lv_record = 
         reinterpret_cast<LiveEphemeral *>
                         (PR_NEXT_LINK(&(*listHead)->links));
     do
     {
         if (lv_record->key == key)
         {
-            NS_IF_ADDREF(lv_record->value);
-            return lv_record->value;
+            nsCOMPtr<jsdIEphemeral> ret = lv_record->value;
+            return ret.forget();
         }
         lv_record = reinterpret_cast<LiveEphemeral *>
                                     (PR_NEXT_LINK(&lv_record->links));
     }
     while (lv_record != *listHead);
 
     return nullptr;
 }
--- a/layout/base/nsCSSFrameConstructor.cpp
+++ b/layout/base/nsCSSFrameConstructor.cpp
@@ -4140,24 +4140,24 @@ nsCSSFrameConstructor::BeginBuildingScro
   // consistent anyway.
   CreateAnonymousFrames(aState, aContent, gfxScrollFrame, nullptr,
                         anonymousItems);
 
   aNewFrame = gfxScrollFrame;
 
   // we used the style that was passed in. So resolve another one.
   nsStyleSet *styleSet = mPresShell->StyleSet();
-  nsStyleContext* aScrolledChildStyle =
-    styleSet->ResolveAnonymousBoxStyle(aScrolledPseudo, contentStyle).get();
+  nsRefPtr<nsStyleContext> scrolledChildStyle =
+    styleSet->ResolveAnonymousBoxStyle(aScrolledPseudo, contentStyle);
 
   if (gfxScrollFrame) {
      gfxScrollFrame->SetInitialChildList(kPrincipalList, anonymousItems);
   }
 
-  return aScrolledChildStyle;
+  return scrolledChildStyle.forget();
 }
 
 void
 nsCSSFrameConstructor::FinishBuildingScrollFrame(nsIFrame* aScrollFrame,
                                                  nsIFrame* aScrolledFrame)
 {
   nsFrameList scrolled(aScrolledFrame, aScrolledFrame);
   aScrollFrame->AppendFrames(kPrincipalList, scrolled);
--- a/layout/base/nsPresContext.cpp
+++ b/layout/base/nsPresContext.cpp
@@ -1455,21 +1455,18 @@ nsPresContext::SetContainer(nsISupports*
   if (mContainer) {
     GetDocumentColorPreferences();
   }
 }
 
 already_AddRefed<nsISupports>
 nsPresContext::GetContainerInternal() const
 {
-  nsISupports *result = nullptr;
-  if (mContainer)
-    CallQueryReferent(mContainer.get(), &result);
-
-  return result;
+  nsCOMPtr<nsISupports> result = do_QueryReferent(mContainer);
+  return result.forget();
 }
 
 already_AddRefed<nsISupports>
 nsPresContext::GetContainerExternal() const
 {
   return GetContainerInternal();
 }
 
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -673,18 +673,18 @@ nsIPresShell::RemoveWeakFrameInternal(ns
   if (nextWeak) {
     nextWeak->SetPreviousWeakFrame(aWeakFrame->GetPreviousWeakFrame());
   }
 }
 
 already_AddRefed<nsFrameSelection>
 nsIPresShell::FrameSelection()
 {
-  NS_IF_ADDREF(mSelection);
-  return mSelection;
+  nsRefPtr<nsFrameSelection> ret = mSelection;
+  return ret.forget();
 }
 
 //----------------------------------------------------------------------
 
 static bool sSynthMouseMove = true;
 
 PresShell::PresShell()
   : mMouseLocation(NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE)
@@ -2019,19 +2019,18 @@ PresShell::NotifyDestroyingFrame(nsIFram
     // tries to remove it from the (array) value of this property.
     mPresContext->PropertyTable()->
       Delete(aFrame, FrameLayerBuilder::LayerManagerDataProperty());
   }
 }
 
 already_AddRefed<nsCaret> PresShell::GetCaret() const
 {
-  nsCaret* caret = mCaret;
-  NS_IF_ADDREF(caret);
-  return caret;
+  nsRefPtr<nsCaret> caret = mCaret;
+  return caret.forget();
 }
 
 void PresShell::MaybeInvalidateCaretPosition()
 {
   if (mCaret) {
     mCaret->InvalidateOutsideCaret();
   }
 }
@@ -4706,21 +4705,20 @@ PresShell::PaintRangePaintInfo(nsTArray<
   }
   else {
     // move aScreenRect to the position of the surface in screen coordinates
     aScreenRect->MoveTo(rootScreenRect.x + pixelArea.x, rootScreenRect.y + pixelArea.y);
   }
   aScreenRect->width = pixelArea.width;
   aScreenRect->height = pixelArea.height;
 
-  gfxImageSurface* surface =
+  nsRefPtr<gfxImageSurface> surface =
     new gfxImageSurface(gfxIntSize(pixelArea.width, pixelArea.height),
                         gfxImageSurface::ImageFormatARGB32);
   if (surface->CairoStatus()) {
-    delete surface;
     return nullptr;
   }
 
   // clear the image
   gfxContext context(surface);
   context.SetOperator(gfxContext::OPERATOR_CLEAR);
   context.Rectangle(gfxRect(0, 0, pixelArea.width, pixelArea.height));
   context.Fill();
@@ -4769,18 +4767,17 @@ PresShell::PaintRangePaintInfo(nsTArray<
     rangeInfo->mList.ComputeVisibilityForRoot(&rangeInfo->mBuilder, &visible);
     rangeInfo->mList.PaintRoot(&rangeInfo->mBuilder, rc, nsDisplayList::PAINT_DEFAULT);
     aArea.MoveBy(rangeInfo->mRootOffset.x, rangeInfo->mRootOffset.y);
   }
 
   // restore the old selection display state
   frameSelection->SetDisplaySelection(oldDisplaySelection);
 
-  NS_ADDREF(surface);
-  return surface;
+  return surface.forget();
 }
 
 already_AddRefed<gfxASurface>
 PresShell::RenderNode(nsIDOMNode* aNode,
                       nsIntRegion* aRegion,
                       nsIntPoint& aPoint,
                       nsIntRect* aScreenRect)
 {
@@ -5668,30 +5665,26 @@ nsIFrame*
 PresShell::GetEventTargetFrame()
 {
   return GetCurrentEventFrame();
 }
 
 already_AddRefed<nsIContent>
 PresShell::GetEventTargetContent(nsEvent* aEvent)
 {
-  nsIContent* content = GetCurrentEventContent();
-  if (content) {
-    NS_ADDREF(content);
-  } else {
+  nsCOMPtr<nsIContent> content = GetCurrentEventContent();
+  if (!content) {
     nsIFrame* currentEventFrame = GetCurrentEventFrame();
     if (currentEventFrame) {
-      currentEventFrame->GetContentForEvent(aEvent, &content);
+      currentEventFrame->GetContentForEvent(aEvent, getter_AddRefs(content));
       NS_ASSERTION(!content || content->GetCurrentDoc() == mDocument,
                    "handing out content from a different doc");
-    } else {
-      content = nullptr;
-    }
-  }
-  return content;
+    }
+  }
+  return content.forget();
 }
 
 void
 PresShell::PushCurrentEventInfo(nsIFrame* aFrame, nsIContent* aContent)
 {
   if (mCurrentEventFrame || mCurrentEventContent) {
     mCurrentEventFrameStack.InsertElementAt(0, mCurrentEventFrame);
     mCurrentEventContentStack.InsertObjectAt(mCurrentEventContent, 0);
@@ -5797,19 +5790,20 @@ PresShell::DisableNonTestMouseEvents(boo
   sDisableNonTestMouseEvents = aDisable;
 }
 
 already_AddRefed<nsPIDOMWindow>
 PresShell::GetFocusedDOMWindowInOurWindow()
 {
   nsCOMPtr<nsPIDOMWindow> rootWindow = GetRootWindow();
   NS_ENSURE_TRUE(rootWindow, nullptr);
-  nsPIDOMWindow* focusedWindow;
-  nsFocusManager::GetFocusedDescendant(rootWindow, true, &focusedWindow);
-  return focusedWindow;
+  nsCOMPtr<nsPIDOMWindow> focusedWindow;
+  nsFocusManager::GetFocusedDescendant(rootWindow, true,
+                                       getter_AddRefs(focusedWindow));
+  return focusedWindow.forget();
 }
 
 void
 PresShell::RecordMouseLocation(nsGUIEvent* aEvent)
 {
   if (!mPresContext)
     return;
 
--- a/layout/forms/nsListControlFrame.cpp
+++ b/layout/forms/nsListControlFrame.cpp
@@ -1013,27 +1013,23 @@ nsListControlFrame::Init(nsIContent*    
   if (IsInDropDownMode()) {
     AddStateBits(NS_FRAME_IN_POPUP);
   }
 }
 
 already_AddRefed<nsIContent> 
 nsListControlFrame::GetOptionAsContent(nsIDOMHTMLOptionsCollection* aCollection, int32_t aIndex) 
 {
-  nsIContent * content = nullptr;
   nsCOMPtr<nsIDOMHTMLOptionElement> optionElement = GetOption(aCollection,
                                                               aIndex);
 
   NS_ASSERTION(optionElement != nullptr, "could not get option element by index!");
 
-  if (optionElement) {
-    CallQueryInterface(optionElement, &content);
-  }
- 
-  return content;
+  nsCOMPtr<nsIContent> content = do_QueryInterface(optionElement);
+  return content.forget();
 }
 
 already_AddRefed<nsIContent> 
 nsListControlFrame::GetOptionContent(int32_t aIndex) const
   
 {
   nsCOMPtr<nsIDOMHTMLOptionsCollection> options = GetOptions(mContent);
   NS_ASSERTION(options.get() != nullptr, "Collection of options is null!");
@@ -1042,38 +1038,37 @@ nsListControlFrame::GetOptionContent(int
     return GetOptionAsContent(options, aIndex);
   } 
   return nullptr;
 }
 
 already_AddRefed<nsIDOMHTMLOptionsCollection>
 nsListControlFrame::GetOptions(nsIContent * aContent)
 {
-  nsIDOMHTMLOptionsCollection* options = nullptr;
+  nsCOMPtr<nsIDOMHTMLOptionsCollection> options;
   nsCOMPtr<nsIDOMHTMLSelectElement> selectElement = do_QueryInterface(aContent);
   if (selectElement) {
-    selectElement->GetOptions(&options);  // AddRefs (1)
+    selectElement->GetOptions(getter_AddRefs(options));
   }
 
-  return options;
+  return options.forget();
 }
 
 already_AddRefed<nsIDOMHTMLOptionElement>
 nsListControlFrame::GetOption(nsIDOMHTMLOptionsCollection* aCollection,
                               int32_t aIndex)
 {
   nsCOMPtr<nsIDOMNode> node;
   if (NS_SUCCEEDED(aCollection->Item(aIndex, getter_AddRefs(node)))) {
     NS_ASSERTION(node,
                  "Item was successful, but node from collection was null!");
     if (node) {
-      nsIDOMHTMLOptionElement* option = nullptr;
-      CallQueryInterface(node, &option);
+      nsCOMPtr<nsIDOMHTMLOptionElement> option = do_QueryInterface(node);
 
-      return option;
+      return option.forget();
     }
   } else {
     NS_ERROR("Couldn't get option by index from collection!");
   }
   return nullptr;
 }
 
 bool 
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -5480,20 +5480,19 @@ nsFrame::GetSelectionController(nsPresCo
   }
 
   return CallQueryInterface(aPresContext->GetPresShell(), aSelCon);
 }
 
 already_AddRefed<nsFrameSelection>
 nsIFrame::GetFrameSelection()
 {
-  nsFrameSelection* fs =
+  nsRefPtr<nsFrameSelection> fs =
     const_cast<nsFrameSelection*>(GetConstFrameSelection());
-  NS_IF_ADDREF(fs);
-  return fs;
+  return fs.forget();
 }
 
 const nsFrameSelection*
 nsIFrame::GetConstFrameSelection() const
 {
   nsIFrame* frame = const_cast<nsIFrame*>(this);
   while (frame && (frame->GetStateBits() & NS_FRAME_INDEPENDENT_SELECTION)) {
     nsITextControlFrame* tcf = do_QueryFrame(frame);
--- a/layout/generic/nsTextFrameThebes.cpp
+++ b/layout/generic/nsTextFrameThebes.cpp
@@ -1701,19 +1701,18 @@ GetReferenceRenderingContext(nsTextFrame
 {
   nsRefPtr<nsRenderingContext> tmp = aRC;
   if (!tmp) {
     tmp = aTextFrame->PresContext()->PresShell()->GetReferenceRenderingContext();
     if (!tmp)
       return nullptr;
   }
 
-  gfxContext* ctx = tmp->ThebesContext();
-  NS_ADDREF(ctx);
-  return ctx;
+  nsRefPtr<gfxContext> ctx = tmp->ThebesContext();
+  return ctx.forget();
 }
 
 /**
  * The returned textrun must be deleted when no longer needed.
  */
 static gfxTextRun*
 GetHyphenTextRun(gfxTextRun* aTextRun, gfxContext* aContext, nsTextFrame* aTextFrame)
 {
--- a/layout/printing/nsPrintEngine.cpp
+++ b/layout/printing/nsPrintEngine.cpp
@@ -3110,25 +3110,25 @@ nsPrintEngine::FindFocusedDOMWindow()
   NS_ENSURE_TRUE(fm, nullptr);
 
   nsCOMPtr<nsPIDOMWindow> window(mDocument->GetWindow());
   NS_ENSURE_TRUE(window, nullptr);
 
   nsCOMPtr<nsPIDOMWindow> rootWindow = window->GetPrivateRoot();
   NS_ENSURE_TRUE(rootWindow, nullptr);
 
-  nsPIDOMWindow* focusedWindow;
-  nsFocusManager::GetFocusedDescendant(rootWindow, true, &focusedWindow);
+  nsCOMPtr<nsPIDOMWindow> focusedWindow;
+  nsFocusManager::GetFocusedDescendant(rootWindow, true,
+                                       getter_AddRefs(focusedWindow));
   NS_ENSURE_TRUE(focusedWindow, nullptr);
 
   if (IsWindowsInOurSubTree(focusedWindow)) {
-    return focusedWindow;
+    return focusedWindow.forget();
   }
 
-  NS_IF_RELEASE(focusedWindow);
   return nullptr;
 }
 
 //---------------------------------------------------------------------
 bool
 nsPrintEngine::IsWindowsInOurSubTree(nsPIDOMWindow * window)
 {
   bool found = false;
--- a/layout/style/StyleRule.cpp
+++ b/layout/style/StyleRule.cpp
@@ -1403,37 +1403,32 @@ StyleRule::GetExistingDOMRule()
 {
   return mDOMRule;
 }
 
 /* virtual */ already_AddRefed<StyleRule>
 StyleRule::DeclarationChanged(Declaration* aDecl,
                               bool aHandleContainer)
 {
-  StyleRule* clone = new StyleRule(*this, aDecl);
-  if (!clone) {
-    return nullptr;
-  }
-
-  NS_ADDREF(clone); // for return
+  nsRefPtr<StyleRule> clone = new StyleRule(*this, aDecl);
 
   if (aHandleContainer) {
     nsCSSStyleSheet* sheet = GetStyleSheet();
     if (mParentRule) {
       if (sheet) {
         sheet->ReplaceRuleInGroup(mParentRule, this, clone);
       } else {
         mParentRule->ReplaceStyleRule(this, clone);
       }
     } else if (sheet) {
       sheet->ReplaceStyleRule(this, clone);
     }
   }
 
-  return clone;
+  return clone.forget();
 }
 
 /* virtual */ void
 StyleRule::MapRuleInfoInto(nsRuleData* aRuleData)
 {
   NS_ABORT_IF_FALSE(mWasMatched,
                     "somebody forgot to call css::StyleRule::RuleMatched");
   mDeclaration->MapNormalRuleInfoInto(aRuleData);
--- a/layout/style/nsCSSStyleSheet.cpp
+++ b/layout/style/nsCSSStyleSheet.cpp
@@ -1568,23 +1568,22 @@ nsCSSStyleSheet::AppendAllChildSheets(ns
 }
 
 already_AddRefed<nsCSSStyleSheet>
 nsCSSStyleSheet::Clone(nsCSSStyleSheet* aCloneParent,
                        css::ImportRule* aCloneOwnerRule,
                        nsIDocument* aCloneDocument,
                        nsINode* aCloneOwningNode) const
 {
-  nsCSSStyleSheet* clone = new nsCSSStyleSheet(*this,
-                                               aCloneParent,
-                                               aCloneOwnerRule,
-                                               aCloneDocument,
-                                               aCloneOwningNode);
-  NS_IF_ADDREF(clone);
-  return clone;
+  nsRefPtr<nsCSSStyleSheet> clone = new nsCSSStyleSheet(*this,
+                                                        aCloneParent,
+                                                        aCloneOwnerRule,
+                                                        aCloneDocument,
+                                                        aCloneOwningNode);
+  return clone.forget();
 }
 
 #ifdef DEBUG
 static void
 ListRules(const nsCOMArray<css::Rule>& aRules, FILE* aOut, int32_t aIndent)
 {
   for (int32_t index = aRules.Count() - 1; index >= 0; --index) {
     aRules.ObjectAt(index)->List(aOut, aIndent);
--- a/layout/style/nsComputedDOMStyle.cpp
+++ b/layout/style/nsComputedDOMStyle.cpp
@@ -311,18 +311,18 @@ nsComputedDOMStyle::GetStyleContextForEl
     if (frame) {
       nsStyleContext* result =
         nsLayoutUtils::GetStyleFrame(frame)->StyleContext();
       // Don't use the style context if it was influenced by
       // pseudo-elements, since then it's not the primary style
       // for this element.
       if (!result->HasPseudoElementData()) {
         // this function returns an addrefed style context
-        result->AddRef();
-        return result;
+        nsRefPtr<nsStyleContext> ret = result;
+        return ret.forget();
       }
     }
   }
 
   // No frame has been created, or we have a pseudo, or we're looking
   // for the default style, so resolve the style ourselves.
   nsRefPtr<nsStyleContext> parentContext;
   nsIContent* parent = aPseudo ? aElement : aElement->GetParent();
--- a/layout/style/nsHTMLStyleSheet.cpp
+++ b/layout/style/nsHTMLStyleSheet.cpp
@@ -450,18 +450,18 @@ nsHTMLStyleSheet::UniqueMappedAttributes
   MappedAttrTableEntry *entry = static_cast<MappedAttrTableEntry*>
                                            (PL_DHashTableOperate(&mMappedAttrTable, aMapped, PL_DHASH_ADD));
   if (!entry)
     return nullptr;
   if (!entry->mAttributes) {
     // We added a new entry to the hashtable, so we have a new unique set.
     entry->mAttributes = aMapped;
   }
-  NS_ADDREF(entry->mAttributes); // for caller
-  return entry->mAttributes;
+  nsRefPtr<nsMappedAttributes> ret = entry->mAttributes;
+  return ret.forget();
 }
 
 void
 nsHTMLStyleSheet::DropMappedAttributes(nsMappedAttributes* aMapped)
 {
   NS_ENSURE_TRUE_VOID(aMapped);
 
   NS_ASSERTION(mMappedAttrTable.ops, "table uninitialized");
--- a/layout/style/nsRuleNode.cpp
+++ b/layout/style/nsRuleNode.cpp
@@ -3611,17 +3611,18 @@ nsRuleNode::GetShadowData(const nsCSSVal
                           nsStyleContext* aContext,
                           bool aIsBoxShadow,
                           bool& canStoreInRuleTree)
 {
   uint32_t arrayLength = ListLength(aList);
 
   NS_ABORT_IF_FALSE(arrayLength > 0,
                     "Non-null text-shadow list, yet we counted 0 items.");
-  nsCSSShadowArray* shadowList = new(arrayLength) nsCSSShadowArray(arrayLength);
+  nsRefPtr<nsCSSShadowArray> shadowList =
+    new(arrayLength) nsCSSShadowArray(arrayLength);
 
   if (!shadowList)
     return nullptr;
 
   nsStyleCoord tempCoord;
   DebugOnly<bool> unitOK;
   for (nsCSSShadowItem* item = shadowList->ShadowAt(0);
        aList;
@@ -3677,18 +3678,17 @@ nsRuleNode::GetShadowData(const nsCSSVal
       NS_ASSERTION(arr->Item(5).GetIntValue() == NS_STYLE_BOX_SHADOW_INSET,
                    "invalid keyword type for box shadow");
       item->mInset = true;
     } else {
       item->mInset = false;
     }
   }
 
-  NS_ADDREF(shadowList);
-  return shadowList;
+  return shadowList.forget();
 }
 
 const void*
 nsRuleNode::ComputeTextData(void* aStartStruct,
                             const nsRuleData* aRuleData,
                             nsStyleContext* aContext,
                             nsRuleNode* aHighestNode,
                             const RuleDetail aRuleDetail,
--- a/layout/style/nsStyleContext.cpp
+++ b/layout/style/nsStyleContext.cpp
@@ -151,17 +151,17 @@ nsStyleContext::FindChildWithRules(const
                                    nsRuleNode* aRulesIfVisited,
                                    bool aRelevantLinkVisited)
 {
   NS_ABORT_IF_FALSE(aRulesIfVisited || !aRelevantLinkVisited,
     "aRelevantLinkVisited should only be set when we have a separate style");
   uint32_t threshold = 10; // The # of siblings we're willing to examine
                            // before just giving this whole thing up.
 
-  nsStyleContext* result = nullptr;
+  nsRefPtr<nsStyleContext> result;
   nsStyleContext *list = aRuleNode->IsRoot() ? mEmptyChild : mChild;
 
   if (list) {
     nsStyleContext *child = list;
     do {
       if (child->mRuleNode == aRuleNode &&
           child->mPseudoTag == aPseudoTag &&
           !child->IsStyleIfVisited() &&
@@ -186,22 +186,19 @@ nsStyleContext::FindChildWithRules(const
   }
 
   if (result) {
     if (result != list) {
       // Move result to the front of the list.
       RemoveChild(result);
       AddChild(result);
     }
-
-    // Add reference for the caller.
-    result->AddRef();
   }
 
-  return result;
+  return result.forget();
 }
 
 const void* nsStyleContext::GetCachedStyleData(nsStyleStructID aSID)
 {
   const void* cachedData;
   if (nsCachedStyleData::IsReset(aSID)) {
     if (mCachedResetData) {
       cachedData = mCachedResetData->mStyleStructs[aSID];
@@ -715,22 +712,21 @@ nsStyleContext::Destroy()
 
 already_AddRefed<nsStyleContext>
 NS_NewStyleContext(nsStyleContext* aParentContext,
                    nsIAtom* aPseudoTag,
                    nsCSSPseudoElements::Type aPseudoType,
                    nsRuleNode* aRuleNode,
                    bool aSkipFlexItemStyleFixup)
 {
-  nsStyleContext* context =
+  nsRefPtr<nsStyleContext> context =
     new (aRuleNode->PresContext())
     nsStyleContext(aParentContext, aPseudoTag, aPseudoType, aRuleNode,
                    aSkipFlexItemStyleFixup);
-  context->AddRef();
-  return context;
+  return context.forget();
 }
 
 static inline void
 ExtractAnimationValue(nsCSSProperty aProperty,
                       nsStyleContext* aStyleContext,
                       nsStyleAnimation::Value& aResult)
 {
   DebugOnly<bool> success =
--- a/layout/style/nsStyleSet.cpp
+++ b/layout/style/nsStyleSet.cpp
@@ -1659,18 +1659,18 @@ nsStyleSet::ReparentStyleContext(nsStyle
   if (!aStyleContext) {
     NS_NOTREACHED("must have style context");
     return nullptr;
   }
 
   // This short-circuit is OK because we don't call TryStartingTransition
   // during style reresolution if the style context pointer hasn't changed.
   if (aStyleContext->GetParent() == aNewParentContext) {
-    aStyleContext->AddRef();
-    return aStyleContext;
+    nsRefPtr<nsStyleContext> ret = aStyleContext;
+    return ret.forget();
   }
 
   nsIAtom* pseudoTag = aStyleContext->GetPseudo();
   nsCSSPseudoElements::Type pseudoType = aStyleContext->GetPseudoType();
   nsRuleNode* ruleNode = aStyleContext->RuleNode();
 
   // Skip transition rules as needed just like
   // nsTransitionManager::WalkTransitionRule would.
--- a/layout/svg/nsSVGFilterInstance.cpp
+++ b/layout/svg/nsSVGFilterInstance.cpp
@@ -71,19 +71,17 @@ nsSVGFilterInstance::CreateImage()
     new gfxImageSurface(gfxIntSize(mSurfaceRect.width, mSurfaceRect.height),
                         gfxASurface::ImageFormatARGB32);
 
   if (!surface || surface->CairoStatus())
     return nullptr;
 
   surface->SetDeviceOffset(gfxPoint(-mSurfaceRect.x, -mSurfaceRect.y));
 
-  gfxImageSurface *retval = nullptr;
-  surface.swap(retval);
-  return retval;
+  return surface.forget();
 }
 
 gfxRect
 nsSVGFilterInstance::UserSpaceToFilterSpace(const gfxRect& aRect) const
 {
   gfxRect r = aRect - mFilterRegion.TopLeft();
   r.Scale(mFilterSpaceSize.width / mFilterRegion.Width(),
           mFilterSpaceSize.height / mFilterRegion.Height());
--- a/layout/svg/nsSVGGradientFrame.cpp
+++ b/layout/svg/nsSVGGradientFrame.cpp
@@ -518,19 +518,18 @@ nsSVGLinearGradientFrame::CreateGradient
 {
   float x1, y1, x2, y2;
 
   x1 = GetLengthValue(dom::SVGLinearGradientElement::ATTR_X1);
   y1 = GetLengthValue(dom::SVGLinearGradientElement::ATTR_Y1);
   x2 = GetLengthValue(dom::SVGLinearGradientElement::ATTR_X2);
   y2 = GetLengthValue(dom::SVGLinearGradientElement::ATTR_Y2);
 
-  gfxPattern *pattern = new gfxPattern(x1, y1, x2, y2);
-  NS_IF_ADDREF(pattern);
-  return pattern;
+  nsRefPtr<gfxPattern> pattern = new gfxPattern(x1, y1, x2, y2);
+  return pattern.forget();
 }
 
 // -------------------------------------------------------------------------
 // Radial Gradients
 // -------------------------------------------------------------------------
 
 #ifdef DEBUG
 void
@@ -667,19 +666,18 @@ nsSVGRadialGradientFrame::CreateGradient
     double d = sqrt((dx * dx) + (dy * dy));
     if (d > dMax) {
       double angle = atan2(dy, dx);
       fx = (float)(dMax * cos(angle)) + cx;
       fy = (float)(dMax * sin(angle)) + cy;
     }
   }
 
-  gfxPattern *pattern = new gfxPattern(fx, fy, 0, cx, cy, r);
-  NS_IF_ADDREF(pattern);
-  return pattern;
+  nsRefPtr<gfxPattern> pattern = new gfxPattern(fx, fy, 0, cx, cy, r);
+  return pattern.forget();
 }
 
 // -------------------------------------------------------------------------
 // Public functions
 // -------------------------------------------------------------------------
 
 nsIFrame*
 NS_NewSVGLinearGradientFrame(nsIPresShell*   aPresShell,
--- a/layout/svg/nsSVGMaskFrame.cpp
+++ b/layout/svg/nsSVGMaskFrame.cpp
@@ -121,20 +121,19 @@ nsSVGMaskFrame::ComputeMaskAlpha(nsRende
       nsSVGUtils::ComputeLinearRGBLuminanceMask(data, stride, rect, aOpacity);
     } else {
       nsSVGUtils::ComputesRGBLuminanceMask(data, stride, rect, aOpacity);
     }
   } else {
     nsSVGUtils::ComputeAlphaMask(data, stride, rect, aOpacity);
   }
 
-  gfxPattern *retval = new gfxPattern(image);
+  nsRefPtr<gfxPattern> retval = new gfxPattern(image);
   retval->SetMatrix(matrix);
-  NS_IF_ADDREF(retval);
-  return retval;
+  return retval.forget();
 }
 
 /* virtual */ void
 nsSVGMaskFrame::DidSetStyleContext(nsStyleContext* aOldStyleContext)
 {
   nsSVGEffects::InvalidateDirectRenderingObservers(this);
   nsSVGMaskFrameBase::DidSetStyleContext(aOldStyleContext);
 }
--- a/layout/tools/layout-debug/src/nsLayoutDebuggingTools.cpp
+++ b/layout/tools/layout-debug/src/nsLayoutDebuggingTools.cpp
@@ -32,19 +32,19 @@ static NS_DEFINE_CID(kLayoutDebuggerCID,
 
 using namespace mozilla;
 
 static already_AddRefed<nsIContentViewer>
 doc_viewer(nsIDocShell *aDocShell)
 {
     if (!aDocShell)
         return nullptr;
-    nsIContentViewer *result = nullptr;
-    aDocShell->GetContentViewer(&result);
-    return result;
+    nsCOMPtr<nsIContentViewer> result;
+    aDocShell->GetContentViewer(getter_AddRefs(result));
+    return result.forget();
 }
 
 static already_AddRefed<nsIPresShell>
 pres_shell(nsIDocShell *aDocShell)
 {
     nsCOMPtr<nsIContentViewer> cv = doc_viewer(aDocShell);
     if (!cv)
         return nullptr;
@@ -68,19 +68,18 @@ document(nsIDocShell *aDocShell)
 {
     nsCOMPtr<nsIContentViewer> cv(doc_viewer(aDocShell));
     if (!cv)
         return nullptr;
     nsCOMPtr<nsIDOMDocument> domDoc;
     cv->GetDOMDocument(getter_AddRefs(domDoc));
     if (!domDoc)
         return nullptr;
-    nsIDocument *result = nullptr;
-    CallQueryInterface(domDoc, &result);
-    return result;
+    nsCOMPtr<nsIDocument> result = do_QueryInterface(domDoc);
+    return result.forget();
 }
 #endif
 
 nsLayoutDebuggingTools::nsLayoutDebuggingTools()
   : mPaintFlashing(false),
     mPaintDumping(false),
     mInvalidateDumping(false),
     mEventDumping(false),
--- a/layout/xul/base/src/nsListBoxLayout.cpp
+++ b/layout/xul/base/src/nsListBoxLayout.cpp
@@ -202,12 +202,11 @@ nsListBoxLayout::LayoutInternal(nsIFrame
 
   return NS_OK;
 }
 
 // Creation Routines ///////////////////////////////////////////////////////////////////////
 
 already_AddRefed<nsBoxLayout> NS_NewListBoxLayout()
 {
-  nsBoxLayout* layout = new nsListBoxLayout();
-  NS_IF_ADDREF(layout);
-  return layout;
+  nsRefPtr<nsBoxLayout> layout = new nsListBoxLayout();
+  return layout.forget();
 } 
--- a/layout/xul/base/src/nsSliderFrame.cpp
+++ b/layout/xul/base/src/nsSliderFrame.cpp
@@ -44,19 +44,18 @@ bool nsSliderFrame::gMiddlePref = false;
 int32_t nsSliderFrame::gSnapMultiplier;
 
 // Turn this on if you want to debug slider frames.
 #undef DEBUG_SLIDER
 
 static already_AddRefed<nsIContent>
 GetContentOfBox(nsIFrame *aBox)
 {
-  nsIContent* content = aBox->GetContent();
-  NS_IF_ADDREF(content);
-  return content;
+  nsCOMPtr<nsIContent> content = aBox->GetContent();
+  return content.forget();
 }
 
 nsIFrame*
 NS_NewSliderFrame (nsIPresShell* aPresShell, nsStyleContext* aContext)
 {
   return new (aPresShell) nsSliderFrame(aPresShell, aContext);
 }
 
--- a/layout/xul/grid/nsGridRowGroupLayout.cpp
+++ b/layout/xul/grid/nsGridRowGroupLayout.cpp
@@ -20,19 +20,18 @@
 #include "nsIScrollableFrame.h"
 #include "nsBoxLayoutState.h"
 #include "nsGridLayout2.h"
 #include "nsGridRow.h"
 #include "nsHTMLReflowState.h"
 
 already_AddRefed<nsBoxLayout> NS_NewGridRowGroupLayout()
 {
-  nsBoxLayout* layout = new nsGridRowGroupLayout();
-  NS_IF_ADDREF(layout);
-  return layout;
+  nsRefPtr<nsBoxLayout> layout = new nsGridRowGroupLayout();
+  return layout.forget();
 } 
 
 nsGridRowGroupLayout::nsGridRowGroupLayout():nsGridRowLayout(), mRowCount(0)
 {
 }
 
 nsGridRowGroupLayout::~nsGridRowGroupLayout()
 {
--- a/layout/xul/grid/nsGridRowLeafLayout.cpp
+++ b/layout/xul/grid/nsGridRowLeafLayout.cpp
@@ -17,19 +17,18 @@
 #include "nsBox.h"
 #include "nsIScrollableFrame.h"
 #include "nsBoxFrame.h"
 #include "nsGridLayout2.h"
 #include <algorithm>
 
 already_AddRefed<nsBoxLayout> NS_NewGridRowLeafLayout()
 {
-  nsBoxLayout* layout = new nsGridRowLeafLayout();
-  NS_IF_ADDREF(layout);
-  return layout;
+  nsRefPtr<nsBoxLayout> layout = new nsGridRowLeafLayout();
+  return layout.forget();
 } 
 
 nsGridRowLeafLayout::nsGridRowLeafLayout():nsGridRowLayout()
 {
 }
 
 nsGridRowLeafLayout::~nsGridRowLeafLayout()
 {
--- a/layout/xul/tree/nsTreeBodyFrame.h
+++ b/layout/xul/tree/nsTreeBodyFrame.h
@@ -397,19 +397,18 @@ protected:
   }
 
 public:
   static
   already_AddRefed<nsTreeColumn> GetColumnImpl(nsITreeColumn* aUnknownCol) {
     if (!aUnknownCol)
       return nullptr;
 
-    nsTreeColumn* col;
-    aUnknownCol->QueryInterface(NS_GET_IID(nsTreeColumn), (void**)&col);
-    return col;
+    nsCOMPtr<nsTreeColumn> col = do_QueryInterface(aUnknownCol);
+    return col.forget();
   }
 
   /**
    * Remove an nsITreeImageListener from being tracked by this frame. Only tree
    * image listeners that are created by this frame are tracked.
    *
    * @param aListener A pointer to an nsTreeImageListener to no longer
    *        track.
--- a/media/webrtc/signaling/test/FakeMediaStreams.h
+++ b/media/webrtc/signaling/test/FakeMediaStreams.h
@@ -193,21 +193,20 @@ public:
   }
 
   NS_DECL_ISUPPORTS
 
   static already_AddRefed<Fake_DOMMediaStream>
   CreateSourceStream(nsIDOMWindow* aWindow, uint32_t aHintContents) {
     Fake_SourceMediaStream *source = new Fake_SourceMediaStream();
 
-    Fake_DOMMediaStream *ds = new Fake_DOMMediaStream(source);
+    nsRefPtr<Fake_DOMMediaStream> ds = new Fake_DOMMediaStream(source);
     ds->SetHintContents(aHintContents);
-    ds->AddRef();
 
-    return ds;
+    return ds.forget();
   }
 
   Fake_MediaStream *GetStream() { return mMediaStream; }
 
   // Hints to tell the SDP generator about whether this
   // MediaStream probably has audio and/or video
   enum {
     HINT_CONTENTS_AUDIO = 0x00000001U,
--- a/netwerk/base/public/nsNetUtil.h
+++ b/netwerk/base/public/nsNetUtil.h
@@ -1084,18 +1084,18 @@ NS_BufferOutputStream(nsIOutputStream *a
     NS_ASSERTION(aOutputStream, "No output stream given!");
 
     nsCOMPtr<nsIOutputStream> bos;
     nsresult rv = NS_NewBufferedOutputStream(getter_AddRefs(bos), aOutputStream,
                                              aBufferSize);
     if (NS_SUCCEEDED(rv))
         return bos.forget();
 
-    NS_ADDREF(aOutputStream);
-    return aOutputStream;
+    bos = aOutputStream;
+    return bos.forget();
 }
 
 // returns an input stream compatible with nsIUploadChannel::SetUploadStream()
 inline nsresult
 NS_NewPostDataStream(nsIInputStream  **result,
                      bool              isFile,
                      const nsACString &data)
 {
@@ -1621,31 +1621,31 @@ NS_TryToSetImmutable(nsIURI* uri)
  */
 inline already_AddRefed<nsIURI>
 NS_TryToMakeImmutable(nsIURI* uri,
                       nsresult* outRv = nullptr)
 {
     nsresult rv;
     nsCOMPtr<nsINetUtil> util = do_GetNetUtil(&rv);
 
-    nsIURI* result = nullptr;
+    nsCOMPtr<nsIURI> result;
     if (NS_SUCCEEDED(rv)) {
         NS_ASSERTION(util, "do_GetNetUtil lied");
-        rv = util->ToImmutableURI(uri, &result);
+        rv = util->ToImmutableURI(uri, getter_AddRefs(result));
     }
 
     if (NS_FAILED(rv)) {
-        NS_IF_ADDREF(result = uri);
+        result = uri;
     }
 
     if (outRv) {
         *outRv = rv;
     }
 
-    return result;
+    return result.forget();
 }
 
 /**
  * Helper function for testing whether the given URI, or any of its
  * inner URIs, has all the given protocol flags.
  */
 inline nsresult
 NS_URIChainHasFlags(nsIURI   *uri,
@@ -1659,32 +1659,33 @@ NS_URIChainHasFlags(nsIURI   *uri,
     return util->URIChainHasFlags(uri, flags, result);
 }
 
 /**
  * Helper function for getting the innermost URI for a given URI.  The return
  * value could be just the object passed in if it's not a nested URI.
  */
 inline already_AddRefed<nsIURI>
-NS_GetInnermostURI(nsIURI *uri)
+NS_GetInnermostURI(nsIURI* aURI)
 {
-    NS_PRECONDITION(uri, "Must have URI");
+    NS_PRECONDITION(aURI, "Must have URI");
+
+    nsCOMPtr<nsIURI> uri = aURI;
     
     nsCOMPtr<nsINestedURI> nestedURI(do_QueryInterface(uri));
     if (!nestedURI) {
-        NS_ADDREF(uri);
-        return uri;
+        return uri.forget();
     }
 
-    nsresult rv = nestedURI->GetInnermostURI(&uri);
+    nsresult rv = nestedURI->GetInnermostURI(getter_AddRefs(uri));
     if (NS_FAILED(rv)) {
         return nullptr;
     }
 
-    return uri;
+    return uri.forget();
 }
 
 /**
  * Get the "final" URI for a channel.  This is either the same as GetURI or
  * GetOriginalURI, depending on whether this channel has
  * nsIChanel::LOAD_REPLACE set.  For channels without that flag set, the final
  * URI is the original URI, while for ones with the flag the final URI is the
  * channel URI.
--- a/netwerk/base/src/nsSocketTransportService2.cpp
+++ b/netwerk/base/src/nsSocketTransportService2.cpp
@@ -96,19 +96,18 @@ nsSocketTransportService::~nsSocketTrans
 
 //-----------------------------------------------------------------------------
 // event queue (any thread)
 
 already_AddRefed<nsIThread>
 nsSocketTransportService::GetThreadSafely()
 {
     MutexAutoLock lock(mLock);
-    nsIThread* result = mThread;
-    NS_IF_ADDREF(result);
-    return result;
+    nsCOMPtr<nsIThread> result = mThread;
+    return result.forget();
 }
 
 NS_IMETHODIMP
 nsSocketTransportService::Dispatch(nsIRunnable *event, uint32_t flags)
 {
     SOCKET_LOG(("STS dispatch [%p]\n", event));
 
     nsCOMPtr<nsIThread> thread = GetThreadSafely();
--- a/parser/html/nsHtml5Module.cpp
+++ b/parser/html/nsHtml5Module.cpp
@@ -67,19 +67,18 @@ nsHtml5Module::ReleaseStatics()
   NS_IF_RELEASE(sMainThread);
 }
 
 // static
 already_AddRefed<nsIParser>
 nsHtml5Module::NewHtml5Parser()
 {
   NS_ABORT_IF_FALSE(sNsHtml5ModuleInitialized, "nsHtml5Module not initialized.");
-  nsIParser* rv = static_cast<nsIParser*> (new nsHtml5Parser());
-  NS_ADDREF(rv);
-  return rv;
+  nsCOMPtr<nsIParser> rv = new nsHtml5Parser();
+  return rv.forget();
 }
 
 // static
 nsresult
 nsHtml5Module::Initialize(nsIParser* aParser, nsIDocument* aDoc, nsIURI* aURI, nsISupports* aContainer, nsIChannel* aChannel)
 {
   NS_ABORT_IF_FALSE(sNsHtml5ModuleInitialized, "nsHtml5Module not initialized.");
   nsHtml5Parser* parser = static_cast<nsHtml5Parser*> (aParser);
--- a/rdf/base/src/nsRDFXMLSerializer.cpp
+++ b/rdf/base/src/nsRDFXMLSerializer.cpp
@@ -195,19 +195,17 @@ nsRDFXMLSerializer::EnsureNewPrefix()
         qname.AppendInt(++mPrefixID, 10);
         prefix = do_GetAtom(qname);
         nsNameSpaceMap::const_iterator iter = mNameSpaces.first();
         while (iter != mNameSpaces.last() && isNewPrefix) {
             isNewPrefix = (iter->mPrefix != prefix);
             ++iter;
         } 
     } while (!isNewPrefix);
-    nsIAtom* outPrefix = nullptr;
-    prefix.swap(outPrefix);
-    return outPrefix;
+    return prefix.forget();
 }
 
 // This converts a property resource (like
 // "http://www.w3.org/TR/WD-rdf-syntax#Description") into a QName
 // ("RDF:Description"), and registers the namespace, if it's made up.
 
 nsresult
 nsRDFXMLSerializer::RegisterQName(nsIRDFResource* aResource)
--- a/security/manager/boot/src/nsSecureBrowserUIImpl.cpp
+++ b/security/manager/boot/src/nsSecureBrowserUIImpl.cpp
@@ -240,28 +240,28 @@ nsSecureBrowserUIImpl::GetState(uint32_t
   ReentrantMonitorAutoEnter lock(mReentrantMonitor);
   return MapInternalToExternalState(aState, mNotifiedSecurityState, mNotifiedToplevelIsEV);
 }
 
 // static
 already_AddRefed<nsISupports> 
 nsSecureBrowserUIImpl::ExtractSecurityInfo(nsIRequest* aRequest)
 {
-  nsISupports *retval = nullptr; 
+  nsCOMPtr<nsISupports> retval;
   nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
   if (channel)
-    channel->GetSecurityInfo(&retval);
+    channel->GetSecurityInfo(getter_AddRefs(retval));
   
   if (!retval) {
     nsCOMPtr<nsISecurityInfoProvider> provider(do_QueryInterface(aRequest));
     if (provider)
-      provider->GetSecurityInfo(&retval);
+      provider->GetSecurityInfo(getter_AddRefs(retval));
   }
 
-  return retval;
+  return retval.forget();
 }
 
 nsresult
 nsSecureBrowserUIImpl::MapInternalToExternalState(uint32_t* aState, lockIconState lock, bool ev)
 {
   NS_ENSURE_ARG(aState);
 
   switch (lock)
--- a/security/manager/ssl/src/nsCertTree.cpp
+++ b/security/manager/ssl/src/nsCertTree.cpp
@@ -279,24 +279,23 @@ nsCertTree::GetThreadDescAtIndex(int32_t
 already_AddRefed<nsIX509Cert>
 nsCertTree::GetCertAtIndex(int32_t index, int32_t *outAbsoluteCertOffset)
 {
   RefPtr<nsCertTreeDispInfo> certdi(
     GetDispInfoAtIndex(index, outAbsoluteCertOffset));
   if (!certdi)
     return nullptr;
 
-  nsIX509Cert *rawPtr = nullptr;
+  nsCOMPtr<nsIX509Cert> ret;
   if (certdi->mCert) {
-    rawPtr = certdi->mCert;
+    ret = certdi->mCert;
   } else if (certdi->mAddonInfo) {
-    rawPtr = certdi->mAddonInfo->mCert;
+    ret = certdi->mAddonInfo->mCert;
   }
-  NS_IF_ADDREF(rawPtr);
-  return rawPtr;
+  return ret.forget();
 }
 
 //  If the row at index is a cert, return that cert.  Otherwise, return null.
 TemporaryRef<nsCertTreeDispInfo>
 nsCertTree::GetDispInfoAtIndex(int32_t index, 
                                int32_t *outAbsoluteCertOffset)
 {
   int i, idx = 0, cIndex = 0, nc;
--- a/toolkit/components/places/tests/cpp/places_test_harness.h
+++ b/toolkit/components/places/tests/cpp/places_test_harness.h
@@ -235,20 +235,20 @@ do_get_NavHistory()
 
 already_AddRefed<mozIStorageConnection>
 do_get_db()
 {
   nsCOMPtr<nsINavHistoryService> history = do_get_NavHistory();
   nsCOMPtr<nsPIPlacesDatabase> database = do_QueryInterface(history);
   do_check_true(database);
 
-  mozIStorageConnection* dbConn;
-  nsresult rv = database->GetDBConnection(&dbConn);
+  nsCOMPtr<mozIStorageConnection> dbConn;
+  nsresult rv = database->GetDBConnection(getter_AddRefs(dbConn));
   do_check_success(rv);
-  return dbConn;
+  return dbConn.forget();
 }
 
 /**
  * Get the place record from the database.
  *
  * @param aURI The unique URI of the place we are looking up
  * @param result Out parameter where the result is stored
  */
--- a/toolkit/components/telemetry/Telemetry.cpp
+++ b/toolkit/components/telemetry/Telemetry.cpp
@@ -1858,18 +1858,18 @@ TelemetryImpl::GetCanSend(bool *ret) {
 already_AddRefed<nsITelemetry>
 TelemetryImpl::CreateTelemetryInstance()
 {
   NS_ABORT_IF_FALSE(sTelemetry == NULL, "CreateTelemetryInstance may only be called once, via GetService()");
   sTelemetry = new TelemetryImpl(); 
   // AddRef for the local reference
   NS_ADDREF(sTelemetry);
   // AddRef for the caller
-  NS_ADDREF(sTelemetry);
-  return sTelemetry;
+  nsCOMPtr<nsITelemetry> ret = sTelemetry;
+  return ret.forget();
 }
 
 void
 TelemetryImpl::ShutdownTelemetry()
 {
   NS_IF_RELEASE(sTelemetry);
 }
 
--- a/toolkit/components/typeaheadfind/nsTypeAheadFind.cpp
+++ b/toolkit/components/typeaheadfind/nsTypeAheadFind.cpp
@@ -1214,19 +1214,18 @@ nsTypeAheadFind::IsRangeVisible(nsIPresS
 }
 
 already_AddRefed<nsIPresShell>
 nsTypeAheadFind::GetPresShell()
 {
   if (!mPresShell)
     return nullptr;
 
-  nsIPresShell *shell = nullptr;
-  CallQueryReferent(mPresShell.get(), &shell);
+  nsCOMPtr<nsIPresShell> shell = do_QueryReferent(mPresShell);
   if (shell) {
     nsPresContext *pc = shell->GetPresContext();
     if (!pc || !nsCOMPtr<nsISupports>(pc->GetContainer())) {
-      NS_RELEASE(shell);
+      return nullptr;
     }
   }
 
-  return shell;
+  return shell.forget();
 }
--- a/toolkit/system/dbus/nsDBusService.cpp
+++ b/toolkit/system/dbus/nsDBusService.cpp
@@ -2,16 +2,17 @@
 /* vim:expandtab:shiftwidth=4:tabstop=4:
  */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDBusService.h"
 #include "nsComponentManagerUtils.h"
+#include "nsAutoPtr.h"
 
 #include <glib.h>
 #include <dbus/dbus-glib-lowlevel.h>
 #include <dbus/dbus-glib.h>
 
 nsDBusService::nsDBusService() {
   mConnection = nullptr;
   mSingleClient = nullptr;
@@ -31,18 +32,18 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsDBusServ
 
 nsDBusService* nsDBusService::gSingleton = nullptr;
 
 already_AddRefed<nsDBusService>
 nsDBusService::Get() {
   if (!gSingleton) {
     gSingleton = new nsDBusService();
   }
-  NS_IF_ADDREF(gSingleton);
-  return gSingleton;
+  nsRefPtr<nsDBusService> ret = gSingleton;
+  return ret.forget();
 }
   
 nsresult
 nsDBusService::AddClient(DBusClient* client) {
   NS_ASSERTION(!mSingleClient, "Only one client supported right now");
   mSingleClient = client;
   nsresult rv = CreateConnection();
   if (NS_FAILED(rv)) {
--- a/toolkit/xre/nsAppRunner.cpp
+++ b/toolkit/xre/nsAppRunner.cpp
@@ -287,39 +287,40 @@ SaveFileToEnv(const char *name, nsIFile 
 #endif
 }
 
 // Load the path of a file saved with SaveFileToEnv
 static already_AddRefed<nsIFile>
 GetFileFromEnv(const char *name)
 {
   nsresult rv;
-  nsIFile *file = nullptr;
+  nsCOMPtr<nsIFile> file;
 
 #ifdef XP_WIN
   WCHAR path[_MAX_PATH];
   if (!GetEnvironmentVariableW(NS_ConvertASCIItoUTF16(name).get(),
                                path, _MAX_PATH))
     return nullptr;
 
-  rv = NS_NewLocalFile(nsDependentString(path), true, &file);
+  rv = NS_NewLocalFile(nsDependentString(path), true, getter_AddRefs(file));
   if (NS_FAILED(rv))
     return nullptr;
 
-  return file;
+  return file.forget();
 #else
   const char *arg = PR_GetEnv(name);
   if (!arg || !*arg)
     return nullptr;
 
-  rv = NS_NewNativeLocalFile(nsDependentCString(arg), true, &file);
+  rv = NS_NewNativeLocalFile(nsDependentCString(arg), true,
+                             getter_AddRefs(file));
   if (NS_FAILED(rv))
     return nullptr;
 
-  return file;
+  return file.forget();
 #endif
 }
 
 // Save the path of the given word to the specified environment variable
 // provided the environment variable does not have a value.
 static void
 SaveWordToEnvIfUnset(const char *name, const nsACString & word)
 {
--- a/uriloader/base/nsDocLoader.cpp
+++ b/uriloader/base/nsDocLoader.cpp
@@ -230,23 +230,18 @@ NS_IMETHODIMP nsDocLoader::GetInterface(
 
   return rv;
 }
 
 /* static */
 already_AddRefed<nsDocLoader>
 nsDocLoader::GetAsDocLoader(nsISupports* aSupports)
 {
-  if (!aSupports) {
-    return nullptr;
-  }
-  
-  nsDocLoader* ptr;
-  CallQueryInterface(aSupports, &ptr);
-  return ptr;
+  nsRefPtr<nsDocLoader> ret = do_QueryObject(aSupports);
+  return ret.forget();
 }
 
 /* static */
 nsresult
 nsDocLoader::AddDocLoaderAsChildOfRoot(nsDocLoader* aDocLoader)
 {
   nsresult rv;
   nsCOMPtr<nsIDocumentLoader> docLoaderService =
--- a/uriloader/exthandler/unix/nsGNOMERegistry.cpp
+++ b/uriloader/exthandler/unix/nsGNOMERegistry.cpp
@@ -181,12 +181,10 @@ nsGNOMERegistry::GetFromType(const nsACS
   nsAutoCString realName (dgettext(kDefaultTextDomain, PromiseFlatCString(name).get()));
   mimeInfo->SetDefaultDescription(NS_ConvertUTF8toUTF16(realName));
 #else
   mimeInfo->SetDefaultDescription(NS_ConvertUTF8toUTF16(name));
 #endif
   mimeInfo->SetPreferredAction(nsIMIMEInfo::useSystemDefault);
   mimeInfo->SetDescription(NS_ConvertUTF8toUTF16(description));
 
-  nsMIMEInfoBase* retval;
-  NS_ADDREF((retval = mimeInfo));
-  return retval;
+  return mimeInfo.forget();
 }
--- a/uriloader/exthandler/unix/nsOSHelperAppService.cpp
+++ b/uriloader/exthandler/unix/nsOSHelperAppService.cpp
@@ -1265,20 +1265,21 @@ nsOSHelperAppService::GetFromExtension(c
                                          minorType,
                                          mime_types_description,
                                          true);
 
   if (NS_FAILED(rv) || majorType.IsEmpty()) {
     
 #ifdef MOZ_WIDGET_GTK2
     LOG(("Looking in GNOME registry\n"));
-    nsMIMEInfoBase *gnomeInfo = nsGNOMERegistry::GetFromExtension(aFileExt).get();
+    nsRefPtr<nsMIMEInfoBase> gnomeInfo =
+      nsGNOMERegistry::GetFromExtension(aFileExt);
     if (gnomeInfo) {
       LOG(("Got MIMEInfo from GNOME registry\n"));
-      return gnomeInfo;
+      return gnomeInfo.forget();
     }
 #endif
 
     rv = LookUpTypeAndDescription(NS_ConvertUTF8toUTF16(aFileExt),
                                   majorType,
                                   minorType,
                                   mime_types_description,
                                   false);
@@ -1296,20 +1297,17 @@ nsOSHelperAppService::GetFromExtension(c
           NS_LossyConvertUTF16toASCII(mime_types_description).get()));
 
   if (majorType.IsEmpty() && minorType.IsEmpty()) {
     // we didn't get a type mapping, so we can't do anything useful
     return nullptr;
   }
 
   nsAutoCString mimeType(asciiMajorType + NS_LITERAL_CSTRING("/") + asciiMinorType);
-  nsMIMEInfoUnix* mimeInfo = new nsMIMEInfoUnix(mimeType);
-  if (!mimeInfo)
-    return nullptr;
-  NS_ADDREF(mimeInfo);
+  nsRefPtr<nsMIMEInfoUnix> mimeInfo = new nsMIMEInfoUnix(mimeType);
   
   mimeInfo->AppendExtension(aFileExt);
   nsHashtable typeOptions; // empty hash table
   rv = LookUpHandlerAndDescription(majorType, minorType, typeOptions,
                                    handler, mailcap_description,
                                    mozillaFlags);
   LOG(("Handler/Description results:  handler='%s', description='%s', mozillaFlags='%s'\n",
           NS_LossyConvertUTF16toASCII(handler).get(),
@@ -1337,17 +1335,17 @@ nsOSHelperAppService::GetFromExtension(c
       mimeInfo->SetDefaultDescription(handler);
     }
   }
 
   if (NS_FAILED(rv)) {
     mimeInfo->SetPreferredAction(nsIMIMEInfo::saveToDisk);
   }
 
-  return mimeInfo;
+  return mimeInfo.forget();
 }
 
 already_AddRefed<nsMIMEInfoBase>
 nsOSHelperAppService::GetFromType(const nsCString& aMIMEType) {
   // if the type is empty, return immediately
   if (aMIMEType.IsEmpty())
     return nullptr;
   
@@ -1384,27 +1382,27 @@ nsOSHelperAppService::GetFromType(const 
                                 mozillaFlags,
                                 true);
   
   LOG(("Private Handler/Description results:  handler='%s', description='%s'\n",
           NS_LossyConvertUTF16toASCII(handler).get(),
           NS_LossyConvertUTF16toASCII(mailcap_description).get()));
 
 #ifdef MOZ_WIDGET_GTK2
-  nsMIMEInfoBase *gnomeInfo = nullptr;
+  nsRefPtr<nsMIMEInfoBase> gnomeInfo;
   if (handler.IsEmpty()) {
     // No useful data yet.  Check the GNOME registry.  Unfortunately, newer
     // GNOME versions no longer have type-to-extension mappings, so we might
     // get back a MIMEInfo without any extensions set.  In that case we'll have
     // to look in our mime.types files for the extensions.    
     LOG(("Looking in GNOME registry\n"));
-    gnomeInfo = nsGNOMERegistry::GetFromType(aMIMEType).get();
+    gnomeInfo = nsGNOMERegistry::GetFromType(aMIMEType);
     if (gnomeInfo && gnomeInfo->HasExtensions()) {
       LOG(("Got MIMEInfo from GNOME registry, and it has extensions set\n"));
-      return gnomeInfo;
+      return gnomeInfo.forget();
     }
   }
 #endif
 
   // Now look up our extensions
   nsAutoString extensions, mime_types_description;
   LookUpExtensionsAndDescription(majorType,
                                  minorType,
@@ -1413,17 +1411,17 @@ nsOSHelperAppService::GetFromType(const 
 
 #ifdef MOZ_WIDGET_GTK2
   if (gnomeInfo) {
     LOG(("Got MIMEInfo from GNOME registry without extensions; setting them "
          "to %s\n", NS_LossyConvertUTF16toASCII(extensions).get()));
 
     NS_ASSERTION(!gnomeInfo->HasExtensions(), "How'd that happen?");
     gnomeInfo->SetFileExtensions(NS_ConvertUTF16toUTF8(extensions));
-    return gnomeInfo;
+    return gnomeInfo.forget();
   }
 #endif
 
   if (handler.IsEmpty()) {
     DoLookUpHandlerAndDescription(majorType,
                                   minorType,
                                   typeOptions,
                                   handler,
@@ -1461,20 +1459,17 @@ nsOSHelperAppService::GetFromType(const 
   mozillaFlags.Trim(" \t");
 
   if (handler.IsEmpty() && extensions.IsEmpty() &&
       mailcap_description.IsEmpty() && mime_types_description.IsEmpty()) {
     // No real useful info
     return nullptr;
   }
   
-  nsMIMEInfoUnix* mimeInfo = new nsMIMEInfoUnix(aMIMEType);
-  if (!mimeInfo)
-    return nullptr;
-  NS_ADDREF(mimeInfo);
+  nsRefPtr<nsMIMEInfoUnix> mimeInfo = new nsMIMEInfoUnix(aMIMEType);
 
   mimeInfo->SetFileExtensions(NS_ConvertUTF16toUTF8(extensions));
   if (! mime_types_description.IsEmpty()) {
     mimeInfo->SetDescription(mime_types_description);
   } else {
     mimeInfo->SetDescription(mailcap_description);
   }
 
@@ -1487,67 +1482,66 @@ nsOSHelperAppService::GetFromType(const 
   if (NS_SUCCEEDED(rv)) {
     mimeInfo->SetDefaultApplication(handlerFile);
     mimeInfo->SetPreferredAction(nsIMIMEInfo::useSystemDefault);
     mimeInfo->SetDefaultDescription(handler);
   } else {
     mimeInfo->SetPreferredAction(nsIMIMEInfo::saveToDisk);
   }
 
-  return mimeInfo;
+  return mimeInfo.forget();
 }
 
 
 already_AddRefed<nsIMIMEInfo>
 nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aType,
                                         const nsACString& aFileExt,
                                         bool       *aFound) {
   *aFound = true;
-  nsMIMEInfoBase* retval = GetFromType(PromiseFlatCString(aType)).get();
+  nsRefPtr<nsMIMEInfoBase> retval = GetFromType(PromiseFlatCString(aType));
   bool hasDefault = false;
   if (retval)
     retval->GetHasDefaultHandler(&hasDefault);
   if (!retval || !hasDefault) {
     nsRefPtr<nsMIMEInfoBase> miByExt = GetFromExtension(PromiseFlatCString(aFileExt));
     // If we had no extension match, but a type match, use that
     if (!miByExt && retval)
-      return retval;
+      return retval.forget();
     // If we had an extension match but no type match, set the mimetype and use
     // it
     if (!retval && miByExt) {
       if (!aType.IsEmpty())
         miByExt->SetMIMEType(aType);
       miByExt.swap(retval);
 
-      return retval;
+      return retval.forget();
     }
     // If we got nothing, make a new mimeinfo
     if (!retval) {
       *aFound = false;
       retval = new nsMIMEInfoUnix(aType);
       if (retval) {
-        NS_ADDREF(retval);
         if (!aFileExt.IsEmpty())
           retval->AppendExtension(aFileExt);
       }
       
-      return retval;
+      return retval.forget();
     }
 
     // Copy the attributes of retval (mimeinfo from type) onto miByExt, to
     // return it 
     // but reset to just collected mDefaultAppDescription (from ext)
     nsAutoString byExtDefault;
     miByExt->GetDefaultDescription(byExtDefault);
     retval->SetDefaultDescription(byExtDefault);
     retval->CopyBasicDataTo(miByExt);
 
     miByExt.swap(retval);
   }
-  return retval;
+  return retval.forget();
 }
 
 NS_IMETHODIMP
 nsOSHelperAppService::GetProtocolHandlerInfoFromOS(const nsACString &aScheme,
                                                    bool *found,
                                                    nsIHandlerInfo **_retval)
 {
   NS_ASSERTION(!aScheme.IsEmpty(), "No scheme was specified!");
--- a/widget/gtk2/nsWindow.cpp
+++ b/widget/gtk2/nsWindow.cpp
@@ -5935,17 +5935,17 @@ nsWindow::GetSurfaceForGdkDrawable(GdkDr
                                    const nsIntSize& aSize)
 {
     GdkVisual* visual = gdk_drawable_get_visual(aDrawable);
     Screen* xScreen =
         gdk_x11_screen_get_xscreen(gdk_drawable_get_screen(aDrawable));
     Display* xDisplay = DisplayOfScreen(xScreen);
     Drawable xDrawable = gdk_x11_drawable_get_xid(aDrawable);
 
-    gfxASurface* result = nullptr;
+    nsRefPtr<gfxASurface> result;
 
     if (visual) {
         Visual* xVisual = gdk_x11_visual_get_xvisual(visual);
 
         result = new gfxXlibSurface(xDisplay, xDrawable, xVisual,
                                     gfxIntSize(aSize.width, aSize.height));
     } else {
         // no visual? we must be using an xrender format.  Find a format
@@ -5962,18 +5962,17 @@ nsWindow::GetSurfaceForGdkDrawable(GdkDr
                 NS_ERROR("Don't know how to handle the given depth!");
                 break;
         }
 
         result = new gfxXlibSurface(xScreen, xDrawable, pf,
                                     gfxIntSize(aSize.width, aSize.height));
     }
 
-    NS_IF_ADDREF(result);
-    return result;
+    return result.forget();
 }
 #endif
 
 // return the gfxASurface for rendering to this widget
 gfxASurface*
 #if defined(MOZ_WIDGET_GTK2)
 nsWindow::GetThebesSurface()
 #else
--- a/xpcom/base/nsAutoPtr.h
+++ b/xpcom/base/nsAutoPtr.h
@@ -978,17 +978,17 @@ class nsRefPtr
 
       already_AddRefed<T>
       forget()
           // return the value of mRawPtr and null out mRawPtr. Useful for
           // already_AddRefed return values.
         {
           T* temp = 0;
           swap(temp);
-          return temp;
+          return already_AddRefed<T>(temp);
         }
 
       template <typename I>
       void
       forget( I** rhs)
           // Set the target of rhs to the value of mRawPtr and null out mRawPtr.
           // Useful to avoid unnecessary AddRef/Release pairs with "out"
           // parameters where rhs bay be a T** or an I** where I is a base class
--- a/xpcom/build/Services.cpp
+++ b/xpcom/build/Services.cpp
@@ -33,18 +33,18 @@ using namespace mozilla::services;
                                                                         \
   already_AddRefed<TYPE>                                                \
   mozilla::services::Get##NAME()                                        \
   {                                                                     \
     if (!g##NAME) {                                                     \
       nsCOMPtr<TYPE> os = do_GetService(CONTRACT_ID);                   \
       g##NAME = os.forget().get();                                      \
     }                                                                   \
-    NS_IF_ADDREF(g##NAME);                                              \
-    return g##NAME;                                                     \
+    nsRefPtr<TYPE> ret = g##NAME;                                       \
+    return ret.forget();                                                \
   }                                                                     \
   NS_EXPORT_(already_AddRefed<TYPE>)                                    \
   mozilla::services::_external_Get##NAME()                              \
   {                                                                     \
     return Get##NAME();                                                 \
   }
 
 #include "ServiceList.h"
--- a/xpcom/build/nsXPComInit.cpp
+++ b/xpcom/build/nsXPComInit.cpp
@@ -252,26 +252,26 @@ NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsChromeProtocolHandler)
 
 #define NS_PERSISTENTPROPERTIES_CID NS_IPERSISTENTPROPERTIES_CID /* sigh */
 
 static already_AddRefed<nsIFactory>
 CreateINIParserFactory(const mozilla::Module& module,
                        const mozilla::Module::CIDEntry& entry)
 {
-    nsIFactory* f = new nsINIParserFactory();
-    f->AddRef();
-    return f;
+    nsCOMPtr<nsIFactory> f = new nsINIParserFactory();
+    return f.forget();
 }
 
 static already_AddRefed<nsIFactory>
 CreateUnicharStreamFactory(const mozilla::Module& module,
                            const mozilla::Module::CIDEntry& entry)
 {
-    return nsSimpleUnicharStreamFactory::GetInstance();
+    return already_AddRefed<nsIFactory>(
+            nsSimpleUnicharStreamFactory::GetInstance());
 }
 
 #define COMPONENT(NAME, Ctor) static NS_DEFINE_CID(kNS_##NAME##_CID, NS_##NAME##_CID);
 #include "XPCOMModule.inc"
 #undef COMPONENT
 
 #define COMPONENT(NAME, Ctor) { &kNS_##NAME##_CID, false, NULL, Ctor },
 const mozilla::Module::CIDEntry kXPCOMCIDEntries[] = {
--- a/xpcom/components/nsComponentManager.cpp
+++ b/xpcom/components/nsComponentManager.cpp
@@ -1792,19 +1792,18 @@ nsFactoryEntry::GetFactory()
             return NULL;
 
         SafeMutexAutoLock lock(nsComponentManagerImpl::gComponentManager->mLock);
         // Threads can race to set mFactory
         if (!mFactory) {
             factory.swap(mFactory);
         }
     }
-    nsIFactory* factory = mFactory;
-    factory->AddRef();
-    return factory;
+    nsCOMPtr<nsIFactory> factory = mFactory;
+    return factory.forget();
 }
 
 size_t
 nsFactoryEntry::SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf)
 {
     size_t n = aMallocSizeOf(this);
 
     // Measurement of the following members may be added later if DMD finds it is
--- a/xpcom/glue/nsCOMPtr.h
+++ b/xpcom/glue/nsCOMPtr.h
@@ -168,17 +168,17 @@ struct already_AddRefed
      *    nsRefPtr<BaseClass> y = x.forget();
      *    return y.forget();
      */
     template<class U>
     operator already_AddRefed<U>()
     {
       U* tmp = mRawPtr;
       mRawPtr = NULL;
-      return tmp;
+      return already_AddRefed<U>(tmp);
     }
 
     /**
      * This helper provides a static_cast replacement for already_AddRefed, so
      * if you have
      *
      *   already_AddRefed<Parent> F();
      *
@@ -776,17 +776,17 @@ class nsCOMPtr MOZ_FINAL
 
       already_AddRefed<T>
       forget()
           // return the value of mRawPtr and null out mRawPtr. Useful for
           // already_AddRefed return values.
         {
           T* temp = 0;
           swap(temp);
-          return temp;
+          return already_AddRefed<T>(temp);
         }
 
       template <typename I>
       void
       forget( I** rhs )
           // Set the target of rhs to the value of mRawPtr and null out mRawPtr.
           // Useful to avoid unnecessary AddRef/Release pairs with "out"
           // parameters where rhs bay be a T** or an I** where I is a base class
@@ -1083,17 +1083,17 @@ class nsCOMPtr<nsISupports>
 
       already_AddRefed<nsISupports>
       forget()
           // return the value of mRawPtr and null out mRawPtr. Useful for
           // already_AddRefed return values.
         {
           nsISupports* temp = 0;
           swap(temp);
-          return temp;
+          return already_AddRefed<nsISupports>(temp);
         }
 
       void
       forget( nsISupports** rhs )
           // Set the target of rhs to the value of mRawPtr and null out mRawPtr.
           // Useful to avoid unnecessary AddRef/Release pairs with "out"
           // parameters.
         {
--- a/xpcom/glue/nsIWeakReferenceUtils.h
+++ b/xpcom/glue/nsIWeakReferenceUtils.h
@@ -71,17 +71,17 @@ NS_GetWeakReference( nsISupports* , nsre
    * call through to |GetWeakReference|, and put it into your |nsCOMPtr|.
    * It is specifically designed to cooperate with |nsCOMPtr| (or |nsWeakPtr|) like so:
    * |nsWeakPtr myWeakPtr = do_GetWeakReference(aPtr);|.
    */
 inline
 already_AddRefed<nsIWeakReference>
 do_GetWeakReference( nsISupports* aRawPtr, nsresult* error = 0 )
   {
-    return NS_GetWeakReference(aRawPtr, error);
+    return dont_AddRef(NS_GetWeakReference(aRawPtr, error));
   }
 
 inline
 void
 do_GetWeakReference( nsIWeakReference* aRawPtr, nsresult* error = 0 )
   {
     // This signature exists solely to _stop_ you from doing a bad thing.
     //  Saying |do_GetWeakReference()| on a weak reference itself,
--- a/xpcom/tests/TestRacingServiceManager.cpp
+++ b/xpcom/tests/TestRacingServiceManager.cpp
@@ -220,18 +220,18 @@ static Factory* gFactory;
 
 static already_AddRefed<nsIFactory>
 CreateFactory(const mozilla::Module& module, const mozilla::Module::CIDEntry& entry)
 {
     if (!gFactory) {
         gFactory = new Factory();
         NS_ADDREF(gFactory);
     }
-    NS_ADDREF(gFactory);
-    return gFactory;
+    nsCOMPtr<nsIFactory> ret = gFactory;
+    return ret.forget();
 }
 
 static const mozilla::Module::CIDEntry kLocalCIDs[] = {
     { &kFactoryCID1, false, CreateFactory, NULL },
     { &kFactoryCID2, false, CreateFactory, NULL },
     { NULL }
 };