Bug 792180 - Replace NS_{UN,}LIKELY with MOZ_{UN,}LIKELY; r=ehsan
authorJacek Szpot <maligree@gmail.com>
Fri, 26 Oct 2012 15:32:10 +0200
changeset 111702 7bd96dda75f03267736c8e628995c0481014a139
parent 111701 9c5a898efbe9fdefa5d97591c57c989005a2cf5f
child 111703 537120d7827fc618f9e90e5622810a89f4ff85f0
push id17209
push usereakhgari@mozilla.com
push dateMon, 29 Oct 2012 22:08:20 +0000
treeherdermozilla-inbound@7bd96dda75f0 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersehsan
bugs792180
milestone19.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 792180 - Replace NS_{UN,}LIKELY with MOZ_{UN,}LIKELY; r=ehsan
accessible/src/atk/AtkSocketAccessible.cpp
accessible/src/atk/nsMaiInterfaceAction.cpp
accessible/src/atk/nsMaiInterfaceComponent.cpp
accessible/src/atk/nsMaiInterfaceDocument.cpp
accessible/src/atk/nsMaiInterfaceEditableText.cpp
accessible/src/atk/nsMaiInterfaceHyperlinkImpl.cpp
accessible/src/atk/nsMaiInterfaceHypertext.cpp
accessible/src/atk/nsMaiInterfaceImage.cpp
accessible/src/atk/nsMaiInterfaceSelection.cpp
accessible/src/atk/nsMaiInterfaceTable.cpp
accessible/src/atk/nsMaiInterfaceText.cpp
accessible/src/atk/nsMaiInterfaceValue.cpp
content/base/public/nsINode.h
content/base/src/FragmentOrElement.cpp
content/base/src/nsContentList.cpp
content/base/src/nsContentUtils.cpp
content/base/src/nsDocument.cpp
content/base/src/nsINode.cpp
content/base/src/nsNodeInfo.cpp
content/base/src/nsRange.cpp
content/events/src/nsDOMEventTargetHelper.cpp
content/html/content/src/nsGenericHTMLElement.cpp
content/svg/content/src/nsSVGSVGElement.cpp
dom/base/nsDOMClassInfo.cpp
dom/base/nsGlobalWindow.cpp
dom/base/nsJSTimeoutHandler.cpp
dom/base/nsLocation.cpp
dom/src/events/nsJSEventListener.cpp
dom/workers/WorkerPrivate.cpp
editor/txmgr/tests/TestTXMgr.cpp
extensions/auth/nsHttpNegotiateAuth.cpp
extensions/spellcheck/src/mozEnglishWordUtils.cpp
gfx/src/nsRect.h
gfx/thebes/gfxFT2FontBase.cpp
gfx/thebes/gfxFT2Utils.cpp
gfx/thebes/gfxFT2Utils.h
gfx/thebes/gfxFont.cpp
gfx/thebes/gfxFontUtils.h
gfx/thebes/gfxPlatformFontList.cpp
image/src/imgFrame.cpp
image/src/imgRequest.cpp
intl/unicharutil/util/nsUnicharUtils.cpp
js/xpconnect/src/XPCWrappedNative.cpp
js/xpconnect/src/nsXPConnect.cpp
layout/base/nsCSSFrameConstructor.cpp
layout/base/nsCounterManager.cpp
layout/base/nsCounterManager.h
layout/base/nsPresShell.cpp
layout/forms/nsComboboxControlFrame.cpp
layout/forms/nsFieldSetFrame.cpp
layout/generic/TextOverflow.cpp
layout/generic/TextOverflow.h
layout/generic/nsBlockFrame.cpp
layout/generic/nsFrame.h
layout/generic/nsFrameSetFrame.cpp
layout/generic/nsInlineFrame.cpp
layout/generic/nsLineBox.cpp
layout/generic/nsLineBox.h
layout/generic/nsTextFrameThebes.cpp
layout/mathml/nsMathMLContainerFrame.cpp
layout/mathml/nsMathMLContainerFrame.h
layout/style/nsCSSRuleProcessor.cpp
layout/style/nsCSSScanner.cpp
layout/style/nsCSSStyleSheet.cpp
layout/style/nsCSSValue.cpp
layout/style/nsRuleNode.cpp
layout/style/nsStyleAnimation.cpp
layout/style/nsStyleStruct.cpp
layout/tables/nsTableFrame.cpp
layout/xul/base/src/nsMenuFrame.cpp
layout/xul/base/src/nsSprocketLayout.cpp
layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
netwerk/base/public/nsReadLine.h
netwerk/base/src/nsSocketTransportService2.cpp
netwerk/cookie/nsCookieService.cpp
parser/html/nsHtml5TokenizerCppSupplement.h
parser/html/nsHtml5TreeBuilder.cpp
parser/html/nsHtml5TreeBuilderCppSupplement.h
parser/html/nsHtml5TreeOpExecutor.cpp
parser/html/nsHtml5TreeOperation.cpp
parser/htmlparser/src/nsHTMLTokenizer.cpp
security/manager/ssl/src/nsNTLMAuthModule.cpp
toolkit/components/places/SQLFunctions.cpp
toolkit/components/telemetry/Telemetry.cpp
toolkit/xre/nsAppRunner.cpp
view/src/nsView.cpp
widget/android/AndroidBridge.h
widget/gtk2/nsGtkIMModule.cpp
widget/gtk2/nsWindow.cpp
widget/qt/nsWindow.cpp
widget/xpwidgets/nsPrimitiveHelpers.cpp
xpcom/base/nsCycleCollector.cpp
xpcom/base/nsError.h
xpcom/base/nscore.h
xpcom/glue/nsCycleCollectionParticipant.h
xpcom/glue/nsDebug.h
xpcom/glue/nsISupportsImpl.h
xpcom/glue/nsProxyRelease.h
xpcom/glue/nsThreadUtils.cpp
xpcom/glue/nsThreadUtils.h
xpcom/glue/pldhash.cpp
xpcom/io/nsStorageStream.cpp
--- a/accessible/src/atk/AtkSocketAccessible.cpp
+++ b/accessible/src/atk/AtkSocketAccessible.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <atk/atk.h>
 #include "AtkSocketAccessible.h"
 
 #include "InterfaceInitFuncs.h"
 #include "nsMai.h"
+#include "mozilla/Likely.h"
 
 AtkSocketEmbedType AtkSocketAccessible::g_atk_socket_embed = NULL;
 GType AtkSocketAccessible::g_atk_socket_type = G_TYPE_INVALID;
 const char* AtkSocketAccessible::sATKSocketEmbedSymbol = "atk_socket_embed";
 const char* AtkSocketAccessible::sATKSocketGetTypeSymbol = "atk_socket_get_type";
 
 bool AtkSocketAccessible::gCanEmbed = FALSE;
 
@@ -100,17 +101,17 @@ GetExtents(AtkComponent* aComponent, gin
                    aX, aY, aWidth, aHeight, aCoordType);
 }
 }
 
 void
 mai_atk_component_iface_init(AtkComponentIface* aIface)
 {
   NS_ASSERTION(aIface, "Invalid Interface");
-  if (NS_UNLIKELY(!aIface))
+  if (MOZ_UNLIKELY(!aIface))
     return;
 
   aIface->ref_accessible_at_point = RefAccessibleAtPoint;
   aIface->get_extents = GetExtents;
 }
 
 AtkSocketAccessible::AtkSocketAccessible(nsIContent* aContent,
                                          DocAccessible* aDoc,
--- a/accessible/src/atk/nsMaiInterfaceAction.cpp
+++ b/accessible/src/atk/nsMaiInterfaceAction.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "InterfaceInitFuncs.h"
 
 #include "Accessible-inl.h"
 #include "nsMai.h"
 #include "Role.h"
+#include "mozilla/Likely.h"
 
 #include "nsString.h"
 
 using namespace mozilla::a11y;
 
 extern "C" {
 
 static gboolean
@@ -111,17 +112,17 @@ getKeyBindingCB(AtkAction *aAction, gint
   return AccessibleWrap::ReturnString(keyBindingsStr);
 }
 }
 
 void
 actionInterfaceInitCB(AtkActionIface* aIface)
 {
   NS_ASSERTION(aIface, "Invalid aIface");
-  if (NS_UNLIKELY(!aIface))
+  if (MOZ_UNLIKELY(!aIface))
     return;
 
   aIface->do_action = doActionCB;
   aIface->get_n_actions = getActionCountCB;
   aIface->get_description = getActionDescriptionCB;
   aIface->get_keybinding = getKeyBindingCB;
   aIface->get_name = getActionNameCB;
 }
--- a/accessible/src/atk/nsMaiInterfaceComponent.cpp
+++ b/accessible/src/atk/nsMaiInterfaceComponent.cpp
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "InterfaceInitFuncs.h"
 
 #include "AccessibleWrap.h"
 #include "nsAccUtils.h"
 #include "nsCoreUtils.h"
 #include "nsMai.h"
+#include "mozilla/Likely.h"
 
 extern "C" {
 
 static AtkObject*
 refAccessibleAtPointCB(AtkComponent* aComponent, gint aAccX, gint aAccY,
                        AtkCoordType aCoordType)
 {
   return refAccessibleAtPointHelper(GetAccessibleWrap(ATK_OBJECT(aComponent)),
@@ -95,17 +96,17 @@ getExtentsHelper(AccessibleWrap* aAccWra
   *aWidth = width;
   *aHeight = height;
 }
 
 void
 componentInterfaceInitCB(AtkComponentIface* aIface)
 {
   NS_ASSERTION(aIface, "Invalid Interface");
-  if(NS_UNLIKELY(!aIface))
+  if(MOZ_UNLIKELY(!aIface))
     return;
 
   /*
    * Use default implementation in atk for contains, get_position,
    * and get_size
    */
   aIface->ref_accessible_at_point = refAccessibleAtPointCB;
   aIface->get_extents = getExtentsCB;
--- a/accessible/src/atk/nsMaiInterfaceDocument.cpp
+++ b/accessible/src/atk/nsMaiInterfaceDocument.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "InterfaceInitFuncs.h"
 
 #include "AccessibleWrap.h"
 #include "DocAccessible.h"
 #include "nsMai.h"
+#include "mozilla/Likely.h"
 
 static const char* const kDocTypeName = "W3C-doctype";
 static const char* const kDocUrlName = "DocURL";
 static const char* const kMimeTypeName = "MimeType";
 
 // below functions are vfuncs on an ATK  interface so they need to be C call
 extern "C" {
 
@@ -21,17 +22,17 @@ static const gchar* getDocumentLocaleCB(
 static AtkAttributeSet* getDocumentAttributesCB(AtkDocument* aDocument);
 static const gchar* getDocumentAttributeValueCB(AtkDocument* aDocument,
                                                 const gchar* aAttrName);
 
 void
 documentInterfaceInitCB(AtkDocumentIface *aIface)
 {
     NS_ASSERTION(aIface, "Invalid Interface");
-    if(NS_UNLIKELY(!aIface))
+    if(MOZ_UNLIKELY(!aIface))
         return;
 
     /*
      * We don't support get_document or set_attribute right now.
      * get_document_type is deprecated, we return DocType in
      * get_document_attribute_value and get_document_attributes instead.
      */
     aIface->get_document_attributes = getDocumentAttributesCB;
--- a/accessible/src/atk/nsMaiInterfaceEditableText.cpp
+++ b/accessible/src/atk/nsMaiInterfaceEditableText.cpp
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "InterfaceInitFuncs.h"
 
 #include "HyperTextAccessible.h"
 #include "nsMai.h"
 
 #include "nsString.h"
+#include "mozilla/Likely.h"
 
 extern "C" {
 static void
 setTextContentsCB(AtkEditableText *aText, const gchar *aString)
 {
   AccessibleWrap* accWrap = GetAccessibleWrap(ATK_OBJECT(aText));
   if (!accWrap)
     return;
@@ -111,17 +112,17 @@ pasteTextCB(AtkEditableText *aText, gint
   text->PasteText(aPosition);
 }
 }
 
 void
 editableTextInterfaceInitCB(AtkEditableTextIface* aIface)
 {
   NS_ASSERTION(aIface, "Invalid aIface");
-  if (NS_UNLIKELY(!aIface))
+  if (MOZ_UNLIKELY(!aIface))
     return;
 
   aIface->set_text_contents = setTextContentsCB;
   aIface->insert_text = insertTextCB;
   aIface->copy_text = copyTextCB;
   aIface->cut_text = cutTextCB;
   aIface->delete_text = deleteTextCB;
   aIface->paste_text = pasteTextCB;
--- a/accessible/src/atk/nsMaiInterfaceHyperlinkImpl.cpp
+++ b/accessible/src/atk/nsMaiInterfaceHyperlinkImpl.cpp
@@ -2,16 +2,17 @@
 /* vim: set ts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "InterfaceInitFuncs.h"
 
 #include "nsMaiHyperlink.h"
+#include "mozilla/Likely.h"
 
 extern "C" {
 static AtkHyperlink*
 getHyperlinkCB(AtkHyperlinkImpl* aImpl)
 {
   AccessibleWrap* accWrap = GetAccessibleWrap(ATK_OBJECT(aImpl));
   if (!accWrap)
     return nullptr;
@@ -23,13 +24,13 @@ getHyperlinkCB(AtkHyperlinkImpl* aImpl)
   return maiHyperlink->GetAtkHyperlink();
 }
 }
 
 void
 hyperlinkImplInterfaceInitCB(AtkHyperlinkImplIface *aIface)
 {
   NS_ASSERTION(aIface, "no interface!");
-  if (NS_UNLIKELY(!aIface))
+  if (MOZ_UNLIKELY(!aIface))
     return;
 
   aIface->get_hyperlink = getHyperlinkCB;
 }
--- a/accessible/src/atk/nsMaiInterfaceHypertext.cpp
+++ b/accessible/src/atk/nsMaiInterfaceHypertext.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "InterfaceInitFuncs.h"
 
 #include "HyperTextAccessible.h"
 #include "nsMai.h"
 #include "nsMaiHyperlink.h"
+#include "mozilla/Likely.h"
 
 extern "C" {
 
 static AtkHyperlink*
 getLinkCB(AtkHypertext *aText, gint aLinkIndex)
 {
   AccessibleWrap* accWrap = GetAccessibleWrap(ATK_OBJECT(aText));
   if (!accWrap)
@@ -65,15 +66,15 @@ getLinkIndexCB(AtkHypertext *aText, gint
   return index;
 }
 }
 
 void
 hypertextInterfaceInitCB(AtkHypertextIface* aIface)
 {
   NS_ASSERTION(aIface, "no interface!");
-  if (NS_UNLIKELY(!aIface))
+  if (MOZ_UNLIKELY(!aIface))
     return;
 
   aIface->get_link = getLinkCB;
   aIface->get_n_links = getLinkCountCB;
   aIface->get_link_index = getLinkIndexCB;
 }
--- a/accessible/src/atk/nsMaiInterfaceImage.cpp
+++ b/accessible/src/atk/nsMaiInterfaceImage.cpp
@@ -3,16 +3,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "InterfaceInitFuncs.h"
 
 #include "AccessibleWrap.h"
 #include "ImageAccessible.h"
+#include "mozilla/Likely.h"
 #include "nsMai.h"
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 extern "C" {
 const gchar* getDescriptionCB(AtkObject* aAtkObj);
 
@@ -48,15 +49,15 @@ getImageSizeCB(AtkImage* aImage, gint* a
   accWrap->AsImage()->GetImageSize(aAccWidth, aAccHeight);
 }
 }
 
 void
 imageInterfaceInitCB(AtkImageIface* aIface)
 {
   NS_ASSERTION(aIface, "no interface!");
-  if (NS_UNLIKELY(!aIface))
+  if (MOZ_UNLIKELY(!aIface))
     return;
 
   aIface->get_image_position = getImagePositionCB;
   aIface->get_image_description = getImageDescriptionCB;
   aIface->get_image_size = getImageSizeCB;
 }
--- a/accessible/src/atk/nsMaiInterfaceSelection.cpp
+++ b/accessible/src/atk/nsMaiInterfaceSelection.cpp
@@ -3,16 +3,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "InterfaceInitFuncs.h"
 
 #include "AccessibleWrap.h"
 #include "nsMai.h"
+#include "mozilla/Likely.h"
 
 #include <atk/atk.h>
 
 extern "C" {
 
 static gboolean
 addSelectionCB(AtkSelection *aSelection, gint i)
 {
@@ -91,17 +92,17 @@ selectAllSelectionCB(AtkSelection *aSele
   return accWrap->SelectAll();
 }
 }
 
 void
 selectionInterfaceInitCB(AtkSelectionIface* aIface)
 {
   NS_ASSERTION(aIface, "Invalid aIface");
-  if (NS_UNLIKELY(!aIface))
+  if (MOZ_UNLIKELY(!aIface))
     return;
 
   aIface->add_selection = addSelectionCB;
   aIface->clear_selection = clearSelectionCB;
   aIface->ref_selection = refSelectionCB;
   aIface->get_selection_count = getSelectionCountCB;
   aIface->is_child_selected = isChildSelectedCB;
   aIface->remove_selection = removeSelectionCB;
--- a/accessible/src/atk/nsMaiInterfaceTable.cpp
+++ b/accessible/src/atk/nsMaiInterfaceTable.cpp
@@ -10,16 +10,18 @@
 #include "AccessibleWrap.h"
 #include "nsAccUtils.h"
 #include "TableAccessible.h"
 #include "TableCellAccessible.h"
 #include "nsMai.h"
 
 #include "nsArrayUtils.h"
 
+#include "mozilla/Likely.h"
+
 using namespace mozilla::a11y;
 
 extern "C" {
 static AtkObject*
 refAtCB(AtkTable* aTable, gint aRowIdx, gint aColIdx)
 {
   AccessibleWrap* accWrap = GetAccessibleWrap(ATK_OBJECT(aTable));
   if (!accWrap || aRowIdx < 0 || aColIdx < 0)
@@ -288,17 +290,17 @@ isCellSelectedCB(AtkTable *aTable, gint 
       IsCellSelected(aRowIdx, aColIdx));
 }
 }
 
 void
 tableInterfaceInitCB(AtkTableIface* aIface)
 {
   NS_ASSERTION(aIface, "no interface!");
-  if (NS_UNLIKELY(!aIface))
+  if (MOZ_UNLIKELY(!aIface))
     return;
 
   aIface->ref_at = refAtCB;
   aIface->get_index_at = getIndexAtCB;
   aIface->get_column_at_index = getColumnAtIndexCB;
   aIface->get_row_at_index = getRowAtIndexCB;
   aIface->get_n_columns = getColumnCountCB;
   aIface->get_n_rows = getRowCountCB;
--- a/accessible/src/atk/nsMaiInterfaceText.cpp
+++ b/accessible/src/atk/nsMaiInterfaceText.cpp
@@ -6,16 +6,18 @@
 
 #include "InterfaceInitFuncs.h"
 
 #include "HyperTextAccessible.h"
 #include "nsMai.h"
 
 #include "nsIPersistentProperties2.h"
 
+#include "mozilla/Likely.h"
+
 using namespace mozilla::a11y;
 
 AtkAttributeSet* ConvertToAtkAttributeSet(nsIPersistentProperties* aAttributes);
 
 static void
 ConvertTexttoAsterisks(AccessibleWrap* accWrap, nsAString& aString)
 {
   // convert each char to "*" when it's "password text" 
@@ -441,17 +443,17 @@ setCaretOffsetCB(AtkText *aText, gint aO
     return NS_SUCCEEDED(rv) ? TRUE : FALSE;
 }
 }
 
 void
 textInterfaceInitCB(AtkTextIface* aIface)
 {
   NS_ASSERTION(aIface, "Invalid aIface");
-  if (NS_UNLIKELY(!aIface))
+  if (MOZ_UNLIKELY(!aIface))
     return;
 
   aIface->get_text = getTextCB;
   aIface->get_text_after_offset = getTextAfterOffsetCB;
   aIface->get_text_at_offset = getTextAtOffsetCB;
   aIface->get_character_at_offset = getCharacterAtOffsetCB;
   aIface->get_text_before_offset = getTextBeforeOffsetCB;
   aIface->get_caret_offset = getCaretOffsetCB;
--- a/accessible/src/atk/nsMaiInterfaceValue.cpp
+++ b/accessible/src/atk/nsMaiInterfaceValue.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "InterfaceInitFuncs.h"
+#include "mozilla/Likely.h"
 
 #include "AccessibleWrap.h"
 #include "nsMai.h"
 
 extern "C" {
 
 static void
 getCurrentValueCB(AtkValue *obj, GValue *value)
@@ -111,17 +112,17 @@ setCurrentValueCB(AtkValue *obj, const G
     return !NS_FAILED(accValue->SetCurrentValue(accDouble));
 }
 }
 
 void
 valueInterfaceInitCB(AtkValueIface* aIface)
 {
   NS_ASSERTION(aIface, "Invalid aIface");
-  if (NS_UNLIKELY(!aIface))
+  if (MOZ_UNLIKELY(!aIface))
     return;
 
   aIface->get_current_value = getCurrentValueCB;
   aIface->get_maximum_value = getMaximumValueCB;
   aIface->get_minimum_value = getMinimumValueCB;
   aIface->get_minimum_increment = getMinimumIncrementCB;
   aIface->set_current_value = setCurrentValueCB;
 }
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -2,16 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsINode_h___
 #define nsINode_h___
 
 #include "mozilla/ErrorResult.h"
+#include "mozilla/Likely.h"
 #include "nsCOMPtr.h"               // for member, local
 #include "nsGkAtoms.h"              // for nsGkAtoms::baseURIProperty
 #include "nsIDOMEventTarget.h"      // for base class
 #include "nsIDOMNode.h"
 #include "nsIDOMNodeSelector.h"     // base class
 #include "nsINodeInfo.h"            // member (in nsCOMPtr)
 #include "nsIVariant.h"             // for use in GetUserData()
 #include "nsNodeInfoManager.h"      // for use in NodePrincipal()
@@ -733,17 +734,17 @@ public:
     return mNodeInfo->NodeInfoManager()->DocumentPrincipal();
   }
 
   /**
    * Get the parent nsIContent for this node.
    * @return the parent, or null if no parent or the parent is not an nsIContent
    */
   nsIContent* GetParent() const {
-    return NS_LIKELY(GetBoolFlag(ParentIsContent)) ?
+    return MOZ_LIKELY(GetBoolFlag(ParentIsContent)) ?
       reinterpret_cast<nsIContent*>(mParent) : nullptr;
   }
 
   /**
    * Get the parent nsINode for this node. This can be either an nsIContent,
    * an nsIDocument or an nsIAttribute.
    * @return the parent node
    */
--- a/content/base/src/FragmentOrElement.cpp
+++ b/content/base/src/FragmentOrElement.cpp
@@ -6,16 +6,17 @@
 
 /*
  * Base class for all element classes; this provides an implementation
  * of DOM Core's nsIDOMElement, implements nsIContent, provides
  * utility methods for subclasses, and so forth.
  */
 
 #include "mozilla/Util.h"
+#include "mozilla/Likely.h"
 
 #include "mozilla/dom/FragmentOrElement.h"
 
 #include "nsDOMAttribute.h"
 #include "nsDOMAttributeMap.h"
 #include "nsIAtom.h"
 #include "nsINodeInfo.h"
 #include "nsIDocument.h"
@@ -1552,17 +1553,17 @@ static const char* kNSURIs[] = {
   " (MathML)",
   " (RDF)",
   " (XUL)",
   " (SVG)",
   " (XML Events)"
 };
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(FragmentOrElement)
-  if (NS_UNLIKELY(cb.WantDebugInfo())) {
+  if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
     char name[512];
     uint32_t nsid = tmp->GetNameSpaceID();
     nsAtomCString localName(tmp->NodeInfo()->NameAtom());
     nsAutoCString uri;
     if (tmp->OwnerDoc()->GetDocumentURI()) {
       tmp->OwnerDoc()->GetDocumentURI()->GetSpec(uri);
     }
 
--- a/content/base/src/nsContentList.cpp
+++ b/content/base/src/nsContentList.cpp
@@ -16,16 +16,17 @@
 #include "nsIDocument.h"
 #include "nsGenericElement.h"
 #include "nsWrapperCacheInlines.h"
 #include "nsContentUtils.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsGkAtoms.h"
 #include "mozilla/dom/HTMLCollectionBinding.h"
 #include "mozilla/dom/NodeListBinding.h"
+#include "mozilla/Likely.h"
 
 // Form related includes
 #include "nsIDOMHTMLFormElement.h"
 
 #include "pldhash.h"
 
 #ifdef DEBUG_CONTENT_LIST
 #include "nsIContentIterator.h"
@@ -43,17 +44,17 @@ nsBaseContentList::~nsBaseContentList()
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsBaseContentList)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsBaseContentList)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSTARRAY(mElements)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsBaseContentList)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
   if (nsCCUncollectableMarker::sGeneration && tmp->IsBlack() &&
-      NS_LIKELY(!cb.WantAllTraces())) {
+      MOZ_LIKELY(!cb.WantAllTraces())) {
     return NS_SUCCESS_INTERRUPTED_TRAVERSE;
   }
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSTARRAY_OF_NSCOMPTR(mElements)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsBaseContentList)
   NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
 NS_IMPL_CYCLE_COLLECTION_TRACE_END
 
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -2,16 +2,17 @@
 /* vim: set ts=2 sw=2 et tw=78: */
 /* 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/. */
 
 /* A namespace class for static layout utilities. */
 
 #include "mozilla/Util.h"
+#include "mozilla/Likely.h"
 
 #include "jsapi.h"
 #include "jsdbgapi.h"
 #include "jsfriendapi.h"
 
 #include <math.h>
 
 #include "Layers.h"
@@ -5613,17 +5614,17 @@ nsContentUtils::GetSafeJSContext()
 }
 
 /* static */
 nsresult
 nsContentUtils::ASCIIToLower(nsAString& aStr)
 {
   PRUnichar* iter = aStr.BeginWriting();
   PRUnichar* end = aStr.EndWriting();
-  if (NS_UNLIKELY(!iter || !end)) {
+  if (MOZ_UNLIKELY(!iter || !end)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   while (iter != end) {
     PRUnichar c = *iter;
     if (c >= 'A' && c <= 'Z') {
       *iter = c + ('a' - 'A');
     }
     ++iter;
@@ -5634,17 +5635,17 @@ nsContentUtils::ASCIIToLower(nsAString& 
 /* static */
 nsresult
 nsContentUtils::ASCIIToLower(const nsAString& aSource, nsAString& aDest)
 {
   uint32_t len = aSource.Length();
   aDest.SetLength(len);
   if (aDest.Length() == len) {
     PRUnichar* dest = aDest.BeginWriting();
-    if (NS_UNLIKELY(!dest)) {
+    if (MOZ_UNLIKELY(!dest)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
     const PRUnichar* iter = aSource.BeginReading();
     const PRUnichar* end = aSource.EndReading();
     while (iter != end) {
       PRUnichar c = *iter;
       *dest = (c >= 'A' && c <= 'Z') ?
          c + ('a' - 'A') : c;
@@ -5657,17 +5658,17 @@ nsContentUtils::ASCIIToLower(const nsASt
 }
 
 /* static */
 nsresult
 nsContentUtils::ASCIIToUpper(nsAString& aStr)
 {
   PRUnichar* iter = aStr.BeginWriting();
   PRUnichar* end = aStr.EndWriting();
-  if (NS_UNLIKELY(!iter || !end)) {
+  if (MOZ_UNLIKELY(!iter || !end)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   while (iter != end) {
     PRUnichar c = *iter;
     if (c >= 'a' && c <= 'z') {
       *iter = c + ('A' - 'a');
     }
     ++iter;
@@ -5678,17 +5679,17 @@ nsContentUtils::ASCIIToUpper(nsAString& 
 /* static */
 nsresult
 nsContentUtils::ASCIIToUpper(const nsAString& aSource, nsAString& aDest)
 {
   uint32_t len = aSource.Length();
   aDest.SetLength(len);
   if (aDest.Length() == len) {
     PRUnichar* dest = aDest.BeginWriting();
-    if (NS_UNLIKELY(!dest)) {
+    if (MOZ_UNLIKELY(!dest)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
     const PRUnichar* iter = aSource.BeginReading();
     const PRUnichar* end = aSource.EndReading();
     while (iter != end) {
       PRUnichar c = *iter;
       *dest = (c >= 'a' && c <= 'z') ?
          c + ('A' - 'a') : c;
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /*
  * Base class for all our document implementations.
  */
 
 #include "mozilla/Util.h"
+#include "mozilla/Likely.h"
 
 #ifdef MOZ_LOGGING
 // so we can get logging even in release builds
 #define FORCE_PR_LOG 1
 #endif
 #include "prlog.h"
 #include "plstr.h"
 #include "prprf.h"
@@ -1584,17 +1585,17 @@ static const char* kNSURIs[] = {
   "(XSLT)",
   "(XBL)",
   "(MathML)",
   "(RDF)",
   "(XUL)"
 };
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsDocument)
-  if (NS_UNLIKELY(cb.WantDebugInfo())) {
+  if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
     char name[512];
     nsAutoCString loadedAsData;
     if (tmp->IsLoadedAsData()) {
       loadedAsData.AssignLiteral("data");
     } else {
       loadedAsData.AssignLiteral("normal");
     }
     uint32_t nsid = tmp->GetDefaultNamespaceID();
--- a/content/base/src/nsINode.cpp
+++ b/content/base/src/nsINode.cpp
@@ -8,16 +8,17 @@
  * Base class for all DOM nodes.
  */
 
 #include "nsINode.h"
 
 #include "jsapi.h"
 #include "mozAutoDocUpdate.h"
 #include "mozilla/CORSMode.h"
+#include "mozilla/Likely.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/Util.h"
 #include "nsAsyncDOMEvent.h"
 #include "nsAttrValueOrString.h"
 #include "nsBindingManager.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsClientRect.h"
 #include "nsContentCreatorFunctions.h"
@@ -1137,17 +1138,17 @@ nsINode::UnoptimizableCCNode() const
          (IsElement() &&
           AsElement()->IsInNamespace(kNameSpaceID_XBL));
 }
 
 /* static */
 bool
 nsINode::Traverse(nsINode *tmp, nsCycleCollectionTraversalCallback &cb)
 {
-  if (NS_LIKELY(!cb.WantAllTraces())) {
+  if (MOZ_LIKELY(!cb.WantAllTraces())) {
     nsIDocument *currentDoc = tmp->GetCurrentDoc();
     if (currentDoc &&
         nsCCUncollectableMarker::InGeneration(currentDoc->GetMarkedCCGeneration())) {
       return false;
     }
 
     if (nsCCUncollectableMarker::sGeneration) {
       // If we're black no need to traverse.
--- a/content/base/src/nsNodeInfo.cpp
+++ b/content/base/src/nsNodeInfo.cpp
@@ -5,16 +5,17 @@
 
 /*
  * Class that represents a prefix/namespace/localName triple; a single
  * nodeinfo is shared by all elements in a document that have that
  * prefix, namespace, and localName.
  */
 
 #include "mozilla/Util.h"
+#include "mozilla/Likely.h"
 
 #include "nscore.h"
 #include "nsNodeInfo.h"
 #include "nsNodeInfoManager.h"
 #include "nsCOMPtr.h"
 #include "nsString.h"
 #include "nsIAtom.h"
 #include "nsDOMString.h"
@@ -159,17 +160,17 @@ static const char* kNSURIs[] = {
   " (XSLT)",
   " (XBL)",
   " (MathML)",
   " (RDF)",
   " (XUL)"
 };
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsNodeInfo)
-  if (NS_UNLIKELY(cb.WantDebugInfo())) {
+  if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
     char name[72];
     uint32_t nsid = tmp->NamespaceID();
     nsAtomCString localName(tmp->NameAtom());
     if (nsid < ArrayLength(kNSURIs)) {
       PR_snprintf(name, sizeof(name), "nsNodeInfo%s %s", kNSURIs[nsid],
                   localName.get());
     }
     else {
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -25,16 +25,17 @@
 #include "nsGkAtoms.h"
 #include "nsContentUtils.h"
 #include "nsGenericDOMDataNode.h"
 #include "nsClientRect.h"
 #include "nsLayoutUtils.h"
 #include "nsTextFrame.h"
 #include "nsFontFaceList.h"
 #include "mozilla/Telemetry.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 
 /******************************************************
  * stack based utilty class for managing monitor
  ******************************************************/
 
 // NS_ERROR_DOM_NOT_OBJECT_ERR is not the correct one to throw, but spec doesn't say
@@ -390,17 +391,17 @@ nsRange::CharacterDataChanged(nsIDocumen
       // splitText(), aInfo->mDetails->mNextSibling is the new text node
       NS_ASSERTION(aInfo->mDetails->mType ==
                    CharacterDataChangeInfo::Details::eSplit,
                    "only a split can start before the end");
       NS_ASSERTION(static_cast<uint32_t>(mStartOffset) <= aInfo->mChangeEnd + 1,
                    "mStartOffset is beyond the end of this node");
       newStartOffset = static_cast<uint32_t>(mStartOffset) - aInfo->mChangeStart;
       newStartNode = aInfo->mDetails->mNextSibling;
-      if (NS_UNLIKELY(aContent == mRoot)) {
+      if (MOZ_UNLIKELY(aContent == mRoot)) {
         newRoot = IsValidBoundary(newStartNode);
       }
 
       bool isCommonAncestor = IsInSelection() && mStartParent == mEndParent;
       if (isCommonAncestor) {
         UnregisterCommonAncestor(mStartParent);
         RegisterCommonAncestor(newStartNode);
       }
@@ -452,24 +453,24 @@ nsRange::CharacterDataChanged(nsIDocumen
   if (aInfo->mDetails &&
       aInfo->mDetails->mType == CharacterDataChangeInfo::Details::eMerge) {
     // normalize(), aInfo->mDetails->mNextSibling is the merged text node
     // that will be removed
     nsIContent* removed = aInfo->mDetails->mNextSibling;
     if (removed == mStartParent) {
       newStartOffset = static_cast<uint32_t>(mStartOffset) + aInfo->mChangeStart;
       newStartNode = aContent;
-      if (NS_UNLIKELY(removed == mRoot)) {
+      if (MOZ_UNLIKELY(removed == mRoot)) {
         newRoot = IsValidBoundary(newStartNode);
       }
     }
     if (removed == mEndParent) {
       newEndOffset = static_cast<uint32_t>(mEndOffset) + aInfo->mChangeStart;
       newEndNode = aContent;
-      if (NS_UNLIKELY(removed == mRoot)) {
+      if (MOZ_UNLIKELY(removed == mRoot)) {
         newRoot = IsValidBoundary(newEndNode);
       }
     }
   }
   if (newStartNode || newEndNode) {
     if (!newStartNode) {
       newStartNode = mStartParent;
       newStartOffset = mStartOffset;
--- a/content/events/src/nsDOMEventTargetHelper.cpp
+++ b/content/events/src/nsDOMEventTargetHelper.cpp
@@ -8,25 +8,26 @@
 #include "nsEventDispatcher.h"
 #include "nsGUIEvent.h"
 #include "nsIDocument.h"
 #include "nsIJSContextStack.h"
 #include "nsDOMJSUtils.h"
 #include "prprf.h"
 #include "nsGlobalWindow.h"
 #include "nsDOMEvent.h"
+#include "mozilla/Likely.h"
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMEventTargetHelper)
 
 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsDOMEventTargetHelper)
   NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
 NS_IMPL_CYCLE_COLLECTION_TRACE_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsDOMEventTargetHelper)
-  if (NS_UNLIKELY(cb.WantDebugInfo())) {
+  if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
     char name[512];
     nsAutoString uri;
     if (tmp->mOwner && tmp->mOwner->GetExtantDocument()) {
       tmp->mOwner->GetExtantDocument()->GetDocumentURI(uri);
     }
     PR_snprintf(name, sizeof(name), "nsDOMEventTargetHelper %s",
                 NS_ConvertUTF16toUTF8(uri).get());
     cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name);
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set tw=80 expandtab softtabstop=2 ts=2 sw=2: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/Util.h"
+#include "mozilla/Likely.h"
 
 #include "nscore.h"
 #include "nsGenericHTMLElement.h"
 #include "nsAttrValueInlines.h"
 #include "nsCOMPtr.h"
 #include "nsIAtom.h"
 #include "nsIContentViewer.h"
 #include "mozilla/css/StyleRule.h"
@@ -1032,17 +1033,17 @@ StartElement(Element* aContent, StringBu
     // Bug 16988.  Yuck.
     if (localName == nsGkAtoms::br && tagNS == kNameSpaceID_XHTML &&
         attName == nsGkAtoms::type && attNs == kNameSpaceID_None &&
         StringBeginsWith(*attValue, NS_LITERAL_STRING("_moz"))) {
       delete attValue;
       continue;
     }
     
-    if (NS_LIKELY(attNs == kNameSpaceID_None) ||
+    if (MOZ_LIKELY(attNs == kNameSpaceID_None) ||
         (attNs == kNameSpaceID_XMLNS &&
          attName == nsGkAtoms::xmlns)) {
       aBuilder.Append(" ");
     } else if (attNs == kNameSpaceID_XML) {
       aBuilder.Append(" xml:");
     } else if (attNs == kNameSpaceID_XMLNS) {
       aBuilder.Append(" xmlns:");
     } else if (attNs == kNameSpaceID_XLink) {
@@ -2153,17 +2154,17 @@ nsGenericHTMLElement::ParseBackgroundAtt
     nsresult rv = nsContentUtils::NewURIWithDocumentCharset(
         getter_AddRefs(uri), aValue, doc, baseURI);
     if (NS_FAILED(rv)) {
       return false;
     }
 
     nsString value(aValue);
     nsRefPtr<nsStringBuffer> buffer = nsCSSValue::BufferFromString(value);
-    if (NS_UNLIKELY(!buffer)) {
+    if (MOZ_UNLIKELY(!buffer)) {
       return false;
     }
 
     mozilla::css::URLValue *url =
       new mozilla::css::URLValue(buffer, baseURI, uri, NodePrincipal());
     aResult.SetTo(url, &aValue);
     return true;
   }
--- a/content/svg/content/src/nsSVGSVGElement.cpp
+++ b/content/svg/content/src/nsSVGSVGElement.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/StandardInteger.h"
 #include "mozilla/Util.h"
+#include "mozilla/Likely.h"
 
 #include "nsGkAtoms.h"
 #include "nsLayoutUtils.h"
 #include "DOMSVGNumber.h"
 #include "DOMSVGLength.h"
 #include "nsSVGAngle.h"
 #include "nsCOMPtr.h"
 #include "nsIPresShell.h"
@@ -1324,17 +1325,17 @@ nsSVGSVGElement::
   SVGPreserveAspectRatio* pAROverridePtr = new SVGPreserveAspectRatio(aPAR);
   nsresult rv = SetProperty(nsGkAtoms::overridePreserveAspectRatio,
                             pAROverridePtr,
                             ReleasePreserveAspectRatioPropertyValue,
                             true);
   NS_ABORT_IF_FALSE(rv != NS_PROPTABLE_PROP_OVERWRITTEN,
                     "Setting override value when it's already set...?"); 
 
-  if (NS_UNLIKELY(NS_FAILED(rv))) {
+  if (MOZ_UNLIKELY(NS_FAILED(rv))) {
     // property-insertion failed (e.g. OOM in property-table code)
     delete pAROverridePtr;
     return false;
   }
   return true;
 }
 
 const SVGPreserveAspectRatio*
@@ -1438,17 +1439,17 @@ nsSVGSVGElement::SetViewBoxProperty(cons
   nsSVGViewBoxRect* pViewBoxOverridePtr = new nsSVGViewBoxRect(aViewBox);
   nsresult rv = SetProperty(nsGkAtoms::viewBox,
                             pViewBoxOverridePtr,
                             ReleaseViewBoxPropertyValue,
                             true);
   NS_ABORT_IF_FALSE(rv != NS_PROPTABLE_PROP_OVERWRITTEN,
                     "Setting override value when it's already set...?"); 
 
-  if (NS_UNLIKELY(NS_FAILED(rv))) {
+  if (MOZ_UNLIKELY(NS_FAILED(rv))) {
     // property-insertion failed (e.g. OOM in property-table code)
     delete pViewBoxOverridePtr;
     return false;
   }
   return true;
 }
 
 const nsSVGViewBoxRect*
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -548,16 +548,17 @@ using mozilla::dom::indexedDB::IDBWrappe
 #include "nsDebug.h"
 
 #ifdef MOZ_WEBRTC
 #include "nsIDOMDataChannel.h"
 #endif
 
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/dom/HTMLCollectionBinding.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 static NS_DEFINE_CID(kDOMSOF_CID, NS_DOM_SCRIPT_OBJECT_FACTORY_CID);
 
 static const char kDOMStringBundleURL[] =
   "chrome://global/locale/dom/dom.properties";
@@ -9172,17 +9173,17 @@ nsHTMLDocumentSH::DocumentAllTagsNewReso
 {
   if (JSID_IS_STRING(id)) {
     nsDocument *doc = GetDocument(obj);
 
     JSObject *proto;
     if (!::JS_GetPrototype(cx, obj, &proto)) {
       return JS_FALSE;
     }
-    if (NS_UNLIKELY(!proto)) {
+    if (MOZ_UNLIKELY(!proto)) {
       return JS_TRUE;
     }
 
     JSBool found;
     if (!::JS_HasPropertyById(cx, proto, id, &found)) {
       return JS_FALSE;
     }
 
@@ -9876,17 +9877,17 @@ nsHTMLPluginObjElementSH::GetProperty(ns
                                       jsval *vp, bool *_retval)
 {
   JSAutoRequest ar(cx);
 
   JSObject *pi_obj;
   if (!::JS_GetPrototype(cx, obj, &pi_obj)) {
     return NS_ERROR_UNEXPECTED;
   }
-  if (NS_UNLIKELY(!pi_obj)) {
+  if (MOZ_UNLIKELY(!pi_obj)) {
     return NS_OK;
   }
 
   JSBool found = false;
 
   if (!ObjectIsNativeWrapper(cx, obj)) {
     *_retval = ::JS_HasPropertyById(cx, pi_obj, id, &found);
     if (!*_retval) {
@@ -9908,17 +9909,17 @@ nsHTMLPluginObjElementSH::SetProperty(ns
                                       jsval *vp, bool *_retval)
 {
   JSAutoRequest ar(cx);
 
   JSObject *pi_obj;
   if (!::JS_GetPrototype(cx, obj, &pi_obj)) {
     return NS_ERROR_UNEXPECTED;
   }
-  if (NS_UNLIKELY(!pi_obj)) {
+  if (MOZ_UNLIKELY(!pi_obj)) {
     return NS_OK;
   }
 
   JSBool found = false;
 
   if (!ObjectIsNativeWrapper(cx, obj)) {
     *_retval = ::JS_HasPropertyById(cx, pi_obj, id, &found);
     if (!*_retval) {
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -37,16 +37,17 @@
 #include "jsfriendapi.h"        // for JS_GetGlobalForFrame
 #include "jswrapper.h"
 #include "nsReadableUtils.h"
 #include "nsDOMClassInfo.h"
 #include "nsJSEnvironment.h"
 #include "nsCharSeparatedTokenizer.h" // for Accept-Language parsing
 #include "nsUnicharUtils.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/Likely.h"
 
 // Other Classes
 #include "nsEventListenerManager.h"
 #include "nsEscape.h"
 #include "nsStyleCoord.h"
 #include "nsMimeTypeArray.h"
 #include "nsNetUtil.h"
 #include "nsICachingChannel.h"
@@ -1281,17 +1282,17 @@ NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_
   return tmp->IsBlackForCC();
 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END
 
 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(nsGlobalWindow)
   return tmp->IsBlackForCC();
 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsGlobalWindow)
-  if (NS_UNLIKELY(cb.WantDebugInfo())) {
+  if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
     char name[512];
     PR_snprintf(name, sizeof(name), "nsGlobalWindow #%ld", tmp->mWindowID);
     cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name);
   } else {
     NS_IMPL_CYCLE_COLLECTION_DESCRIBE(nsGlobalWindow, tmp->mRefCnt.get())
   }
 
   if (!cb.WantAllTraces() && tmp->IsBlackForCC()) {
--- a/dom/base/nsJSTimeoutHandler.cpp
+++ b/dom/base/nsJSTimeoutHandler.cpp
@@ -15,16 +15,17 @@
 #include "nsContentUtils.h"
 #include "nsJSEnvironment.h"
 #include "nsServiceManagerUtils.h"
 #include "nsError.h"
 #include "nsGlobalWindow.h"
 #include "nsIContentSecurityPolicy.h"
 #include "nsAlgorithm.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 
 static const char kSetIntervalStr[] = "setInterval";
 static const char kSetTimeoutStr[] = "setTimeout";
 
 // Our JS nsIScriptTimeoutHandler implementation.
 class nsJSScriptTimeoutHandler MOZ_FINAL : public nsIScriptTimeoutHandler
 {
 public:
@@ -71,17 +72,17 @@ private:
 
 // nsJSScriptTimeoutHandler
 // QueryInterface implementation for nsJSScriptTimeoutHandler
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSScriptTimeoutHandler)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsJSScriptTimeoutHandler)
   tmp->ReleaseJSObjects();
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsJSScriptTimeoutHandler)
-  if (NS_UNLIKELY(cb.WantDebugInfo())) {
+  if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
     nsAutoCString name("nsJSScriptTimeoutHandler");
     if (tmp->mExpr) {
       name.AppendLiteral(" [");
       name.Append(tmp->mFileName);
       name.AppendLiteral(":");
       name.AppendInt(tmp->mLineNo);
       name.AppendLiteral("]");
     }
--- a/dom/base/nsLocation.cpp
+++ b/dom/base/nsLocation.cpp
@@ -32,16 +32,17 @@
 #include "nsCRT.h"
 #include "nsIProtocolHandler.h"
 #include "nsReadableUtils.h"
 #include "nsITextToSubURI.h"
 #include "nsJSUtils.h"
 #include "jsfriendapi.h"
 #include "nsContentUtils.h"
 #include "nsEventStateManager.h"
+#include "mozilla/Likely.h"
 
 static nsresult
 GetDocumentCharacterSetForURI(const nsAString& aHref, nsACString& aCharset)
 {
   aCharset.Truncate();
 
   nsresult rv;
 
@@ -934,16 +935,16 @@ nsLocation::GetSourceBaseURL(JSContext* 
   return NS_OK;
 }
 
 bool
 nsLocation::CallerSubsumes()
 {
   // Get the principal associated with the location object.
   nsCOMPtr<nsIDOMWindow> outer = do_QueryReferent(mOuter);
-  if (NS_UNLIKELY(!outer))
+  if (MOZ_UNLIKELY(!outer))
     return false;
   nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(outer);
   bool subsumes = false;
   nsresult rv = nsContentUtils::GetSubjectPrincipal()->Subsumes(sop->GetPrincipal(), &subsumes);
   NS_ENSURE_SUCCESS(rv, false);
   return subsumes;
 }
--- a/dom/src/events/nsJSEventListener.cpp
+++ b/dom/src/events/nsJSEventListener.cpp
@@ -18,16 +18,17 @@
 #include "nsVariant.h"
 #include "nsIDOMBeforeUnloadEvent.h"
 #include "nsGkAtoms.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIJSContextStack.h"
 #include "xpcpublic.h"
 #include "nsJSEnvironment.h"
 #include "nsDOMJSUtils.h"
+#include "mozilla/Likely.h"
 #ifdef DEBUG
 
 #include "nspr.h" // PR_fprintf
 
 class EventListenerCounter
 {
 public:
   ~EventListenerCounter() {
@@ -66,17 +67,17 @@ NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSEvent
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsJSEventListener)
   if (tmp->mContext) {
     NS_DROP_JS_OBJECTS(tmp, nsJSEventListener);
     tmp->mScopeObject = nullptr;
     NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mContext)
   }
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsJSEventListener)
-  if (NS_UNLIKELY(cb.WantDebugInfo()) && tmp->mEventName) {
+  if (MOZ_UNLIKELY(cb.WantDebugInfo()) && tmp->mEventName) {
     nsAutoCString name;
     name.AppendLiteral("nsJSEventListener handlerName=");
     name.Append(
       NS_ConvertUTF16toUTF8(nsDependentAtomString(tmp->mEventName)).get());
     cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name.get());
   } else {
     NS_IMPL_CYCLE_COLLECTION_DESCRIBE(nsJSEventListener, tmp->mRefCnt.get())
   }
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -39,16 +39,17 @@
 #include "nsGUIEvent.h"
 #include "nsJSEnvironment.h"
 #include "nsJSUtils.h"
 #include "nsNetUtil.h"
 #include "nsSandboxFlags.h"
 #include "nsThreadUtils.h"
 #include "xpcpublic.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 
 #ifdef ANDROID
 #include <android/log.h>
 #endif
 
 #include "Events.h"
 #include "Exceptions.h"
 #include "File.h"
@@ -3673,17 +3674,17 @@ WorkerPrivate::SetTimeout(JSContext* aCx
   if (currentStatus >= Closing) {
     return false;
   }
 
   nsAutoPtr<TimeoutInfo> newInfo(new TimeoutInfo());
   newInfo->mIsInterval = aIsInterval;
   newInfo->mId = timerId;
 
-  if (NS_UNLIKELY(timerId == UINT32_MAX)) {
+  if (MOZ_UNLIKELY(timerId == UINT32_MAX)) {
     NS_WARNING("Timeout ids overflowed!");
     mNextTimeoutId = 1;
   }
 
   JS::Value* argv = JS_ARGV(aCx, aVp);
 
   // Take care of the main argument.
   if (argv[0].isObject()) {
--- a/editor/txmgr/tests/TestTXMgr.cpp
+++ b/editor/txmgr/tests/TestTXMgr.cpp
@@ -2,16 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "TestHarness.h"
 
 #include "nsITransactionManager.h"
 #include "nsComponentManagerUtils.h"
+#include "mozilla/Likely.h"
 
 static int32_t sConstructorCount     = 0;
 static int32_t sDestructorCount      = 0;
 static int32_t *sDestructorOrderArr  = 0;
 static int32_t sDoCount              = 0;
 static int32_t *sDoOrderArr          = 0;
 static int32_t sUndoCount            = 0;
 static int32_t *sUndoOrderArr        = 0;
@@ -4441,17 +4442,17 @@ stress_test(TestTransactionFactory *fact
       result = mgr->UndoTransaction();
       if (NS_FAILED(result)) {
         fail("Failed to undo transaction %d-%d. (%d)\n", i, j, result);
         return result;
       }
     }
 
     // Trivial feedback not to let the user think the test is stuck.
-    if (NS_UNLIKELY(j % 100 == 0))
+    if (MOZ_UNLIKELY(j % 100 == 0))
       printf("%i ", j);
   } // for, iterations.
 
   printf("passed\n");
 
   result = mgr->Clear();
   if (NS_FAILED(result)) {
     fail("Clear() failed. (%d)\n", result);
--- a/extensions/auth/nsHttpNegotiateAuth.cpp
+++ b/extensions/auth/nsHttpNegotiateAuth.cpp
@@ -31,16 +31,17 @@
 #include "nsString.h"
 #include "nsNetCID.h"
 #include "plbase64.h"
 #include "plstr.h"
 #include "prprf.h"
 #include "prlog.h"
 #include "prmem.h"
 #include "prnetdb.h"
+#include "mozilla/Likely.h"
 
 //-----------------------------------------------------------------------------
 
 static const char kNegotiate[] = "Negotiate";
 static const char kNegotiateAuthTrustedURIs[] = "network.negotiate-auth.trusted-uris";
 static const char kNegotiateAuthDelegationURIs[] = "network.negotiate-auth.delegation-uris";
 static const char kNegotiateAuthAllowProxies[] = "network.negotiate-auth.allow-proxies";
 static const char kNegotiateAuthAllowNonFqdn[] = "network.negotiate-auth.allow-non-fqdn";
@@ -270,17 +271,17 @@ nsHttpNegotiateAuth::GenerateCredentials
 
     if (!encoded_token)
         return NS_ERROR_OUT_OF_MEMORY;
 
     LOG(("  Sending a token of length %d\n", outTokenLen));
 
     // allocate a buffer sizeof("Negotiate" + " " + b64output_token + "\0")
     *creds = (char *) nsMemory::Alloc(kNegotiateLen + 1 + strlen(encoded_token) + 1);
-    if (NS_UNLIKELY(!*creds))
+    if (MOZ_UNLIKELY(!*creds))
         rv = NS_ERROR_OUT_OF_MEMORY;
     else
         sprintf(*creds, "%s %s", kNegotiate, encoded_token);
 
     PR_Free(encoded_token);
     return rv;
 }
 
--- a/extensions/spellcheck/src/mozEnglishWordUtils.cpp
+++ b/extensions/spellcheck/src/mozEnglishWordUtils.cpp
@@ -5,16 +5,17 @@
 
 #include "mozEnglishWordUtils.h"
 #include "nsReadableUtils.h"
 #include "nsIServiceManager.h"
 #include "nsUnicharUtils.h"
 #include "nsUnicharUtilCIID.h"
 #include "nsUnicodeProperties.h"
 #include "nsCRT.h"
+#include "mozilla/Likely.h"
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(mozEnglishWordUtils)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(mozEnglishWordUtils)
 
 NS_INTERFACE_MAP_BEGIN(mozEnglishWordUtils)
   NS_INTERFACE_MAP_ENTRY(mozISpellI18NUtil)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, mozISpellI18NUtil)
   NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(mozEnglishWordUtils)
@@ -242,17 +243,17 @@ NS_IMETHODIMP mozEnglishWordUtils::FromR
   PRUnichar **tmpPtr  = (PRUnichar **)nsMemory::Alloc(sizeof(PRUnichar *)*icount);
   if (!tmpPtr)
     return NS_ERROR_OUT_OF_MEMORY;
 
   mozEnglishWordUtils::myspCapitalization ct = captype(word);
   for(uint32_t i = 0; i < icount; ++i) {
     length = NS_strlen(iwords[i]);
     tmpPtr[i] = (PRUnichar *) nsMemory::Alloc(sizeof(PRUnichar) * (length + 1));
-    if (NS_UNLIKELY(!tmpPtr[i])) {
+    if (MOZ_UNLIKELY(!tmpPtr[i])) {
       NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(i, tmpPtr);
       return NS_ERROR_OUT_OF_MEMORY;
     }
     memcpy(tmpPtr[i], iwords[i], (length + 1) * sizeof(PRUnichar));
 
     nsAutoString capTest(tmpPtr[i]);
     mozEnglishWordUtils::myspCapitalization newCt=captype(capTest);
     if(newCt == NoCap){
--- a/gfx/src/nsRect.h
+++ b/gfx/src/nsRect.h
@@ -10,16 +10,17 @@
 #include <stdio.h>
 #include "nsCoord.h"
 #include "nsPoint.h"
 #include "nsSize.h"
 #include "nsMargin.h"
 #include "gfxCore.h"
 #include "nsTraceRefcnt.h"
 #include "mozilla/gfx/BaseRect.h"
+#include "mozilla/Likely.h"
 
 struct nsIntRect;
 
 struct NS_GFX nsRect :
   public mozilla::gfx::BaseRect<nscoord, nsRect, nsPoint, nsSize, nsMargin> {
   typedef mozilla::gfx::BaseRect<nscoord, nsRect, nsPoint, nsSize, nsMargin> Super;
 
   static void VERIFY_COORD(nscoord aValue) { ::VERIFY_COORD(aValue); }
@@ -54,51 +55,51 @@ struct NS_GFX nsRect :
   // width & height is capped at the maximum value nscoord_MAX.
   void SaturatingInflate(const nsMargin& aMargin)
   {
 #ifdef NS_COORD_IS_FLOAT
     Inflate(aMargin);
 #else
     int64_t nx = int64_t(x) - aMargin.left;
     int64_t w = int64_t(width) + int64_t(aMargin.left) + aMargin.right;
-    if (NS_UNLIKELY(w > nscoord_MAX)) {
+    if (MOZ_UNLIKELY(w > nscoord_MAX)) {
       NS_WARNING("Overflowed nscoord_MAX in conversion to nscoord width");
       int64_t xdiff = nx - nscoord_MIN / 2;
       if (xdiff < 0) {
         // Clamp huge negative x to nscoord_MIN / 2 and try again.
         nx = nscoord_MIN / 2;
         w += xdiff;
       }
-      if (NS_UNLIKELY(w > nscoord_MAX)) {
+      if (MOZ_UNLIKELY(w > nscoord_MAX)) {
         w = nscoord_MAX;
       }
     }
     width = nscoord(w);
-    if (NS_UNLIKELY(nx < nscoord_MIN)) {
+    if (MOZ_UNLIKELY(nx < nscoord_MIN)) {
       NS_WARNING("Underflowed nscoord_MIN in conversion to nscoord x");
       nx = nscoord_MIN;
     }
     x = nscoord(nx);
 
     int64_t ny = int64_t(y) - aMargin.top;
     int64_t h = int64_t(height) + int64_t(aMargin.top) + aMargin.bottom;
-    if (NS_UNLIKELY(h > nscoord_MAX)) {
+    if (MOZ_UNLIKELY(h > nscoord_MAX)) {
       NS_WARNING("Overflowed nscoord_MAX in conversion to nscoord height");
       int64_t ydiff = ny - nscoord_MIN / 2;
       if (ydiff < 0) {
         // Clamp huge negative y to nscoord_MIN / 2 and try again.
         ny = nscoord_MIN / 2;
         h += ydiff;
       }
-      if (NS_UNLIKELY(h > nscoord_MAX)) {
+      if (MOZ_UNLIKELY(h > nscoord_MAX)) {
         h = nscoord_MAX;
       }
     }
     height = nscoord(h);
-    if (NS_UNLIKELY(ny < nscoord_MIN)) {
+    if (MOZ_UNLIKELY(ny < nscoord_MIN)) {
       NS_WARNING("Underflowed nscoord_MIN in conversion to nscoord y");
       ny = nscoord_MIN;
     }
     y = nscoord(ny);
 #endif
   }
 
   // We have saturating versions of all the Union methods. These avoid
@@ -119,35 +120,35 @@ struct NS_GFX nsRect :
   nsRect SaturatingUnionEdges(const nsRect& aRect) const
   {
 #ifdef NS_COORD_IS_FLOAT
     return UnionEdges(aRect);
 #else
     nsRect result;
     result.x = NS_MIN(aRect.x, x);
     int64_t w = NS_MAX(int64_t(aRect.x) + aRect.width, int64_t(x) + width) - result.x;
-    if (NS_UNLIKELY(w > nscoord_MAX)) {
+    if (MOZ_UNLIKELY(w > nscoord_MAX)) {
       NS_WARNING("Overflowed nscoord_MAX in conversion to nscoord width");
       // Clamp huge negative x to nscoord_MIN / 2 and try again.
       result.x = NS_MAX(result.x, nscoord_MIN / 2);
       w = NS_MAX(int64_t(aRect.x) + aRect.width, int64_t(x) + width) - result.x;
-      if (NS_UNLIKELY(w > nscoord_MAX)) {
+      if (MOZ_UNLIKELY(w > nscoord_MAX)) {
         w = nscoord_MAX;
       }
     }
     result.width = nscoord(w);
 
     result.y = NS_MIN(aRect.y, y);
     int64_t h = NS_MAX(int64_t(aRect.y) + aRect.height, int64_t(y) + height) - result.y;
-    if (NS_UNLIKELY(h > nscoord_MAX)) {
+    if (MOZ_UNLIKELY(h > nscoord_MAX)) {
       NS_WARNING("Overflowed nscoord_MAX in conversion to nscoord height");
       // Clamp huge negative y to nscoord_MIN / 2 and try again.
       result.y = NS_MAX(result.y, nscoord_MIN / 2);
       h = NS_MAX(int64_t(aRect.y) + aRect.height, int64_t(y) + height) - result.y;
-      if (NS_UNLIKELY(h > nscoord_MAX)) {
+      if (MOZ_UNLIKELY(h > nscoord_MAX)) {
         h = nscoord_MAX;
       }
     }
     result.height = nscoord(h);
     return result;
 #endif
   }
 
--- a/gfx/thebes/gfxFT2FontBase.cpp
+++ b/gfx/thebes/gfxFT2FontBase.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 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 "gfxFT2FontBase.h"
 #include "gfxFT2Utils.h"
 #include "harfbuzz/hb.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla::gfx;
 
 gfxFT2FontBase::gfxFT2FontBase(cairo_scaled_font_t *aScaledFont,
                                gfxFontEntry *aFontEntry,
                                const gfxFontStyle *aFontStyle)
     : gfxFont(aFontEntry, aFontStyle, kAntialiasDefault, aScaledFont),
       mSpaceGlyph(0),
@@ -105,17 +106,17 @@ gfxFT2FontBase::GetGlyphExtents(uint32_t
 }
 
 const gfxFont::Metrics&
 gfxFT2FontBase::GetMetrics()
 {
     if (mHasMetrics)
         return mMetrics;
 
-    if (NS_UNLIKELY(GetStyle()->size <= 0.0)) {
+    if (MOZ_UNLIKELY(GetStyle()->size <= 0.0)) {
         new(&mMetrics) gfxFont::Metrics(); // zero initialize
         mSpaceGlyph = 0;
     } else {
         gfxFT2LockedFace(this).GetMetrics(&mMetrics, &mSpaceGlyph);
     }
 
     SanitizeMetrics(&mMetrics, false);
 
--- a/gfx/thebes/gfxFT2Utils.cpp
+++ b/gfx/thebes/gfxFT2Utils.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 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 "gfxFT2FontBase.h"
 #include "gfxFT2Utils.h"
+#include "mozilla/Likely.h"
 #include FT_TRUETYPE_TAGS_H
 #include FT_TRUETYPE_TABLES_H
 
 #ifdef HAVE_FONTCONFIG_FCFREETYPE_H
 #include <fontconfig/fcfreetype.h>
 #endif
 
 #include "prlink.h"
@@ -43,17 +44,17 @@ SnapLineToPixels(gfxFloat& aOffset, gfxF
 
 void
 gfxFT2LockedFace::GetMetrics(gfxFont::Metrics* aMetrics,
                              uint32_t* aSpaceGlyph)
 {
     NS_PRECONDITION(aMetrics != NULL, "aMetrics must not be NULL");
     NS_PRECONDITION(aSpaceGlyph != NULL, "aSpaceGlyph must not be NULL");
 
-    if (NS_UNLIKELY(!mFace)) {
+    if (MOZ_UNLIKELY(!mFace)) {
         // No face.  This unfortunate situation might happen if the font
         // file is (re)moved at the wrong time.
         aMetrics->emHeight = mGfxFont->GetStyle()->size;
         aMetrics->emAscent = 0.8 * aMetrics->emHeight;
         aMetrics->emDescent = 0.2 * aMetrics->emHeight;
         aMetrics->maxAscent = aMetrics->emAscent;
         aMetrics->maxDescent = aMetrics->maxDescent;
         aMetrics->maxHeight = aMetrics->emHeight;
@@ -262,17 +263,17 @@ gfxFT2LockedFace::GetMetrics(gfxFont::Me
     aMetrics->emAscent = sum > 0.0 ?
         aMetrics->emAscent * aMetrics->emHeight / sum : 0.0;
     aMetrics->emDescent = aMetrics->emHeight - aMetrics->emAscent;
 }
 
 uint32_t
 gfxFT2LockedFace::GetGlyph(uint32_t aCharCode)
 {
-    if (NS_UNLIKELY(!mFace))
+    if (MOZ_UNLIKELY(!mFace))
         return 0;
 
 #ifdef HAVE_FONTCONFIG_FCFREETYPE_H
     // FcFreeTypeCharIndex will search starting from the most recently
     // selected charmap.  This can cause non-determistic behavior when more
     // than one charmap supports a character but with different glyphs, as
     // with older versions of MS Gothic, for example.  Always prefer a Unicode
     // charmap, if there is one.  (FcFreeTypeCharIndex usually does the
@@ -292,17 +293,17 @@ typedef FT_UInt (*GetCharVariantFunction
                                           FT_ULong charcode,
                                           FT_ULong variantSelector);
 
 uint32_t
 gfxFT2LockedFace::GetUVSGlyph(uint32_t aCharCode, uint32_t aVariantSelector)
 {
     NS_PRECONDITION(aVariantSelector, "aVariantSelector should not be NULL");
 
-    if (NS_UNLIKELY(!mFace))
+    if (MOZ_UNLIKELY(!mFace))
         return 0;
 
     // This function is available from FreeType 2.3.6 (June 2008).
     static CharVariantFunction sGetCharVariantPtr = FindCharVariantFunction();
     if (!sGetCharVariantPtr)
         return 0;
 
 #ifdef HAVE_FONTCONFIG_FCFREETYPE_H
@@ -323,22 +324,22 @@ gfxFT2LockedFace::GetFontTable(uint32_t 
         return false;
 
     FT_ULong length = 0;
     // TRUETYPE_TAG is defined equivalent to FT_MAKE_TAG
     FT_Error error = FT_Load_Sfnt_Table(mFace, aTag, 0, NULL, &length);
     if (error != 0)
         return false;
 
-    if (NS_UNLIKELY(length > static_cast<FallibleTArray<uint8_t>::size_type>(-1))
-        || NS_UNLIKELY(!aBuffer.SetLength(length)))
+    if (MOZ_UNLIKELY(length > static_cast<FallibleTArray<uint8_t>::size_type>(-1))
+        || MOZ_UNLIKELY(!aBuffer.SetLength(length)))
         return false;
         
     error = FT_Load_Sfnt_Table(mFace, aTag, 0, aBuffer.Elements(), &length);
-    if (NS_UNLIKELY(error != 0)) {
+    if (MOZ_UNLIKELY(error != 0)) {
         aBuffer.Clear();
         return false;
     }
 
     return true;
 }
 
 uint32_t
--- a/gfx/thebes/gfxFT2Utils.h
+++ b/gfx/thebes/gfxFT2Utils.h
@@ -3,16 +3,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef GFX_FT2UTILS_H
 #define GFX_FT2UTILS_H
 
 #include "cairo-ft.h"
 #include "gfxFT2FontBase.h"
+#include "mozilla/Likely.h"
 
 // Rounding and truncation functions for a FreeType fixed point number 
 // (FT26Dot6) stored in a 32bit integer with high 26 bits for the integer
 // part and low 6 bits for the fractional part. 
 #define FLOAT_FROM_26_6(x) ((x) / 64.0)
 #define FLOAT_FROM_16_16(x) ((x) / 65536.0)
 #define ROUND_26_6_TO_INT(x) ((x) >= 0 ?  ((32 + (x)) >> 6) \
                                        : -((32 - (x)) >> 6))
@@ -48,17 +49,17 @@ public:
     void GetMetrics(gfxFont::Metrics* aMetrics, uint32_t* aSpaceGlyph);
 
     bool GetFontTable(uint32_t aTag, FallibleTArray<uint8_t>& aBuffer);
 
     // A scale factor for use in converting horizontal metrics from font units
     // to pixels.
     gfxFloat XScale()
     {
-        if (NS_UNLIKELY(!mFace))
+        if (MOZ_UNLIKELY(!mFace))
             return 0.0;
 
         const FT_Size_Metrics& ftMetrics = mFace->size->metrics;
 
         if (FT_IS_SCALABLE(mFace)) {
             // Prefer FT_Size_Metrics::x_scale to x_ppem as x_ppem does not
             // have subpixel accuracy.
             //
--- a/gfx/thebes/gfxFont.cpp
+++ b/gfx/thebes/gfxFont.cpp
@@ -26,16 +26,17 @@
 #include "gfxPlatformFontList.h"
 #include "gfxScriptItemizer.h"
 #include "nsUnicodeProperties.h"
 #include "nsMathUtils.h"
 #include "nsBidiUtils.h"
 #include "nsUnicodeRange.h"
 #include "nsStyleConsts.h"
 #include "mozilla/FloatingPoint.h"
+#include "mozilla/Likely.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
 #include "mozilla/Telemetry.h"
 #include "gfxSVGGlyphs.h"
 
 #include "cairo.h"
 #include "gfxFontTest.h"
 
@@ -419,24 +420,24 @@ gfxFontEntry::GetExistingFontTable(uint3
     *aBlob = entry->GetBlob();
     return true;
 }
 
 hb_blob_t *
 gfxFontEntry::ShareFontTableAndGetBlob(uint32_t aTag,
                                        FallibleTArray<uint8_t>* aBuffer)
 {
-    if (NS_UNLIKELY(!mFontTableCache.IsInitialized())) {
+    if (MOZ_UNLIKELY(!mFontTableCache.IsInitialized())) {
         // we do this here rather than on fontEntry construction
         // because not all shapers will access the table cache at all
         mFontTableCache.Init(10);
     }
 
     FontTableHashEntry *entry = mFontTableCache.PutEntry(aTag);
-    if (NS_UNLIKELY(!entry)) { // OOM
+    if (MOZ_UNLIKELY(!entry)) { // OOM
         return nullptr;
     }
 
     if (!aBuffer) {
         // ensure the entry is null
         entry->Clear();
         return nullptr;
     }
@@ -838,17 +839,17 @@ gfxFontFamily::FindFontForChar(GlobalFon
         int32_t rank = 0;
 
         if (fe->TestCharacterMap(aMatchData->mCh)) {
             rank += RANK_MATCHED_CMAP;
             aMatchData->mCount++;
 #ifdef PR_LOGGING
             PRLogModuleInfo *log = gfxPlatform::GetLog(eGfxLog_textrun);
 
-            if (NS_UNLIKELY(log)) {
+            if (MOZ_UNLIKELY(log)) {
                 uint32_t charRange = gfxFontUtils::CharRangeBit(aMatchData->mCh);
                 uint32_t unicodeRange = FindCharUnicodeRange(aMatchData->mCh);
                 uint32_t script = GetScriptCode(aMatchData->mCh);
                 PR_LOG(log, PR_LOG_DEBUG,\
                        ("(textrun-systemfallback-fonts) char: u+%6.6x "
                         "char-range: %d unicode-range: %d script: %d match: [%s]\n",
                         aMatchData->mCh,
                         charRange, unicodeRange, script,
@@ -1750,17 +1751,17 @@ gfxFont::Draw(gfxTextRun *aTextRun, uint
     double x = aPt->x;
     double y = aPt->y;
 
     cairo_t *cr = aContext->GetCairo();
     RefPtr<DrawTarget> dt = aContext->GetDrawTarget();
 
     if (aContext->IsCairo()) {
       bool success = SetupCairoFont(aContext);
-      if (NS_UNLIKELY(!success))
+      if (MOZ_UNLIKELY(!success))
           return;
 
       ::GlyphBuffer glyphs;
       cairo_glyph_t *glyph;
 
       if (aSpacing) {
           x += direction*aSpacing[0].mBefore;
       }
@@ -3473,17 +3474,17 @@ gfxFontGroup::MakeSpaceTextRun(const Par
     aFlags |= TEXT_IS_8BIT | TEXT_IS_ASCII | TEXT_IS_PERSISTENT;
 
     gfxTextRun *textRun = gfxTextRun::Create(aParams, 1, this, aFlags);
     if (!textRun) {
         return nullptr;
     }
 
     gfxFont *font = GetFontAt(0);
-    if (NS_UNLIKELY(GetStyle()->size == 0)) {
+    if (MOZ_UNLIKELY(GetStyle()->size == 0)) {
         // Short-circuit for size-0 fonts, as Windows and ATSUI can't handle
         // them, and always create at least size 1 fonts, i.e. they still
         // render something for size 0 fonts.
         textRun->AddGlyphRun(font, gfxTextRange::kFontGroup, 0, false);
     }
     else {
         textRun->SetSpaceGlyph(font, aParams->mContext, 0);
     }
@@ -3634,17 +3635,17 @@ gfxFontGroup::InitTextRun(gfxContext *aC
                                 gfxPlatform::GetLog(eGfxLog_textrun));
 #endif
 
         uint32_t runStart = 0, runLimit = aLength;
         int32_t runScript = MOZ_SCRIPT_LATIN;
         while (scriptRuns.Next(runStart, runLimit, runScript)) {
 
 #ifdef PR_LOGGING
-            if (NS_UNLIKELY(log)) {
+            if (MOZ_UNLIKELY(log)) {
                 nsAutoCString lang;
                 mStyle.language->ToUTF8String(lang);
                 uint32_t runLen = runLimit - runStart;
                 PR_LOG(log, PR_LOG_WARNING,\
                        ("(%s) fontgroup: [%s] lang: %s script: %d len %d "
                         "weight: %d width: %d style: %s "
                         "TEXTRUN [%s] ENDTEXTRUN\n",
                         (mStyle.systemFont ? "textrunui" : "textrun"),
--- a/gfx/thebes/gfxFontUtils.h
+++ b/gfx/thebes/gfxFontUtils.h
@@ -17,16 +17,17 @@
 #include "nsITimer.h"
 #include "nsCOMPtr.h"
 #include "nsIRunnable.h"
 #include "nsThreadUtils.h"
 #include "nsComponentManagerUtils.h"
 #include "nsTArray.h"
 #include "nsAutoPtr.h"
 #include "nsIStreamBufferAccess.h"
+#include "mozilla/Likely.h"
 
 #include "zlib.h"
 
 /* Bug 341128 - w32api defines min/max which causes problems with <bitset> */
 #ifdef __MINGW32__
 #undef min
 #undef max
 #endif
@@ -149,17 +150,17 @@ public:
         
         return false;
     }
     
     void set(uint32_t aIndex) {
         uint32_t blockIndex = aIndex/BLOCK_SIZE_BITS;
         if (blockIndex >= mBlocks.Length()) {
             nsAutoPtr<Block> *blocks = mBlocks.AppendElements(blockIndex + 1 - mBlocks.Length());
-            if (NS_UNLIKELY(!blocks)) // OOM
+            if (MOZ_UNLIKELY(!blocks)) // OOM
                 return;
         }
         Block *block = mBlocks[blockIndex];
         if (!block) {
             block = new Block;
             mBlocks[blockIndex] = block;
         }
         block->mBits[(aIndex>>3) & (BLOCK_SIZE - 1)] |= 1 << (aIndex & 0x7);
@@ -174,17 +175,17 @@ public:
 
     void SetRange(uint32_t aStart, uint32_t aEnd) {
         const uint32_t startIndex = aStart/BLOCK_SIZE_BITS;
         const uint32_t endIndex = aEnd/BLOCK_SIZE_BITS;
 
         if (endIndex >= mBlocks.Length()) {
             uint32_t numNewBlocks = endIndex + 1 - mBlocks.Length();
             nsAutoPtr<Block> *blocks = mBlocks.AppendElements(numNewBlocks);
-            if (NS_UNLIKELY(!blocks)) // OOM
+            if (MOZ_UNLIKELY(!blocks)) // OOM
                 return;
         }
 
         for (uint32_t i = startIndex; i <= endIndex; ++i) {
             const uint32_t blockFirstBit = i * BLOCK_SIZE_BITS;
             const uint32_t blockLastBit = blockFirstBit + BLOCK_SIZE_BITS - 1;
 
             Block *block = mBlocks[i];
@@ -208,34 +209,34 @@ public:
             }
         }
     }
 
     void clear(uint32_t aIndex) {
         uint32_t blockIndex = aIndex/BLOCK_SIZE_BITS;
         if (blockIndex >= mBlocks.Length()) {
             nsAutoPtr<Block> *blocks = mBlocks.AppendElements(blockIndex + 1 - mBlocks.Length());
-            if (NS_UNLIKELY(!blocks)) // OOM
+            if (MOZ_UNLIKELY(!blocks)) // OOM
                 return;
         }
         Block *block = mBlocks[blockIndex];
         if (!block) {
             return;
         }
         block->mBits[(aIndex>>3) & (BLOCK_SIZE - 1)] &= ~(1 << (aIndex & 0x7));
     }
 
     void ClearRange(uint32_t aStart, uint32_t aEnd) {
         const uint32_t startIndex = aStart/BLOCK_SIZE_BITS;
         const uint32_t endIndex = aEnd/BLOCK_SIZE_BITS;
 
         if (endIndex >= mBlocks.Length()) {
             uint32_t numNewBlocks = endIndex + 1 - mBlocks.Length();
             nsAutoPtr<Block> *blocks = mBlocks.AppendElements(numNewBlocks);
-            if (NS_UNLIKELY(!blocks)) // OOM
+            if (MOZ_UNLIKELY(!blocks)) // OOM
                 return;
         }
 
         for (uint32_t i = startIndex; i <= endIndex; ++i) {
             const uint32_t blockFirstBit = i * BLOCK_SIZE_BITS;
 
             Block *block = mBlocks[i];
             if (!block) {
@@ -276,17 +277,17 @@ public:
 
     // set this bitset to the union of its current contents and another
     void Union(const gfxSparseBitSet& aBitset) {
         // ensure mBlocks is large enough
         uint32_t blockCount = aBitset.mBlocks.Length();
         if (blockCount > mBlocks.Length()) {
             uint32_t needed = blockCount - mBlocks.Length();
             nsAutoPtr<Block> *blocks = mBlocks.AppendElements(needed);
-            if (NS_UNLIKELY(!blocks)) { // OOM
+            if (MOZ_UNLIKELY(!blocks)) { // OOM
                 return;
             }
         }
         // for each block that may be present in aBitset...
         for (uint32_t i = 0; i < blockCount; ++i) {
             // if it is missing (implicitly empty), just skip
             if (!aBitset.mBlocks[i]) {
                 continue;
--- a/gfx/thebes/gfxPlatformFontList.cpp
+++ b/gfx/thebes/gfxPlatformFontList.cpp
@@ -9,20 +9,21 @@
 #include "prlog.h"
 
 #include "gfxPlatformFontList.h"
 
 #include "nsUnicharUtils.h"
 #include "nsUnicodeRange.h"
 #include "nsUnicodeProperties.h"
 
+#include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/TimeStamp.h"
-#include "mozilla/Attributes.h"
 
 using namespace mozilla;
 
 // font info loader constants
 static const uint32_t kDelayBeforeLoadingCmaps = 8 * 1000; // 8secs
 static const uint32_t kIntervalBetweenLoadingCmaps = 150; // 150ms
 static const uint32_t kNumFontsPerSlice = 10; // read in info 10 fonts at a time
 
@@ -416,17 +417,17 @@ gfxPlatformFontList::SystemFindFontForCh
         common = false;
         fontEntry = GlobalFontFallback(aCh, aRunScript, aStyle, cmapCount);
     }
     TimeDuration elapsed = TimeStamp::Now() - start;
 
 #ifdef PR_LOGGING
     PRLogModuleInfo *log = gfxPlatform::GetLog(eGfxLog_textrun);
 
-    if (NS_UNLIKELY(log)) {
+    if (MOZ_UNLIKELY(log)) {
         uint32_t charRange = gfxFontUtils::CharRangeBit(aCh);
         uint32_t unicodeRange = FindCharUnicodeRange(aCh);
         int32_t script = mozilla::unicode::GetScriptCode(aCh);
         PR_LOG(log, PR_LOG_WARNING,\
                ("(textrun-systemfallback-%s) char: u+%6.6x "
                  "char-range: %d unicode-range: %d script: %d match: [%s]"
                 " time: %dus cmaps: %d\n",
                 (common ? "common" : "global"), aCh,
--- a/image/src/imgFrame.cpp
+++ b/image/src/imgFrame.cpp
@@ -13,16 +13,17 @@
 
 #include "gfxPlatform.h"
 #include "gfxUtils.h"
 
 static bool gDisableOptimize = false;
 
 #include "cairo.h"
 #include "sampler.h"
+#include "mozilla/Likely.h"
 
 #if defined(XP_WIN)
 
 #include "gfxWindowsPlatform.h"
 
 /* Whether to use the windows surface; only for desktop win32 */
 #define USE_WIN_SURFACE 1
 
@@ -37,40 +38,40 @@ static uint32_t gTotalDDBSize = 0;
 
 using namespace mozilla::image;
 
 // Returns true if an image of aWidth x aHeight is allowed and legal.
 static bool AllowedImageSize(int32_t aWidth, int32_t aHeight)
 {
   // reject over-wide or over-tall images
   const int32_t k64KLimit = 0x0000FFFF;
-  if (NS_UNLIKELY(aWidth > k64KLimit || aHeight > k64KLimit )) {
+  if (MOZ_UNLIKELY(aWidth > k64KLimit || aHeight > k64KLimit )) {
     NS_WARNING("image too big");
     return false;
   }
 
   // protect against invalid sizes
-  if (NS_UNLIKELY(aHeight <= 0 || aWidth <= 0)) {
+  if (MOZ_UNLIKELY(aHeight <= 0 || aWidth <= 0)) {
     return false;
   }
 
   // check to make sure we don't overflow a 32-bit
   int32_t tmp = aWidth * aHeight;
-  if (NS_UNLIKELY(tmp / aHeight != aWidth)) {
+  if (MOZ_UNLIKELY(tmp / aHeight != aWidth)) {
     NS_WARNING("width or height too large");
     return false;
   }
   tmp = tmp * 4;
-  if (NS_UNLIKELY(tmp / 4 != aWidth * aHeight)) {
+  if (MOZ_UNLIKELY(tmp / 4 != aWidth * aHeight)) {
     NS_WARNING("width or height too large");
     return false;
   }
 #if defined(XP_MACOSX)
   // CoreGraphics is limited to images < 32K in *height*, so clamp all surfaces on the Mac to that height
-  if (NS_UNLIKELY(aHeight > SHRT_MAX)) {
+  if (MOZ_UNLIKELY(aHeight > SHRT_MAX)) {
     NS_WARNING("image too big");
     return false;
   }
 #endif
   return true;
 }
 
 // Returns whether we should, at this time, use image surfaces instead of
--- a/image/src/imgRequest.cpp
+++ b/image/src/imgRequest.cpp
@@ -41,16 +41,17 @@
 
 #include "nsString.h"
 #include "nsXPIDLString.h"
 #include "plstr.h" // PL_strcasestr(...)
 #include "nsNetUtil.h"
 #include "nsIProtocolHandler.h"
 
 #include "mozilla/Preferences.h"
+#include "mozilla/Likely.h"
 
 #include "DiscardTracker.h"
 #include "nsAsyncRedirectVerifyHelper.h"
 
 #define SVG_MIMETYPE "image/svg+xml"
 
 using namespace mozilla;
 using namespace mozilla::image;
@@ -86,17 +87,17 @@ imgRequest::imgRequest(imgLoader* aLoade
  , mCORSMode(imgIRequest::CORS_NONE)
  , mDecodeRequested(false)
  , mIsMultiPartChannel(false)
  , mGotData(false)
  , mIsInCache(false)
  , mResniffMimeType(false)
 {
   // Register our pref observers if we haven't yet.
-  if (NS_UNLIKELY(!gInitializedPrefCaches)) {
+  if (MOZ_UNLIKELY(!gInitializedPrefCaches)) {
     InitPrefCaches();
   }
 }
 
 imgRequest::~imgRequest()
 {
   if (mURI) {
     nsAutoCString spec;
--- a/intl/unicharutil/util/nsUnicharUtils.cpp
+++ b/intl/unicharutil/util/nsUnicharUtils.cpp
@@ -8,16 +8,17 @@
 
 #include "nsCRT.h"
 #include "nsICaseConversion.h"
 #include "nsServiceManagerUtils.h"
 #include "nsXPCOMStrings.h"
 #include "nsUTF8Utils.h"
 #include "nsUnicodeProperties.h"
 #include "nsHashKeys.h"
+#include "mozilla/Likely.h"
 
 // We map x -> x, except for upper-case letters,
 // which we map to their lower-case equivalents.
 static const uint8_t gASCIIToLower [128] = {
     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
     0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
     0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
@@ -278,49 +279,49 @@ GetLowerUTF8Codepoint(const char* aStr, 
   // sign extend.
   const unsigned char *str = (unsigned char*)aStr;
 
   if (UTF8traits::isASCII(str[0])) {
     // It's ASCII; just convert to lower-case and return it.
     *aNext = aStr + 1;
     return gASCIIToLower[*str];
   }
-  if (UTF8traits::is2byte(str[0]) && NS_LIKELY(aStr + 1 < aEnd)) {
+  if (UTF8traits::is2byte(str[0]) && MOZ_LIKELY(aStr + 1 < aEnd)) {
     // It's a two-byte sequence, so it looks like
     //  110XXXXX 10XXXXXX.
     // This is definitely in the BMP, so we can store straightaway into a
     // uint16_t.
 
     uint16_t c;
     c  = (str[0] & 0x1F) << 6;
     c += (str[1] & 0x3F);
 
     // we don't go through ToLowerCase here, because we know this isn't
     // an ASCII character so the ASCII fast-path there is useless
     c = mozilla::unicode::GetLowercase(c);
 
     *aNext = aStr + 2;
     return c;
   }
-  if (UTF8traits::is3byte(str[0]) && NS_LIKELY(aStr + 2 < aEnd)) {
+  if (UTF8traits::is3byte(str[0]) && MOZ_LIKELY(aStr + 2 < aEnd)) {
     // It's a three-byte sequence, so it looks like
     //  1110XXXX 10XXXXXX 10XXXXXX.
     // This will just barely fit into 16-bits, so store into a uint16_t.
 
     uint16_t c;
     c  = (str[0] & 0x0F) << 12;
     c += (str[1] & 0x3F) << 6;
     c += (str[2] & 0x3F);
 
     c = mozilla::unicode::GetLowercase(c);
 
     *aNext = aStr + 3;
     return c;
   }
-  if (UTF8traits::is4byte(str[0]) && NS_LIKELY(aStr + 3 < aEnd)) {
+  if (UTF8traits::is4byte(str[0]) && MOZ_LIKELY(aStr + 3 < aEnd)) {
     // It's a four-byte sequence, so it looks like
     //   11110XXX 10XXXXXX 10XXXXXX 10XXXXXX.
 
     uint32_t c;
     c  = (str[0] & 0x07) << 18;
     c += (str[1] & 0x3F) << 12;
     c += (str[2] & 0x3F) << 6;
     c += (str[3] & 0x3F);
@@ -340,21 +341,21 @@ int32_t CaseInsensitiveCompare(const cha
                                uint32_t aLeftBytes,
                                uint32_t aRightBytes)
 {
   const char *leftEnd = aLeft + aLeftBytes;
   const char *rightEnd = aRight + aRightBytes;
 
   while (aLeft < leftEnd && aRight < rightEnd) {
     uint32_t leftChar = GetLowerUTF8Codepoint(aLeft, leftEnd, &aLeft);
-    if (NS_UNLIKELY(leftChar == uint32_t(-1)))
+    if (MOZ_UNLIKELY(leftChar == uint32_t(-1)))
       return -1;
 
     uint32_t rightChar = GetLowerUTF8Codepoint(aRight, rightEnd, &aRight);
-    if (NS_UNLIKELY(rightChar == uint32_t(-1)))
+    if (MOZ_UNLIKELY(rightChar == uint32_t(-1)))
       return -1;
 
     // Now leftChar and rightChar are lower-case, so we can compare them.
     if (leftChar != rightChar) {
       if (leftChar > rightChar)
         return 1;
       return -1;
     }
@@ -378,23 +379,23 @@ CaseInsensitiveUTF8CharsEqual(const char
 {
   NS_ASSERTION(aLeftNext, "Out pointer shouldn't be null.");
   NS_ASSERTION(aRightNext, "Out pointer shouldn't be null.");
   NS_ASSERTION(aErr, "Out pointer shouldn't be null.");
   NS_ASSERTION(aLeft < aLeftEnd, "aLeft must be less than aLeftEnd.");
   NS_ASSERTION(aRight < aRightEnd, "aRight must be less than aRightEnd.");
 
   uint32_t leftChar = GetLowerUTF8Codepoint(aLeft, aLeftEnd, aLeftNext);
-  if (NS_UNLIKELY(leftChar == uint32_t(-1))) {
+  if (MOZ_UNLIKELY(leftChar == uint32_t(-1))) {
     *aErr = true;
     return false;
   }
 
   uint32_t rightChar = GetLowerUTF8Codepoint(aRight, aRightEnd, aRightNext);
-  if (NS_UNLIKELY(rightChar == uint32_t(-1))) {
+  if (MOZ_UNLIKELY(rightChar == uint32_t(-1))) {
     *aErr = true;
     return false;
   }
 
   // Can't have an error past this point.
   *aErr = false;
 
   return leftChar == rightChar;
--- a/js/xpconnect/src/XPCWrappedNative.cpp
+++ b/js/xpconnect/src/XPCWrappedNative.cpp
@@ -54,17 +54,17 @@ NS_IMETHODIMP
 NS_CYCLE_COLLECTION_CLASSNAME(XPCWrappedNative)::TraverseImpl
    (NS_CYCLE_COLLECTION_CLASSNAME(XPCWrappedNative) *that, void *p,
     nsCycleCollectionTraversalCallback &cb)
 {
     XPCWrappedNative *tmp = static_cast<XPCWrappedNative*>(p);
     if (!tmp->IsValid())
         return NS_OK;
 
-    if (NS_UNLIKELY(cb.WantDebugInfo())) {
+    if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
         char name[72];
         XPCNativeScriptableInfo* si = tmp->GetScriptableInfo();
         if (si)
             JS_snprintf(name, sizeof(name), "XPCWrappedNative (%s)",
                         si->GetJSClass()->name);
         else
             JS_snprintf(name, sizeof(name), "XPCWrappedNative");
 
--- a/js/xpconnect/src/nsXPConnect.cpp
+++ b/js/xpconnect/src/nsXPConnect.cpp
@@ -3,16 +3,17 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* High level class and public functions implementation. */
 
 #include "mozilla/Assertions.h"
 #include "mozilla/Base64.h"
+#include "mozilla/Likely.h"
 #include "mozilla/Util.h"
 
 #include "xpcprivate.h"
 #include "XPCWrapper.h"
 #include "nsBaseHashtable.h"
 #include "nsHashKeys.h"
 #include "jsfriendapi.h"
 #include "dom_quickstubs.h"
@@ -131,17 +132,17 @@ nsXPConnect::~nsXPConnect()
 
 // static
 nsXPConnect*
 nsXPConnect::GetXPConnect()
 {
     // Do a release-mode assert that we're not doing anything significant in
     // XPConnect off the main thread. If you're an extension developer hitting
     // this, you need to change your code. See bug 716167.
-    if (!NS_LIKELY(NS_IsMainThread() || NS_IsCycleCollectorThread()))
+    if (!MOZ_LIKELY(NS_IsMainThread() || NS_IsCycleCollectorThread()))
         MOZ_CRASH();
 
     if (!gSelf) {
         if (gOnceAliveNowDead)
             return nullptr;
         gSelf = new nsXPConnect();
         if (!gSelf)
             return nullptr;
@@ -690,17 +691,17 @@ NoteJSChild(JSTracer *trc, void *thing, 
      * This function needs to be careful to avoid stack overflow. Normally, when
      * AddToCCKind is true, the recursion terminates immediately as we just add
      * |thing| to the CC graph. So overflow is only possible when there are long
      * chains of non-AddToCCKind GC things. Currently, this only can happen via
      * shape parent pointers. The special JSTRACE_SHAPE case below handles
      * parent pointers iteratively, rather than recursively, to avoid overflow.
      */
     if (AddToCCKind(kind)) {
-        if (NS_UNLIKELY(tracer->cb.WantDebugInfo())) {
+        if (MOZ_UNLIKELY(tracer->cb.WantDebugInfo())) {
             // based on DumpNotify in jsapi.c
             if (tracer->debugPrinter) {
                 char buffer[200];
                 tracer->debugPrinter(trc, buffer, sizeof(buffer));
                 tracer->cb.NoteNextEdgeName(buffer);
             } else if (tracer->debugPrintIndex != (size_t)-1) {
                 char buffer[200];
                 JS_snprintf(buffer, sizeof(buffer), "%s[%lu]",
@@ -1992,17 +1993,17 @@ nsXPConnect::OnProcessNextEvent(nsIThrea
     return Push(nullptr);
 }
 
 NS_IMETHODIMP
 nsXPConnect::AfterProcessNextEvent(nsIThreadInternal *aThread,
                                    uint32_t aRecursionDepth)
 {
     // Watch out for unpaired events during observer registration.
-    if (NS_UNLIKELY(mEventDepth == 0))
+    if (MOZ_UNLIKELY(mEventDepth == 0))
         return NS_OK;
     mEventDepth--;
 
     // Call cycle collector occasionally.
     MOZ_ASSERT(NS_IsMainThread());
     nsJSContext::MaybePokeCC();
     nsDOMMutationObserver::HandleMutations();
 
--- a/layout/base/nsCSSFrameConstructor.cpp
+++ b/layout/base/nsCSSFrameConstructor.cpp
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /*
  * construction of a frame tree that is nearly isomorphic to the content
  * tree and updating of that tree in response to dynamic changes
  */
 
 #include "mozilla/Util.h"
+#include "mozilla/Likely.h"
 
 #include "nsCSSFrameConstructor.h"
 #include "nsCRT.h"
 #include "nsIAtom.h"
 #include "nsIURL.h"
 #include "nsHashtable.h"
 #include "nsIHTMLDocument.h"
 #include "nsIStyleRule.h"
@@ -1117,17 +1118,17 @@ nsFrameConstructorState::AddChild(nsIFra
   
   // The comments in GetGeometricParent regarding root table frames
   // all apply here, unfortunately.
 
   bool needPlaceholder = false;
   nsFrameState placeholderType;
   nsFrameItems* frameItems = &aFrameItems;
 #ifdef MOZ_XUL
-  if (NS_UNLIKELY(aIsOutOfFlowPopup)) {
+  if (MOZ_UNLIKELY(aIsOutOfFlowPopup)) {
       NS_ASSERTION(aNewFrame->GetParent() == mPopupItems.containingBlock,
                    "Popup whose parent is not the popup containing block?");
       NS_ASSERTION(mPopupItems.containingBlock, "Must have a popup set frame!");
       needPlaceholder = true;
       frameItems = &mPopupItems;
       placeholderType = PLACEHOLDER_FOR_POPUP;
   }
   else
@@ -1984,17 +1985,17 @@ nsCSSFrameConstructor::ConstructTableRow
   const uint32_t nameSpaceID = aItem.mNameSpaceID;
 
   nsIFrame* newFrame;
   if (kNameSpaceID_MathML == nameSpaceID)
     newFrame = NS_NewMathMLmtrFrame(mPresShell, styleContext);
   else
     newFrame = NS_NewTableRowFrame(mPresShell, styleContext);
 
-  if (NS_UNLIKELY(!newFrame)) {
+  if (MOZ_UNLIKELY(!newFrame)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   InitAndRestoreFrame(aState, content, aParentFrame, nullptr, newFrame);
 
   nsFrameItems childItems;
   nsresult rv;
   if (aItem.mFCData->mBits & FCDATA_USE_CHILD_ITEMS) {
     rv = ConstructFramesFromItemList(aState, aItem.mChildItems, newFrame,
@@ -2019,32 +2020,32 @@ nsCSSFrameConstructor::ConstructTableCol
                                          const nsStyleDisplay*    aStyleDisplay,
                                          nsFrameItems&            aFrameItems,
                                          nsIFrame**               aNewFrame)
 {
   nsIContent* const content = aItem.mContent;
   nsStyleContext* const styleContext = aItem.mStyleContext;
 
   nsTableColFrame* colFrame = NS_NewTableColFrame(mPresShell, styleContext);
-  if (NS_UNLIKELY(!colFrame)) {
+  if (MOZ_UNLIKELY(!colFrame)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   InitAndRestoreFrame(aState, content, aParentFrame, nullptr, colFrame);
 
   NS_ASSERTION(colFrame->GetStyleContext() == styleContext,
                "Unexpected style context");
 
   aFrameItems.AddChild(colFrame);
   *aNewFrame = colFrame;
 
   // construct additional col frames if the col frame has a span > 1
   int32_t span = colFrame->GetSpan();
   for (int32_t spanX = 1; spanX < span; spanX++) {
     nsTableColFrame* newCol = NS_NewTableColFrame(mPresShell, styleContext);
-    if (NS_UNLIKELY(!newCol)) {
+    if (MOZ_UNLIKELY(!newCol)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
     InitAndRestoreFrame(aState, content, aParentFrame, nullptr, newCol,
                         false);
     aFrameItems.LastChild()->SetNextContinuation(newCol);
     newCol->SetPrevContinuation(aFrameItems.LastChild());
     aFrameItems.AddChild(newCol);
     newCol->SetColType(eColAnonymousCol);
@@ -2080,17 +2081,17 @@ nsCSSFrameConstructor::ConstructTableCel
   if (kNameSpaceID_MathML == nameSpaceID && !borderCollapse)
     newFrame = NS_NewMathMLmtdFrame(mPresShell, styleContext);
   else
     // Warning: If you change this and add a wrapper frame around table cell
     // frames, make sure Bug 368554 doesn't regress!
     // See IsInAutoWidthTableCellForQuirk() in nsImageFrame.cpp.    
     newFrame = NS_NewTableCellFrame(mPresShell, styleContext, borderCollapse);
 
-  if (NS_UNLIKELY(!newFrame)) {
+  if (MOZ_UNLIKELY(!newFrame)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   // Initialize the table cell frame
   InitAndRestoreFrame(aState, content, aParentFrame, nullptr, newFrame);
   
   // Resolve pseudo style and initialize the body cell frame
   nsRefPtr<nsStyleContext> innerPseudoStyle;
@@ -2103,17 +2104,17 @@ nsCSSFrameConstructor::ConstructTableCel
   if (kNameSpaceID_MathML == nameSpaceID) {
     cellInnerFrame = NS_NewMathMLmtdInnerFrame(mPresShell, innerPseudoStyle);
     isBlock = false;
   } else {
     cellInnerFrame = NS_NewBlockFormattingContext(mPresShell, innerPseudoStyle);
     isBlock = true;
   }
 
-  if (NS_UNLIKELY(!cellInnerFrame)) {
+  if (MOZ_UNLIKELY(!cellInnerFrame)) {
     newFrame->Destroy();
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   InitAndRestoreFrame(aState, content, newFrame, nullptr, cellInnerFrame);
 
   nsFrameItems childItems;
   nsresult rv;
@@ -2366,17 +2367,17 @@ nsCSSFrameConstructor::ConstructDocEleme
 
 #ifdef DEBUG
   NS_ASSERTION(!display->IsScrollableOverflow() || 
                state.mPresContext->IsPaginated() ||
                propagatedScrollFrom == aDocElement,
                "Scrollbars should have been propagated to the viewport");
 #endif
 
-  if (NS_UNLIKELY(display->mDisplay == NS_STYLE_DISPLAY_NONE)) {
+  if (MOZ_UNLIKELY(display->mDisplay == NS_STYLE_DISPLAY_NONE)) {
     SetUndisplayedContent(aDocElement, styleContext);
     return NS_OK;
   }
 
   AncestorFilter::AutoAncestorPusher
     ancestorPusher(true, state.mTreeMatchContext.mAncestorFilter, aDocElement);
 
   // Make sure to start any background image loads for the root element now.
@@ -2404,17 +2405,17 @@ nsCSSFrameConstructor::ConstructDocEleme
   // placeholder.
   nsIFrame* contentFrame;
   bool processChildren = false;
 
   // Check whether we need to build a XUL box or SVG root frame
 #ifdef MOZ_XUL
   if (aDocElement->IsXUL()) {
     contentFrame = NS_NewDocElementBoxFrame(mPresShell, styleContext);
-    if (NS_UNLIKELY(!contentFrame)) {
+    if (MOZ_UNLIKELY(!contentFrame)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
     InitAndRestoreFrame(state, aDocElement, mDocElementContainingBlock, nullptr,
                         contentFrame);
     *aNewFrame = contentFrame;
     processChildren = true;
   }
   else
@@ -2811,30 +2812,30 @@ nsCSSFrameConstructor::ConstructPageFram
   nsStyleContext* parentStyleContext = aParentFrame->GetStyleContext();
   nsStyleSet *styleSet = aPresShell->StyleSet();
 
   nsRefPtr<nsStyleContext> pagePseudoStyle;
   pagePseudoStyle = styleSet->ResolveAnonymousBoxStyle(nsCSSAnonBoxes::page,
                                                        parentStyleContext);
 
   aPageFrame = NS_NewPageFrame(aPresShell, pagePseudoStyle);
-  if (NS_UNLIKELY(!aPageFrame))
+  if (MOZ_UNLIKELY(!aPageFrame))
     return NS_ERROR_OUT_OF_MEMORY;
 
   // Initialize the page frame and force it to have a view. This makes printing of
   // the pages easier and faster.
   aPageFrame->Init(nullptr, aParentFrame, aPrevPageFrame);
 
   nsRefPtr<nsStyleContext> pageContentPseudoStyle;
   pageContentPseudoStyle =
     styleSet->ResolveAnonymousBoxStyle(nsCSSAnonBoxes::pageContent,
                                        pagePseudoStyle);
 
   nsIFrame* pageContentFrame = NS_NewPageContentFrame(aPresShell, pageContentPseudoStyle);
-  if (NS_UNLIKELY(!pageContentFrame))
+  if (MOZ_UNLIKELY(!pageContentFrame))
     return NS_ERROR_OUT_OF_MEMORY;
 
   // Initialize the page content frame and force it to have a view. Also make it the
   // containing block for fixed elements which are repeated on every page.
   nsIFrame* prevPageContentFrame = nullptr;
   if (aPrevPageFrame) {
     prevPageContentFrame = aPrevPageFrame->GetFirstPrincipalChild();
     NS_ASSERTION(prevPageContentFrame, "missing page content frame");
@@ -2845,17 +2846,17 @@ nsCSSFrameConstructor::ConstructPageFram
   // Make it an absolute container for fixed-pos elements
   mFixedContainingBlock->MarkAsAbsoluteContainingBlock();
 
   nsRefPtr<nsStyleContext> canvasPseudoStyle;
   canvasPseudoStyle = styleSet->ResolveAnonymousBoxStyle(nsCSSAnonBoxes::canvas,
                                                          pageContentPseudoStyle);
 
   aCanvasFrame = NS_NewCanvasFrame(aPresShell, canvasPseudoStyle);
-  if (NS_UNLIKELY(!aCanvasFrame))
+  if (MOZ_UNLIKELY(!aCanvasFrame))
     return NS_ERROR_OUT_OF_MEMORY;
 
   nsIFrame* prevCanvasFrame = nullptr;
   if (prevPageContentFrame) {
     prevCanvasFrame = prevPageContentFrame->GetFirstPrincipalChild();
     NS_ASSERTION(prevCanvasFrame, "missing canvas frame");
   }
   aCanvasFrame->Init(nullptr, pageContentFrame, prevCanvasFrame);
@@ -3115,17 +3116,17 @@ nsCSSFrameConstructor::ConstructFieldSet
                                               const nsStyleDisplay*    aStyleDisplay,
                                               nsFrameItems&            aFrameItems,
                                               nsIFrame**               aNewFrame)
 {
   nsIContent* const content = aItem.mContent;
   nsStyleContext* const styleContext = aItem.mStyleContext;
 
   nsIFrame* newFrame = NS_NewFieldSetFrame(mPresShell, styleContext);
-  if (NS_UNLIKELY(!newFrame)) {
+  if (MOZ_UNLIKELY(!newFrame)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   // Initialize it
   InitAndRestoreFrame(aState, content,
                       aState.GetGeometricParent(aStyleDisplay, aParentFrame),
                       nullptr, newFrame);
 
@@ -3236,17 +3237,17 @@ nsCSSFrameConstructor::ConstructTextFram
                                           nsIFrame*                aParentFrame,
                                           nsStyleContext*          aStyleContext,
                                           nsFrameItems&            aFrameItems)
 {
   NS_PRECONDITION(aData, "Must have frame construction data");
 
   nsIFrame* newFrame = (*aData->mFunc.mCreationFunc)(mPresShell, aStyleContext);
 
-  if (NS_UNLIKELY(!newFrame))
+  if (MOZ_UNLIKELY(!newFrame))
     return NS_ERROR_OUT_OF_MEMORY;
 
   nsresult rv = InitAndRestoreFrame(aState, aContent, aParentFrame,
                                     nullptr, newFrame);
 
   if (NS_FAILED(rv)) {
     newFrame->Destroy();
     return rv;
@@ -3668,17 +3669,17 @@ nsCSSFrameConstructor::ConstructFrameFro
     nsIFrame* possiblyLeafFrame = newFrame;
     if (bits & FCDATA_CREATE_BLOCK_WRAPPER_FOR_ALL_KIDS) {
       nsRefPtr<nsStyleContext> blockContext;
       blockContext =
         mPresShell->StyleSet()->ResolveAnonymousBoxStyle(*data->mAnonBoxPseudo,
                                                          styleContext);
       nsIFrame* blockFrame =
         NS_NewBlockFormattingContext(mPresShell, blockContext);
-      if (NS_UNLIKELY(!blockFrame)) {
+      if (MOZ_UNLIKELY(!blockFrame)) {
         primaryFrame->Destroy();
         return NS_ERROR_OUT_OF_MEMORY;
       }
 
       rv = InitAndRestoreFrame(aState, content, newFrame, nullptr, blockFrame);
       if (NS_FAILED(rv)) {
         blockFrame->Destroy();
         primaryFrame->Destroy();
@@ -4470,17 +4471,17 @@ nsCSSFrameConstructor::ConstructScrollab
 
   nsFrameItems blockItem;
   nsresult rv = ConstructBlock(aState,
                                scrolledContentStyle->GetStyleDisplay(), content,
                                *aNewFrame, *aNewFrame, scrolledContentStyle,
                                &scrolledFrame, blockItem,
                                aDisplay->IsPositioned(scrolledFrame),
                                aItem.mPendingBinding);
-  if (NS_UNLIKELY(NS_FAILED(rv))) {
+  if (MOZ_UNLIKELY(NS_FAILED(rv))) {
     // XXXbz any cleanup needed here?
     return rv;
   }
 
   NS_ASSERTION(blockItem.FirstChild() == scrolledFrame,
                "Scrollframe's frameItems should be exactly the scrolled frame");
   FinishBuildingScrollFrame(*aNewFrame, scrolledFrame);
 
@@ -4635,17 +4636,17 @@ nsCSSFrameConstructor::FlushAccumulatedB
 
 
   // then, create a block frame that will wrap the child frames. Make it a
   // MathML frame so that Get(Absolute/Float)ContainingBlockFor know that this
   // is not a suitable block.
   nsIFrame* blockFrame =
       NS_NewMathMLmathBlockFrame(mPresShell, blockContext,
                                  NS_BLOCK_FLOAT_MGR | NS_BLOCK_MARGIN_ROOT);
-  if (NS_UNLIKELY(!blockFrame))
+  if (MOZ_UNLIKELY(!blockFrame))
     return NS_ERROR_OUT_OF_MEMORY;
 
   InitAndRestoreFrame(aState, aContent, aParentFrame, nullptr, blockFrame);
   ReparentFrames(this, blockFrame, aBlockItems);
   // abs-pos and floats are disabled in MathML children so we don't have to
   // worry about messing up those.
   blockFrame->SetInitialChildList(kPrincipalList, aBlockItems);
   NS_ASSERTION(aBlockItems.IsEmpty(), "What happened?");
@@ -10799,17 +10800,17 @@ nsCSSFrameConstructor::RemoveFloatingFir
     return NS_OK;
   }
   nsRefPtr<nsStyleContext> newSC;
   newSC = aPresShell->StyleSet()->ResolveStyleForNonElement(parentSC);
   if (!newSC) {
     return NS_OK;
   }
   nsIFrame* newTextFrame = NS_NewTextFrame(aPresShell, newSC);
-  if (NS_UNLIKELY(!newTextFrame)) {
+  if (MOZ_UNLIKELY(!newTextFrame)) {
     return NS_ERROR_OUT_OF_MEMORY;;
   }
   newTextFrame->Init(textContent, parentFrame, nullptr);
 
   // Destroy the old text frame's continuations (the old text frame
   // will be destroyed when its letter frame is destroyed).
   nsIFrame* frameToDelete = textFrame->GetLastContinuation();
   while (frameToDelete != textFrame) {
@@ -12214,17 +12215,17 @@ nsCSSFrameConstructor::ProcessPendingRes
 }
 
 void
 nsCSSFrameConstructor::PostRestyleEventCommon(Element* aElement,
                                               nsRestyleHint aRestyleHint,
                                               nsChangeHint aMinChangeHint,
                                               bool aForAnimation)
 {
-  if (NS_UNLIKELY(mPresShell->IsDestroying())) {
+  if (MOZ_UNLIKELY(mPresShell->IsDestroying())) {
     return;
   }
 
   if (aRestyleHint == 0 && !aMinChangeHint) {
     // Nothing to do here
     return;
   }
 
--- a/layout/base/nsCounterManager.cpp
+++ b/layout/base/nsCounterManager.cpp
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* implementation of CSS counters (for numbering things) */
 
 #include "nsCounterManager.h"
 #include "nsBulletFrame.h" // legacy location for list style type to text code
 #include "nsContentUtils.h"
 #include "nsTArray.h"
+#include "mozilla/Likely.h"
 
 bool
 nsCounterUseNode::InitTextFrame(nsGenConList* aList,
         nsIFrame* aPseudoFrame, nsIFrame* aTextFrame)
 {
   nsCounterNode::InitTextFrame(aList, aPseudoFrame, aTextFrame);
 
   nsCounterList *counterList = static_cast<nsCounterList*>(aList);
@@ -224,17 +225,17 @@ nsCounterManager::AddResetOrIncrement(ns
         // Tell the caller it's responsible for recalculating the entire
         // list.
         counterList->SetDirty();
         return true;
     }
 
     // Don't call Calc() if the list is already dirty -- it'll be recalculated
     // anyway, and trying to calculate with a dirty list doesn't work.
-    if (NS_LIKELY(!counterList->IsDirty())) {
+    if (MOZ_LIKELY(!counterList->IsDirty())) {
         node->Calc(counterList);
     }
     return false;
 }
 
 nsCounterList*
 nsCounterManager::CounterListFor(const nsSubstring& aCounterName)
 {
--- a/layout/base/nsCounterManager.h
+++ b/layout/base/nsCounterManager.h
@@ -7,16 +7,17 @@
 /* implementation of CSS counters (for numbering things) */
 
 #ifndef nsCounterManager_h_
 #define nsCounterManager_h_
 
 #include "nsGenConList.h"
 #include "nsAutoPtr.h"
 #include "nsClassHashtable.h"
+#include "mozilla/Likely.h"
 
 class nsCounterList;
 struct nsCounterUseNode;
 struct nsCounterChangeNode;
 
 struct nsCounterNode : public nsGenConNode {
     enum Type {
         RESET,     // a "counter number" pair in 'counter-reset'
@@ -161,17 +162,17 @@ public:
     nsCounterList() : nsGenConList(),
                       mDirty(false)
     {}
 
     void Insert(nsCounterNode* aNode) {
         nsGenConList::Insert(aNode);
         // Don't SetScope if we're dirty -- we'll reset all the scopes anyway,
         // and we can't usefully compute scopes right now.
-        if (NS_LIKELY(!IsDirty())) {
+        if (MOZ_LIKELY(!IsDirty())) {
             SetScope(aNode);
         }
     }
 
     nsCounterNode* First() {
         return static_cast<nsCounterNode*>(mFirstNode);
     }
 
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -15,16 +15,17 @@
  * Date         Modified by     Description of modification
  * 05/03/2000   IBM Corp.       Observer events for reflow states
  */
 
 /* a presentation of a document, part 2 */
 
 #include "mozilla/dom/PBrowserChild.h"
 #include "mozilla/dom/TabChild.h"
+#include "mozilla/Likely.h"
 #include "mozilla/Util.h"
 
 #ifdef XP_WIN
 #include "winuser.h"
 #endif
 
 #include "nsPresShell.h"
 #include "nsPresContext.h"
@@ -1741,17 +1742,17 @@ PresShell::Initialize(nscoord aWidth, ns
     // And that might have run _more_ XBL constructors
     NS_ENSURE_STATE(!mHaveShutDown);
   }
 
   NS_ASSERTION(rootFrame, "How did that happen?");
 
   // Note: when the frame was created above it had the NS_FRAME_IS_DIRTY bit
   // set, but XBL processing could have caused a reflow which clears it.
-  if (NS_LIKELY(rootFrame->GetStateBits() & NS_FRAME_IS_DIRTY)) {
+  if (MOZ_LIKELY(rootFrame->GetStateBits() & NS_FRAME_IS_DIRTY)) {
     // Unset the DIRTY bits so that FrameNeedsReflow() will work right.
     rootFrame->RemoveStateBits(NS_FRAME_IS_DIRTY |
                                NS_FRAME_HAS_DIRTY_CHILDREN);
     NS_ASSERTION(!mDirtyRoots.Contains(rootFrame),
                  "Why is the root in mDirtyRoots already?");
     FrameNeedsReflow(rootFrame, eResize, NS_FRAME_IS_DIRTY);
     NS_ASSERTION(mDirtyRoots.Contains(rootFrame),
                  "Should be in mDirtyRoots now");
@@ -3295,17 +3296,17 @@ PresShell::DoScrollContentIntoView()
     nsLayoutUtils::GetClosestFrameOfType(frame->GetParent(), nsGkAtoms::scrollFrame);
   if (!container) {
     // nothing can be scrolled
     return;
   }
 
   ScrollIntoViewData* data = static_cast<ScrollIntoViewData*>(
     mContentToScrollTo->GetProperty(nsGkAtoms::scrolling));
-  if (NS_UNLIKELY(!data)) {
+  if (MOZ_UNLIKELY(!data)) {
     mContentToScrollTo = nullptr;
     return;
   }
 
   // This is a two-step process.
   // Step 1: Find the bounds of the rect we want to scroll into view.  For
   //         example, for an inline frame we may want to scroll in the whole
   //         line, or we may want to scroll multiple lines into view.
@@ -3645,17 +3646,17 @@ PresShell::UnsuppressPainting()
     UnsuppressAndInvalidate();
 }
 
 // Post a request to handle an arbitrary callback after reflow has finished.
 nsresult
 PresShell::PostReflowCallback(nsIReflowCallback* aCallback)
 {
   void* result = AllocateMisc(sizeof(nsCallbackEventRequest));
-  if (NS_UNLIKELY(!result)) {
+  if (MOZ_UNLIKELY(!result)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   nsCallbackEventRequest* request = (nsCallbackEventRequest*)result;
 
   request->callback = aCallback;
   request->next = nullptr;
 
   if (mLastCallbackEventRequest) {
@@ -5393,17 +5394,17 @@ nsIPresShell::SetCapturingContent(nsICon
     gCaptureInfo.mPreventDrag = (aFlags & CAPTURE_PREVENTDRAG) != 0;
     gCaptureInfo.mPointerLock = (aFlags & CAPTURE_POINTERLOCK) != 0;
   }
 }
 
 nsIFrame*
 PresShell::GetCurrentEventFrame()
 {
-  if (NS_UNLIKELY(mIsDestroying)) {
+  if (MOZ_UNLIKELY(mIsDestroying)) {
     return nullptr;
   }
     
   if (!mCurrentEventFrame && mCurrentEventContent) {
     // Make sure the content still has a document reference. If not,
     // then we assume it is no longer in the content tree and the
     // frame shouldn't get an event, nor should we even assume its
     // safe to try and find the frame.
--- a/layout/forms/nsComboboxControlFrame.cpp
+++ b/layout/forms/nsComboboxControlFrame.cpp
@@ -48,16 +48,17 @@
 #include "nsLayoutUtils.h"
 #include "nsDisplayList.h"
 #include "nsITheme.h"
 #include "nsThemeConstants.h"
 #include "nsAsyncDOMEvent.h"
 #include "nsRenderingContext.h"
 #include "mozilla/Preferences.h"
 #include "nsContentList.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 
 NS_IMETHODIMP
 nsComboboxControlFrame::RedisplayTextEvent::Run()
 {
   if (mControlFrame)
     mControlFrame->HandleRedisplayTextEvent();
@@ -774,17 +775,17 @@ nsComboboxControlFrame::GetIntrinsicWidt
   if (mListControlFrame) {
     nsIScrollableFrame* scrollable = do_QueryFrame(mListControlFrame);
     NS_ASSERTION(scrollable, "List must be a scrollable frame");
     scrollbarWidth =
       scrollable->GetDesiredScrollbarSizes(presContext, aRenderingContext).LeftRight();
   }
 
   nscoord displayWidth = 0;
-  if (NS_LIKELY(mDisplayFrame)) {
+  if (MOZ_LIKELY(mDisplayFrame)) {
     displayWidth = nsLayoutUtils::IntrinsicForContainer(aRenderingContext,
                                                         mDisplayFrame,
                                                         aType);
   }
 
   if (mDropdownFrame) {
     nscoord dropdownContentWidth;
     if (aType == nsLayoutUtils::MIN_WIDTH) {
@@ -1389,42 +1390,42 @@ nsComboboxControlFrame::CreateFrameFor(n
   nsIPresShell *shell = PresContext()->PresShell();
   nsStyleSet *styleSet = shell->StyleSet();
 
   // create the style contexts for the anonymous block frame and text frame
   nsRefPtr<nsStyleContext> styleContext;
   styleContext = styleSet->
     ResolveAnonymousBoxStyle(nsCSSAnonBoxes::mozDisplayComboboxControlFrame,
                              mStyleContext);
-  if (NS_UNLIKELY(!styleContext)) {
+  if (MOZ_UNLIKELY(!styleContext)) {
     return nullptr;
   }
 
   nsRefPtr<nsStyleContext> textStyleContext;
   textStyleContext = styleSet->ResolveStyleForNonElement(mStyleContext);
-  if (NS_UNLIKELY(!textStyleContext)) {
+  if (MOZ_UNLIKELY(!textStyleContext)) {
     return nullptr;
   }
 
   // Start by by creating our anonymous block frame
   mDisplayFrame = new (shell) nsComboboxDisplayFrame(styleContext, this);
-  if (NS_UNLIKELY(!mDisplayFrame)) {
+  if (MOZ_UNLIKELY(!mDisplayFrame)) {
     return nullptr;
   }
 
   nsresult rv = mDisplayFrame->Init(mContent, this, nullptr);
   if (NS_FAILED(rv)) {
     mDisplayFrame->Destroy();
     mDisplayFrame = nullptr;
     return nullptr;
   }
 
   // Create a text frame and put it inside the block frame
   nsIFrame* textFrame = NS_NewTextFrame(shell, textStyleContext);
-  if (NS_UNLIKELY(!textFrame)) {
+  if (MOZ_UNLIKELY(!textFrame)) {
     return nullptr;
   }
 
   // initialize the text frame
   rv = textFrame->Init(aContent, mDisplayFrame, nullptr);
   if (NS_FAILED(rv)) {
     mDisplayFrame->Destroy();
     mDisplayFrame = nullptr;
--- a/layout/forms/nsFieldSetFrame.cpp
+++ b/layout/forms/nsFieldSetFrame.cpp
@@ -22,16 +22,17 @@
 #include "nsHTMLParts.h"
 #include "nsGkAtoms.h"
 #include "nsStyleConsts.h"
 #include "nsFont.h"
 #include "nsCOMPtr.h"
 #include "nsIServiceManager.h"
 #include "nsDisplayList.h"
 #include "nsRenderingContext.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 using namespace mozilla::layout;
 
 class nsLegendFrame;
 
 class nsFieldSetFrame : public nsContainerFrame {
 public:
@@ -608,17 +609,17 @@ nsFieldSetFrame::InsertFrames(ChildListI
                               nsFrameList&   aFrameList)
 {
   NS_ASSERTION(!aPrevFrame || aPrevFrame->GetParent() == this ||
                aPrevFrame->GetParent() == mContentFrame,
                "inserting after sibling frame with different parent");
 
   // aFrameList is not allowed to contain "the legend" for this fieldset
   ReparentFrameList(aFrameList);
-  if (NS_UNLIKELY(aPrevFrame == mLegendFrame)) {
+  if (MOZ_UNLIKELY(aPrevFrame == mLegendFrame)) {
     aPrevFrame = nullptr;
   }
   return mContentFrame->InsertFrames(aListID, aPrevFrame, aFrameList);
 }
 
 NS_IMETHODIMP
 nsFieldSetFrame::RemoveFrame(ChildListID    aListID,
                              nsIFrame*      aOldFrame)
--- a/layout/generic/TextOverflow.cpp
+++ b/layout/generic/TextOverflow.cpp
@@ -14,16 +14,17 @@
 #include "nsIScrollableFrame.h"
 #include "nsLayoutUtils.h"
 #include "nsPresContext.h"
 #include "nsRect.h"
 #include "nsRenderingContext.h"
 #include "nsTextFrame.h"
 #include "nsStyleStructInlines.h"
 #include "mozilla/Util.h"
+#include "mozilla/Likely.h"
 
 namespace mozilla {
 namespace css {
 
 static const PRUnichar kEllipsisChar[] = { 0x2026, 0x0 };
 static const PRUnichar kASCIIPeriodsChar[] = { '.', '.', '.', 0x0 };
 
 // Return an ellipsis if the font supports it,
@@ -619,25 +620,25 @@ TextOverflow::PruneDisplayListContents(n
 
     nsCharClipDisplayItem* charClip = itemFrame ? 
       nsCharClipDisplayItem::CheckCast(item) : nullptr;
     if (charClip && GetSelfOrNearestBlock(itemFrame) == mBlock) {
       nsRect rect = itemFrame->GetScrollableOverflowRect() +
                     itemFrame->GetOffsetTo(mBlock);
       if (mLeft.IsNeeded() && rect.x < aInsideMarkersArea.x) {
         nscoord left = aInsideMarkersArea.x - rect.x;
-        if (NS_UNLIKELY(left < 0)) {
+        if (MOZ_UNLIKELY(left < 0)) {
           item->~nsDisplayItem();
           continue;
         }
         charClip->mLeftEdge = left;
       }
       if (mRight.IsNeeded() && rect.XMost() > aInsideMarkersArea.XMost()) {
         nscoord right = rect.XMost() - aInsideMarkersArea.XMost();
-        if (NS_UNLIKELY(right < 0)) {
+        if (MOZ_UNLIKELY(right < 0)) {
           item->~nsDisplayItem();
           continue;
         }
         charClip->mRightEdge = right;
       }
     }
 
     saved.AppendToTop(item);
--- a/layout/generic/TextOverflow.h
+++ b/layout/generic/TextOverflow.h
@@ -6,16 +6,17 @@
 
 #ifndef TextOverflow_h_
 #define TextOverflow_h_
 
 #include "nsDisplayList.h"
 #include "nsLineBox.h"
 #include "nsStyleStruct.h"
 #include "nsTHashtable.h"
+#include "mozilla/Likely.h"
 class nsIScrollableFrame;
 
 namespace mozilla {
 namespace css {
 
 /**
  * A class for rendering CSS3 text-overflow.
  * Usage:
@@ -54,17 +55,17 @@ class TextOverflow {
  protected:
   TextOverflow() {}
   void Init(nsDisplayListBuilder*   aBuilder,
             nsIFrame*               aBlockFrame);
 
   struct AlignmentEdges {
     AlignmentEdges() : mAssigned(false) {}
     void Accumulate(const nsRect& aRect) {
-      if (NS_LIKELY(mAssigned)) {
+      if (MOZ_LIKELY(mAssigned)) {
         x = NS_MIN(x, aRect.X());
         xmost = NS_MAX(xmost, aRect.XMost());
       } else {
         x = aRect.X();
         xmost = aRect.XMost();
         mAssigned = true;
       }
     }
@@ -72,25 +73,25 @@ class TextOverflow {
     nscoord x;
     nscoord xmost;
     bool mAssigned;
   };
 
   struct InnerClipEdges {
     InnerClipEdges() : mAssignedLeft(false), mAssignedRight(false) {}
     void AccumulateLeft(const nsRect& aRect) {
-      if (NS_LIKELY(mAssignedLeft)) {
+      if (MOZ_LIKELY(mAssignedLeft)) {
         mLeft = NS_MAX(mLeft, aRect.X());
       } else {
         mLeft = aRect.X();
         mAssignedLeft = true;
       }
     }
     void AccumulateRight(const nsRect& aRect) {
-      if (NS_LIKELY(mAssignedRight)) {
+      if (MOZ_LIKELY(mAssignedRight)) {
         mRight = NS_MIN(mRight, aRect.XMost());
       } else {
         mRight = aRect.XMost();
         mAssignedRight = true;
       }
     }
     nscoord mLeft;
     nscoord mRight;
--- a/layout/generic/nsBlockFrame.cpp
+++ b/layout/generic/nsBlockFrame.cpp
@@ -49,16 +49,17 @@
 #include "nsCSSAnonBoxes.h"
 #include "nsCSSFrameConstructor.h"
 #include "nsCSSRendering.h"
 #include "FrameLayerBuilder.h"
 #include "nsRenderingContext.h"
 #include "TextOverflow.h"
 #include "nsStyleStructInlines.h"
 #include "mozilla/Util.h" // for DebugOnly
+#include "mozilla/Likely.h"
 
 #ifdef IBMBIDI
 #include "nsBidiPresUtils.h"
 #endif // IBMBIDI
 
 #include "nsIDOMHTMLBodyElement.h"
 #include "nsIDOMHTMLHtmlElement.h"
 
@@ -2538,17 +2539,17 @@ nsBlockFrame::PullFrameFrom(nsBlockReflo
   nsIFrame* frame = fromLine->mFirstChild;
   nsIFrame* newFirstChild = frame->GetNextSibling();
 
   if (aFromContainer != this) {
     NS_ASSERTION(aState.mPrevChild == aLine->LastChild(),
       "mPrevChild should be the LastChild of the line we are adding to");
     // The frame is being pulled from a next-in-flow; therefore we
     // need to add it to our sibling list.
-    if (NS_LIKELY(!aFromOverflowLine)) {
+    if (MOZ_LIKELY(!aFromOverflowLine)) {
       NS_ASSERTION(&aFromFrameList == &aFromContainer->mFrames,
                    "must be normal flow if not overflow line");
       NS_ASSERTION(aFromLine == aFromContainer->mLines.begin(),
                    "should only pull from first line");
     }
     aFromFrameList.RemoveFrame(frame);
 
     // When pushing and pulling frames we need to check for whether any
--- a/layout/generic/nsFrame.h
+++ b/layout/generic/nsFrame.h
@@ -4,16 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* base class of all rendering objects */
 
 #ifndef nsFrame_h___
 #define nsFrame_h___
 
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 #include "nsBox.h"
 #include "nsRect.h"
 #include "nsString.h"
 #include "prlog.h"
 
 #include "nsIPresShell.h"
 #include "nsFrameSelection.h"
 #include "nsHTMLReflowState.h"
@@ -573,17 +574,17 @@ public:
 
   /**
    * Returns true if aFrame should apply overflow clipping.
    */
   static bool ApplyOverflowClipping(const nsIFrame* aFrame,
                                     const nsStyleDisplay* aDisp)
   {
     // clip overflow:-moz-hidden-unscrollable ...
-    if (NS_UNLIKELY(aDisp->mOverflowX == NS_STYLE_OVERFLOW_CLIP)) {
+    if (MOZ_UNLIKELY(aDisp->mOverflowX == NS_STYLE_OVERFLOW_CLIP)) {
       return true;
     }
 
     // and overflow:hidden that we should interpret as -moz-hidden-unscrollable
     if (aDisp->mOverflowX == NS_STYLE_OVERFLOW_HIDDEN &&
         aDisp->mOverflowY == NS_STYLE_OVERFLOW_HIDDEN) {
       // REVIEW: these are the frame types that set up clipping.
       nsIAtom* type = aFrame->GetType();
--- a/layout/generic/nsFrameSetFrame.cpp
+++ b/layout/generic/nsFrameSetFrame.cpp
@@ -36,16 +36,17 @@
 #include "nsStyleSet.h"
 #include "mozilla/dom/Element.h"
 #include "nsDisplayList.h"
 #include "nsNodeUtils.h"
 #include "mozAutoDocUpdate.h"
 #include "mozilla/Preferences.h"
 #include "nsHTMLFrameSetElement.h"
 #include "mozilla/LookAndFeel.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 
 // masks for mEdgeVisibility
 #define LEFT_VIS   0x0001
 #define RIGHT_VIS  0x0002
 #define TOP_VIS    0x0004
 #define BOTTOM_VIS 0x0008
@@ -362,34 +363,34 @@ nsHTMLFramesetFrame::Init(nsIContent*   
     if (tag == nsGkAtoms::frameset || tag == nsGkAtoms::frame) {
       nsRefPtr<nsStyleContext> kidSC;
       nsresult result;
 
       kidSC = shell->StyleSet()->ResolveStyleFor(child->AsElement(),
                                                  mStyleContext);
       if (tag == nsGkAtoms::frameset) {
         frame = NS_NewHTMLFramesetFrame(shell, kidSC);
-        if (NS_UNLIKELY(!frame))
+        if (MOZ_UNLIKELY(!frame))
           return NS_ERROR_OUT_OF_MEMORY;
 
         mChildTypes[mChildCount] = FRAMESET;
         nsHTMLFramesetFrame* childFrame = (nsHTMLFramesetFrame*)frame;
         childFrame->SetParentFrameborder(frameborder);
         childFrame->SetParentBorderWidth(borderWidth);
         childFrame->SetParentBorderColor(borderColor);
         result = frame->Init(child, this, nullptr);
         if (NS_FAILED(result)) {
           frame->Destroy();
           return result;
         }
 
         mChildBorderColors[mChildCount].Set(childFrame->GetBorderColor());
       } else { // frame
         frame = NS_NewSubDocumentFrame(shell, kidSC);
-        if (NS_UNLIKELY(!frame))
+        if (MOZ_UNLIKELY(!frame))
           return NS_ERROR_OUT_OF_MEMORY;
 
         result = frame->Init(child, this, nullptr);
         if (NS_FAILED(result)) {
           frame->Destroy();
           return result;
         }
 
@@ -523,17 +524,17 @@ void nsHTMLFramesetFrame::CalculateRowCo
   int32_t  numFixed = 0;
   nsAutoArrayPtr<int32_t> fixed(new int32_t[aNumSpecs]);
   int32_t  numPercent = 0;
   nsAutoArrayPtr<int32_t> percent(new int32_t[aNumSpecs]);
   int32_t  relativeSums = 0;
   int32_t  numRelative = 0;
   nsAutoArrayPtr<int32_t> relative(new int32_t[aNumSpecs]);
 
-  if (NS_UNLIKELY(!fixed || !percent || !relative)) {
+  if (MOZ_UNLIKELY(!fixed || !percent || !relative)) {
     return; // NS_ERROR_OUT_OF_MEMORY
   }
 
   int32_t i, j;
  
   // initialize the fixed, percent, relative indices, allocate the fixed sizes and zero the others
   for (i = 0; i < aNumSpecs; i++) {   
     aValues[i] = 0;
@@ -1031,33 +1032,33 @@ nsHTMLFramesetFrame::Reflow(nsPresContex
         pseudoStyleContext = styleSet->
           ResolveAnonymousBoxStyle(nsCSSAnonBoxes::horizontalFramesetBorder,
                                    mStyleContext);
 
         borderFrame = new (shell) nsHTMLFramesetBorderFrame(pseudoStyleContext,
                                                             borderWidth,
                                                             false,
                                                             false);
-        if (NS_LIKELY(borderFrame != nullptr)) {
+        if (MOZ_LIKELY(borderFrame != nullptr)) {
           borderFrame->Init(mContent, this, nullptr);
           mChildCount++;
           mFrames.AppendFrame(nullptr, borderFrame);
           mHorBorders[cellIndex.y-1] = borderFrame;
           // set the neighbors for determining drag boundaries
           borderFrame->mPrevNeighbor = lastRow;
           borderFrame->mNextNeighbor = cellIndex.y;
         }
       } else {
         borderFrame = (nsHTMLFramesetBorderFrame*)mFrames.FrameAt(borderChildX);
-        if (NS_LIKELY(borderFrame != nullptr)) {
+        if (MOZ_LIKELY(borderFrame != nullptr)) {
           borderFrame->mWidth = borderWidth;
           borderChildX++;
         }
       }
-      if (NS_LIKELY(borderFrame != nullptr)) {
+      if (MOZ_LIKELY(borderFrame != nullptr)) {
         nsSize borderSize(aDesiredSize.width, borderWidth);
         ReflowPlaceChild(borderFrame, aPresContext, aReflowState, offset, borderSize);
         borderFrame = nullptr;
       }
       offset.y += borderWidth;
     } else {
       if (cellIndex.x > 0) {  // moved to next col in same row
         if (0 == cellIndex.y) { // in 1st row
@@ -1067,33 +1068,33 @@ nsHTMLFramesetFrame::Reflow(nsPresContex
             pseudoStyleContext = styleSet->
               ResolveAnonymousBoxStyle(nsCSSAnonBoxes::verticalFramesetBorder,
                                        mStyleContext);
 
             borderFrame = new (shell) nsHTMLFramesetBorderFrame(pseudoStyleContext, 
                                                                 borderWidth,
                                                                 true,
                                                                 false);
-            if (NS_LIKELY(borderFrame != nullptr)) {
+            if (MOZ_LIKELY(borderFrame != nullptr)) {
               borderFrame->Init(mContent, this, nullptr);
               mChildCount++;
               mFrames.AppendFrame(nullptr, borderFrame);
               mVerBorders[cellIndex.x-1] = borderFrame;
               // set the neighbors for determining drag boundaries
               borderFrame->mPrevNeighbor = lastCol;
               borderFrame->mNextNeighbor = cellIndex.x;
             }
           } else {         
             borderFrame = (nsHTMLFramesetBorderFrame*)mFrames.FrameAt(borderChildX);
-            if (NS_LIKELY(borderFrame != nullptr)) {
+            if (MOZ_LIKELY(borderFrame != nullptr)) {
               borderFrame->mWidth = borderWidth;
               borderChildX++;
             }
           }
-          if (NS_LIKELY(borderFrame != nullptr)) {
+          if (MOZ_LIKELY(borderFrame != nullptr)) {
             nsSize borderSize(borderWidth, aDesiredSize.height);
             ReflowPlaceChild(borderFrame, aPresContext, aReflowState, offset, borderSize);
             borderFrame = nullptr;
           }
         }
         offset.x += borderWidth;
       }
     }
@@ -1323,17 +1324,17 @@ nsHTMLFramesetFrame::RecalculateBorderRe
     return;
   }
 
   PR_STATIC_ASSERT(NS_MAX_FRAMESET_SPEC_COUNT < INT32_MAX / NS_MAX_FRAMESET_SPEC_COUNT);
   int32_t numCells = mNumRows * mNumCols; // max number of cells
   PR_STATIC_ASSERT(NS_MAX_FRAMESET_SPEC_COUNT
                    < UINT_MAX / sizeof(int32_t) / NS_MAX_FRAMESET_SPEC_COUNT); 
   nsAutoArrayPtr<int32_t> childTypes(new int32_t[numCells]);
-  if (NS_UNLIKELY(!childTypes)) {
+  if (MOZ_UNLIKELY(!childTypes)) {
     return;
   }
   int32_t childTypeIndex = 0;
 
   for (nsIContent *child = mContent->GetFirstChild(); child;
        child = child->GetNextSibling()) {
     if (child->IsHTML()) {
       nsINodeInfo *ni = child->NodeInfo();
--- a/layout/generic/nsInlineFrame.cpp
+++ b/layout/generic/nsInlineFrame.cpp
@@ -14,16 +14,17 @@
 #include "nsStyleContext.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsRenderingContext.h"
 #include "nsCSSAnonBoxes.h"
 #include "nsAutoPtr.h"
 #include "nsFrameManager.h"
 #include "nsDisplayList.h"
+#include "mozilla/Likely.h"
 
 #ifdef DEBUG
 #undef NOISY_PUSHING
 #endif
 
 using namespace mozilla;
 
 
@@ -501,17 +502,17 @@ nsInlineFrame::ReflowFrames(nsPresContex
           frameManager->ReparentStyleContext(child);
         }
         // We also need to do the same for |frame|'s next-in-flows that are in
         // the sibling list. Otherwise, if we reflow |frame| and it's complete
         // we'll crash when trying to delete its next-in-flow.
         // This scenario doesn't happen often, but it can happen.
         nsIFrame* nextSibling = child->GetNextSibling();
         child = child->GetNextInFlow();
-        if (NS_UNLIKELY(child)) {
+        if (MOZ_UNLIKELY(child)) {
           while (child != nextSibling && nextSibling) {
             nextSibling = nextSibling->GetNextSibling();
           }
           if (!nextSibling) {
             child = nullptr;
           }
         }
         MOZ_ASSERT(!child || mFrames.ContainsFrame(child));
--- a/layout/generic/nsLineBox.cpp
+++ b/layout/generic/nsLineBox.cpp
@@ -11,16 +11,17 @@
 #include "prprf.h"
 #include "nsBlockFrame.h"
 #include "nsIFrame.h"
 #include "nsPresArena.h"
 #ifdef IBMBIDI
 #include "nsBidiPresUtils.h"
 #endif
 #include "nsStyleStructInlines.h"
+#include "mozilla/Likely.h"
 
 #ifdef DEBUG
 static int32_t ctorCount;
 int32_t nsLineBox::GetCtorCount() { return ctorCount; }
 #endif
 
 #ifndef _MSC_VER
 // static nsLineBox constant; initialized in the header file.
@@ -48,17 +49,17 @@ nsLineBox::nsLineBox(nsIFrame* aFrame, i
   mChildCount = aCount;
   MarkDirty();
   mFlags.mBlock = aIsBlock;
 }
 
 nsLineBox::~nsLineBox()
 {
   MOZ_COUNT_DTOR(nsLineBox);
-  if (NS_UNLIKELY(mFlags.mHasHashedFrames)) {
+  if (MOZ_UNLIKELY(mFlags.mHasHashedFrames)) {
     delete mFrames;
   }  
   Cleanup();
 }
 
 nsLineBox*
 NS_NewLineBox(nsIPresShell* aPresShell, nsIFrame* aFrame, bool aIsBlock)
 {
@@ -94,17 +95,17 @@ nsLineBox::StealHashTableFrom(nsLineBox*
 
 void
 nsLineBox::NoteFramesMovedFrom(nsLineBox* aFromLine)
 {
   uint32_t fromCount = aFromLine->GetChildCount();
   uint32_t toCount = GetChildCount();
   MOZ_ASSERT(toCount <= fromCount, "moved more frames than aFromLine has");
   uint32_t fromNewCount = fromCount - toCount;
-  if (NS_LIKELY(!aFromLine->mFlags.mHasHashedFrames)) {
+  if (MOZ_LIKELY(!aFromLine->mFlags.mHasHashedFrames)) {
     aFromLine->mChildCount = fromNewCount;
     MOZ_ASSERT(toCount < kMinChildCountForHashtable);
   } else if (fromNewCount < kMinChildCountForHashtable) {
     // aFromLine has a hash table but will not have it after moving the frames
     // so this line can steal the hash table if it needs it.
     if (toCount >= kMinChildCountForHashtable) {
       StealHashTableFrom(aFromLine, fromNewCount);
     } else {
@@ -357,17 +358,17 @@ nsLineBox::DeleteLineList(nsPresContext*
 {
   nsIPresShell* shell = aPresContext->PresShell();
 
   // Keep our line list and frame list up to date as we
   // remove frames, in case something wants to traverse the
   // frame tree while we're destroying.
   while (!aLines.empty()) {
     nsLineBox* line = aLines.front();
-    if (NS_UNLIKELY(line->mFlags.mHasHashedFrames)) {
+    if (MOZ_UNLIKELY(line->mFlags.mHasHashedFrames)) {
       line->SwitchToCounter();  // Avoid expensive has table removals.
     }
     while (line->GetChildCount() > 0) {
       nsIFrame* child = aFrames->RemoveFirstChild();
       MOZ_ASSERT(child == line->mFirstChild, "Lines out of sync");
       line->mFirstChild = aFrames->FirstChild();
       line->NoteFrameRemoved(child);
       child->DestroyFrom(aDestructRoot);
@@ -386,17 +387,17 @@ nsLineBox::RFindLineContaining(nsIFrame*
                                int32_t* aFrameIndexInLine)
 {
   NS_PRECONDITION(aFrame, "null ptr");
 
   nsIFrame* curFrame = aLastFrameBeforeEnd;
   while (aBegin != aEnd) {
     --aEnd;
     NS_ASSERTION(aEnd->LastChild() == curFrame, "Unexpected curFrame");
-    if (NS_UNLIKELY(aEnd->mFlags.mHasHashedFrames) &&
+    if (MOZ_UNLIKELY(aEnd->mFlags.mHasHashedFrames) &&
         !aEnd->Contains(aFrame)) {
       if (aEnd->mFirstChild) {
         curFrame = aEnd->mFirstChild->GetPrevSibling();
       }
       continue;
     }
     // i is the index of curFrame in aEnd
     int32_t i = aEnd->GetChildCount() - 1;
--- a/layout/generic/nsLineBox.h
+++ b/layout/generic/nsLineBox.h
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* representation of one line within a block frame, a CSS line box */
 
 #ifndef nsLineBox_h___
 #define nsLineBox_h___
 
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 
 #include "nsILineIterator.h"
 #include "nsIFrame.h"
 
 class nsLineBox;
 class nsFloatCache;
 class nsFloatCacheList;
 class nsFloatCacheFreeList;
@@ -356,38 +357,38 @@ private:
     uint32_t count = GetChildCount();
     delete mFrames;
     mFlags.mHasHashedFrames = 0;
     mChildCount = count;
   }
 
 public:
   int32_t GetChildCount() const {
-    return NS_UNLIKELY(mFlags.mHasHashedFrames) ? mFrames->Count() : mChildCount;
+    return MOZ_UNLIKELY(mFlags.mHasHashedFrames) ? mFrames->Count() : mChildCount;
   }
 
   /**
    * Register that aFrame is now on this line.
    */
   void NoteFrameAdded(nsIFrame* aFrame) {
-    if (NS_UNLIKELY(mFlags.mHasHashedFrames)) {
+    if (MOZ_UNLIKELY(mFlags.mHasHashedFrames)) {
       mFrames->PutEntry(aFrame);
     } else {
       if (++mChildCount >= kMinChildCountForHashtable) {
         SwitchToHashtable();
       }
     }
   }
 
   /**
    * Register that aFrame is not on this line anymore.
    */
   void NoteFrameRemoved(nsIFrame* aFrame) {
     MOZ_ASSERT(GetChildCount() > 0);
-    if (NS_UNLIKELY(mFlags.mHasHashedFrames)) {
+    if (MOZ_UNLIKELY(mFlags.mHasHashedFrames)) {
       mFrames->RemoveEntry(aFrame);
       if (mFrames->Count() < kMinChildCountForHashtable) {
         SwitchToCounter();
       }
     } else {
       --mChildCount;
     }
   }
@@ -505,17 +506,17 @@ public:
   nsIFrame* LastChild() const;
 #endif
 
 private:
   int32_t IndexOf(nsIFrame* aFrame) const;
 public:
 
   bool Contains(nsIFrame* aFrame) const {
-    return NS_UNLIKELY(mFlags.mHasHashedFrames) ? mFrames->Contains(aFrame)
+    return MOZ_UNLIKELY(mFlags.mHasHashedFrames) ? mFrames->Contains(aFrame)
                                                 : IndexOf(aFrame) >= 0;
   }
 
   // whether the line box is "logically" empty (just like nsIFrame::IsEmpty)
   bool IsEmpty() const;
 
   // Call this only while in Reflow() for the block the line belongs
   // to, only between reflowing the line (or sliding it, if we skip
--- a/layout/generic/nsTextFrameThebes.cpp
+++ b/layout/generic/nsTextFrameThebes.cpp
@@ -65,20 +65,21 @@
 
 #include "nsBidiUtils.h"
 #include "nsPrintfCString.h"
 
 #include "gfxFont.h"
 #include "gfxContext.h"
 #include "gfxImageSurface.h"
 
+#include "mozilla/Attributes.h"
 #include "mozilla/dom/Element.h"
+#include "mozilla/Likely.h"
+#include "mozilla/LookAndFeel.h"
 #include "mozilla/Util.h" // for DebugOnly
-#include "mozilla/LookAndFeel.h"
-#include "mozilla/Attributes.h"
 
 #include "sampler.h"
 
 #ifdef DEBUG
 #undef NOISY_BLINK
 #undef NOISY_REFLOW
 #undef NOISY_TRIM
 #else
@@ -2390,31 +2391,31 @@ BuildTextRunsScanner::AssignTextRun(gfxT
         nsTextFrame* firstFrame = nullptr;
         uint32_t startOffset = 0;
         if (oldTextRun->GetFlags() & nsTextFrameUtils::TEXT_IS_SIMPLE_FLOW) {
           firstFrame = static_cast<nsTextFrame*>(oldTextRun->GetUserData());
         }
         else {
           TextRunUserData* userData = static_cast<TextRunUserData*>(oldTextRun->GetUserData());
           firstFrame = userData->mMappedFlows[0].mStartFrame;
-          if (NS_UNLIKELY(f != firstFrame)) {
+          if (MOZ_UNLIKELY(f != firstFrame)) {
             TextRunMappedFlow* flow = FindFlowForContent(userData, f->GetContent());
             if (flow) {
               startOffset = flow->mDOMOffsetToBeforeTransformOffset;
             }
             else {
               NS_ERROR("Can't find flow containing frame 'f'");
             }
           }
         }
 
         // Optimization: if |f| is the first frame in the flow then there are no
         // prev-continuations that use |oldTextRun|.
         nsTextFrame* clearFrom = nullptr;
-        if (NS_UNLIKELY(f != firstFrame)) {
+        if (MOZ_UNLIKELY(f != firstFrame)) {
           // If all the frames in the mapped flow starting at |f| (inclusive)
           // are empty then we let the prev-continuations keep the old text run.
           gfxSkipCharsIterator iter(oldTextRun->GetSkipChars(), startOffset, f->GetContentOffset());
           uint32_t textRunOffset = iter.ConvertOriginalToSkipped(f->GetContentOffset());
           clearFrom = textRunOffset == oldTextRun->GetLength() ? f : nullptr;
         }
         f->ClearTextRun(clearFrom, mWhichTextRun);
 
@@ -7685,17 +7686,17 @@ nsTextFrame::ReflowText(nsLineLayout& aL
     // newline if there is one.
     int32_t skipLength = newLineOffset >= 0 ? length - 1 : length;
     int32_t whitespaceCount =
       GetTrimmableWhitespaceCount(frag, offset, skipLength, 1);
     if (whitespaceCount) {
       offset += whitespaceCount;
       length -= whitespaceCount;
       // Make sure this frame maps the trimmable whitespace.
-      if (NS_UNLIKELY(offset > GetContentEnd())) {
+      if (MOZ_UNLIKELY(offset > GetContentEnd())) {
         SetLength(offset - GetContentOffset(), &aLineLayout,
                   ALLOW_FRAME_CREATION_AND_DESTRUCTION);
       }
     }
   }
 
   bool completedFirstLetter = false;
   // Layout dependent styles are a problem because we need to reconstruct
--- a/layout/mathml/nsMathMLContainerFrame.cpp
+++ b/layout/mathml/nsMathMLContainerFrame.cpp
@@ -21,16 +21,17 @@
 #include "nsGkAtoms.h"
 #include "nsMathMLParts.h"
 #include "nsMathMLContainerFrame.h"
 #include "nsAutoPtr.h"
 #include "nsStyleSet.h"
 #include "nsDisplayList.h"
 #include "nsCSSFrameConstructor.h"
 #include "nsIReflowCallback.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 
 //
 // nsMathMLContainerFrame implementation
 //
 
 NS_IMPL_FRAMEARENA_HELPERS(nsMathMLContainerFrame)
@@ -1385,17 +1386,17 @@ GetInterFrameSpacingFor(int32_t         
   return 0;
 }
 
 nscoord
 nsMathMLContainerFrame::FixInterFrameSpacing(nsHTMLReflowMetrics& aDesiredSize)
 {
   nscoord gap = 0;
   nsIContent* parentContent = mParent->GetContent();
-  if (NS_UNLIKELY(!parentContent)) {
+  if (MOZ_UNLIKELY(!parentContent)) {
     return 0;
   }
   nsIAtom *parentTag = parentContent->Tag();
   if (parentContent->GetNameSpaceID() == kNameSpaceID_MathML && 
       (parentTag == nsGkAtoms::math || parentTag == nsGkAtoms::mtd_)) {
     gap = GetInterFrameSpacingFor(GetStyleFont()->mScriptLevel, mParent, this);
     // add our own italic correction
     nscoord leftCorrection = 0, italicCorrection = 0;
@@ -1418,17 +1419,17 @@ nsMathMLContainerFrame::FixInterFrameSpa
   }
   return gap;
 }
 
 /* static */ void
 nsMathMLContainerFrame::DidReflowChildren(nsIFrame* aFirst, nsIFrame* aStop)
 
 {
-  if (NS_UNLIKELY(!aFirst))
+  if (MOZ_UNLIKELY(!aFirst))
     return;
 
   for (nsIFrame* frame = aFirst;
        frame != aStop;
        frame = frame->GetNextSibling()) {
     NS_ASSERTION(frame, "aStop isn't a sibling");
     if (frame->GetStateBits() & NS_FRAME_IN_REFLOW) {
       // finish off principal descendants, too
--- a/layout/mathml/nsMathMLContainerFrame.h
+++ b/layout/mathml/nsMathMLContainerFrame.h
@@ -11,16 +11,17 @@
 #include "nsContainerFrame.h"
 #include "nsBlockFrame.h"
 #include "nsInlineFrame.h"
 #include "nsMathMLAtoms.h"
 #include "nsMathMLOperators.h"
 #include "nsMathMLChar.h"
 #include "nsMathMLFrame.h"
 #include "nsMathMLParts.h"
+#include "mozilla/Likely.h"
 
 /*
  * Base class for MathML container frames. It acts like an inferred 
  * mrow. By default, this frame uses its Reflow() method to lay its 
  * children horizontally and ensure that their baselines are aligned.
  * The Reflow() method relies upon Place() to position children.
  * By overloading Place() in derived classes, it is therefore possible
  * to position children in various customized ways.
@@ -392,42 +393,42 @@ public:
 
   NS_IMETHOD
   AppendFrames(ChildListID     aListID,
                nsFrameList&    aFrameList)
   {
     NS_ASSERTION(aListID == kPrincipalList || aListID == kNoReflowPrincipalList,
                  "unexpected frame list");
     nsresult rv = nsBlockFrame::AppendFrames(aListID, aFrameList);
-    if (NS_LIKELY(aListID == kPrincipalList))
+    if (MOZ_LIKELY(aListID == kPrincipalList))
       nsMathMLContainerFrame::ReLayoutChildren(this);
     return rv;
   }
 
   NS_IMETHOD
   InsertFrames(ChildListID     aListID,
                nsIFrame*       aPrevFrame,
                nsFrameList&    aFrameList) MOZ_OVERRIDE
   {
     NS_ASSERTION(aListID == kPrincipalList || aListID == kNoReflowPrincipalList,
                  "unexpected frame list");
     nsresult rv = nsBlockFrame::InsertFrames(aListID, aPrevFrame, aFrameList);
-    if (NS_LIKELY(aListID == kPrincipalList))
+    if (MOZ_LIKELY(aListID == kPrincipalList))
       nsMathMLContainerFrame::ReLayoutChildren(this);
     return rv;
   }
 
   NS_IMETHOD
   RemoveFrame(ChildListID     aListID,
               nsIFrame*       aOldFrame) MOZ_OVERRIDE
   {
     NS_ASSERTION(aListID == kPrincipalList || aListID == kNoReflowPrincipalList,
                  "unexpected frame list");
     nsresult rv = nsBlockFrame::RemoveFrame(aListID, aOldFrame);
-    if (NS_LIKELY(aListID == kPrincipalList))
+    if (MOZ_LIKELY(aListID == kPrincipalList))
       nsMathMLContainerFrame::ReLayoutChildren(this);
     return rv;
   }
 
   virtual bool IsFrameOfType(uint32_t aFlags) const MOZ_OVERRIDE {
     return nsBlockFrame::IsFrameOfType(aFlags &
               ~(nsIFrame::eMathML | nsIFrame::eExcludesIgnorableWhitespace));
   }
@@ -462,42 +463,42 @@ public:
 
   NS_IMETHOD
   AppendFrames(ChildListID     aListID,
                nsFrameList&    aFrameList) MOZ_OVERRIDE
   {
     NS_ASSERTION(aListID == kPrincipalList || aListID == kNoReflowPrincipalList,
                  "unexpected frame list");
     nsresult rv = nsInlineFrame::AppendFrames(aListID, aFrameList);
-    if (NS_LIKELY(aListID == kPrincipalList))
+    if (MOZ_LIKELY(aListID == kPrincipalList))
       nsMathMLContainerFrame::ReLayoutChildren(this);
     return rv;
   }
 
   NS_IMETHOD
   InsertFrames(ChildListID     aListID,
                nsIFrame*       aPrevFrame,
                nsFrameList&    aFrameList) MOZ_OVERRIDE
   {
     NS_ASSERTION(aListID == kPrincipalList || aListID == kNoReflowPrincipalList,
                  "unexpected frame list");
     nsresult rv = nsInlineFrame::InsertFrames(aListID, aPrevFrame, aFrameList);
-    if (NS_LIKELY(aListID == kPrincipalList))
+    if (MOZ_LIKELY(aListID == kPrincipalList))
       nsMathMLContainerFrame::ReLayoutChildren(this);
     return rv;
   }
 
   NS_IMETHOD
   RemoveFrame(ChildListID     aListID,
               nsIFrame*       aOldFrame) MOZ_OVERRIDE
   {
     NS_ASSERTION(aListID == kPrincipalList || aListID == kNoReflowPrincipalList,
                  "unexpected frame list");
     nsresult rv = nsInlineFrame::RemoveFrame(aListID, aOldFrame);
-    if (NS_LIKELY(aListID == kPrincipalList))
+    if (MOZ_LIKELY(aListID == kPrincipalList))
       nsMathMLContainerFrame::ReLayoutChildren(this);
     return rv;
   }
 
   virtual bool IsFrameOfType(uint32_t aFlags) const {
       return nsInlineFrame::IsFrameOfType(aFlags &
                 ~(nsIFrame::eMathML | nsIFrame::eExcludesIgnorableWhitespace));
   }
--- a/layout/style/nsCSSRuleProcessor.cpp
+++ b/layout/style/nsCSSRuleProcessor.cpp
@@ -55,16 +55,17 @@
 #include "nsIObserverService.h"
 #include "nsNetCID.h"
 #include "mozilla/Services.h"
 #include "mozilla/dom/Element.h"
 #include "nsGenericElement.h"
 #include "nsNthIndexCache.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/LookAndFeel.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 #define VISITED_PSEUDO_PREF "layout.css.visited_links_enabled"
 
 static bool gSupportVisitedPseudo = true;
 
@@ -2838,17 +2839,17 @@ AddSelector(RuleCascadeData* aCascade,
 
 static bool
 AddRule(RuleSelectorPair* aRuleInfo, RuleCascadeData* aCascade)
 {
   RuleCascadeData * const cascade = aCascade;
 
   // Build the rule hash.
   nsCSSPseudoElements::Type pseudoType = aRuleInfo->mSelector->PseudoType();
-  if (NS_LIKELY(pseudoType == nsCSSPseudoElements::ePseudo_NotPseudoElement)) {
+  if (MOZ_LIKELY(pseudoType == nsCSSPseudoElements::ePseudo_NotPseudoElement)) {
     cascade->mRuleHash.AppendRule(*aRuleInfo);
   } else if (pseudoType < nsCSSPseudoElements::ePseudo_PseudoElementCount) {
     RuleHash*& ruleHash = cascade->mPseudoElementRuleHashes[pseudoType];
     if (!ruleHash) {
       ruleHash = new RuleHash(cascade->mQuirksMode);
       if (!ruleHash) {
         // Out of memory; give up
         return false;
@@ -3241,17 +3242,17 @@ nsCSSRuleProcessor::SelectorListMatches(
 void
 AncestorFilter::Init(Element *aElement)
 {
   MOZ_ASSERT(!mFilter);
   MOZ_ASSERT(mHashes.IsEmpty());
 
   mFilter = new Filter();
 
-  if (NS_LIKELY(aElement)) {
+  if (MOZ_LIKELY(aElement)) {
     MOZ_ASSERT(aElement->IsInDoc(),
                "aElement must be in the document for the assumption that "
                "GetParentNode() is non-null on all element ancestors of "
                "aElement to be true");
     // Collect up the ancestors
     nsAutoTArray<Element*, 50> ancestors;
     Element* cur = aElement;
     do {
--- a/layout/style/nsCSSScanner.cpp
+++ b/layout/style/nsCSSScanner.cpp
@@ -22,16 +22,17 @@
 #include "nsIConsoleService.h"
 #include "nsIScriptError.h"
 #include "nsIStringBundle.h"
 #include "nsIDocument.h"
 #include "mozilla/Services.h"
 #include "mozilla/css/Loader.h"
 #include "nsCSSStyleSheet.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 
 #ifdef CSS_REPORT_PARSE_ERRORS
 static bool gReportErrors = true;
 static nsIConsoleService *gConsoleService;
 static nsIFactory *gScriptErrorFactory;
 static nsIStringBundle *gStringBundle;
@@ -908,17 +909,17 @@ nsCSSScanner::NextURL(nsCSSToken& aToken
 #endif
       ParseString(ch, aToken);
     NS_ABORT_IF_FALSE(ok, "ParseString should never fail, "
                           "since there's always something read");
 
     NS_ABORT_IF_FALSE(aToken.mType == eCSSToken_String ||
                       aToken.mType == eCSSToken_Bad_String,
                       "unexpected token type");
-    if (NS_LIKELY(aToken.mType == eCSSToken_String)) {
+    if (MOZ_LIKELY(aToken.mType == eCSSToken_String)) {
       EatWhiteSpace();
       if (LookAheadOrEOF(')')) {
         aToken.mType = eCSSToken_URL;
       } else {
         aToken.mType = eCSSToken_Bad_URL;
       }
     } else {
       aToken.mType = eCSSToken_Bad_URL;
--- a/layout/style/nsCSSStyleSheet.cpp
+++ b/layout/style/nsCSSStyleSheet.cpp
@@ -33,16 +33,17 @@
 #include "nsCOMPtr.h"
 #include "nsContentUtils.h"
 #include "nsIScriptSecurityManager.h"
 #include "mozAutoDocUpdate.h"
 #include "mozilla/css/Declaration.h"
 #include "nsRuleNode.h"
 #include "nsMediaFeatures.h"
 #include "nsDOMClassInfoID.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 
 
 // -------------------------------
 // Style Rule List for the DOM
 //
 class CSSRuleListImpl : public nsICSSRuleList
@@ -1484,17 +1485,17 @@ nsCSSStyleSheet::AppendStyleRule(css::Ru
 void
 nsCSSStyleSheet::ReplaceStyleRule(css::Rule* aOld, css::Rule* aNew)
 {
   NS_PRECONDITION(mInner->mOrderedRules.Count() != 0, "can't have old rule");
   NS_PRECONDITION(mInner->mComplete, "No replacing in an incomplete sheet!");
 
   if (NS_SUCCEEDED(WillDirty())) {
     int32_t index = mInner->mOrderedRules.IndexOf(aOld);
-    if (NS_UNLIKELY(index == -1)) {
+    if (MOZ_UNLIKELY(index == -1)) {
       NS_NOTREACHED("Couldn't find old rule");
       return;
     }
     mInner->mOrderedRules.ReplaceObjectAt(aNew, index);
 
     aNew->SetStyleSheet(this);
     aOld->SetStyleSheet(nullptr);
     DidDirty();
--- a/layout/style/nsCSSValue.cpp
+++ b/layout/style/nsCSSValue.cpp
@@ -11,16 +11,17 @@
 #include "imgIRequest.h"
 #include "nsIPrincipal.h"
 #include "nsCSSProps.h"
 #include "nsContentUtils.h"
 #include "nsStyleUtil.h"
 #include "CSSCalc.h"
 #include "nsNetUtil.h"
 #include "mozilla/css/ImageLoader.h"
+#include "mozilla/Likely.h"
 
 namespace css = mozilla::css;
 
 nsCSSValue::nsCSSValue(int32_t aValue, nsCSSUnit aUnit)
   : mUnit(aUnit)
 {
   NS_ABORT_IF_FALSE(aUnit == eCSSUnit_Integer || aUnit == eCSSUnit_Enumerated ||
                     aUnit == eCSSUnit_EnumColor, "not an int value");
@@ -49,17 +50,17 @@ nsCSSValue::nsCSSValue(float aValue, nsC
 }
 
 nsCSSValue::nsCSSValue(const nsString& aValue, nsCSSUnit aUnit)
   : mUnit(aUnit)
 {
   NS_ABORT_IF_FALSE(UnitHasStringValue(), "not a string value");
   if (UnitHasStringValue()) {
     mValue.mString = BufferFromString(aValue).get();
-    if (NS_UNLIKELY(!mValue.mString)) {
+    if (MOZ_UNLIKELY(!mValue.mString)) {
       // XXXbz not much we can do here; just make sure that our promise of a
       // non-null mValue.mString holds for string units.
       mUnit = eCSSUnit_Null;
     }
   }
   else {
     mUnit = eCSSUnit_Null;
     mValue.mInt = 0;
@@ -338,17 +339,17 @@ void nsCSSValue::SetFloatValue(float aVa
 void nsCSSValue::SetStringValue(const nsString& aValue,
                                 nsCSSUnit aUnit)
 {
   Reset();
   mUnit = aUnit;
   NS_ABORT_IF_FALSE(UnitHasStringValue(), "not a string unit");
   if (UnitHasStringValue()) {
     mValue.mString = BufferFromString(aValue).get();
-    if (NS_UNLIKELY(!mValue.mString)) {
+    if (MOZ_UNLIKELY(!mValue.mString)) {
       // XXXbz not much we can do here; just make sure that our promise of a
       // non-null mValue.mString holds for string units.
       mUnit = eCSSUnit_Null;
     }
   } else
     mUnit = eCSSUnit_Null;
 }
 
@@ -628,17 +629,17 @@ nsCSSValue::BufferFromString(const nsStr
     return buffer;
   }
 
   nsString::size_type length = aValue.Length();
 
   // NOTE: Alloc prouduces a new, already-addref'd (refcnt = 1) buffer.
   // NOTE: String buffer allocation is currently fallible.
   buffer = nsStringBuffer::Alloc((length + 1) * sizeof(PRUnichar));
-  if (NS_UNLIKELY(!buffer)) {
+  if (MOZ_UNLIKELY(!buffer)) {
     NS_RUNTIMEABORT("out of memory");
   }
 
   PRUnichar* data = static_cast<PRUnichar*>(buffer->Data());
   nsCharTraits<PRUnichar>::copy(data, aValue.get(), length);
   // Null-terminate.
   data[length] = 0;
   return buffer;
--- a/layout/style/nsRuleNode.cpp
+++ b/layout/style/nsRuleNode.cpp
@@ -37,16 +37,17 @@
 #include "nsCSSProps.h"
 #include "nsTArray.h"
 #include "nsContentUtils.h"
 #include "CSSCalc.h"
 #include "nsPrintfCString.h"
 
 #include "mozilla/Assertions.h"
 #include "mozilla/dom/Element.h"
+#include "mozilla/Likely.h"
 #include "mozilla/LookAndFeel.h"
 #include "mozilla/Util.h"
 
 #if defined(_MSC_VER) || defined(__MINGW32__)
 #include <malloc.h>
 #ifdef _MSC_VER
 #define alloca _alloca
 #endif
@@ -2022,219 +2023,219 @@ nsRuleNode::WalkRuleTree(const nsStyleSt
 #define STYLE_STRUCT(name, checkdata_cb, ctor_args)                           \
   res = Compute##name##Data(startStruct, &ruleData, aContext,                 \
                             highestNode, detail, ruleData.mCanStoreInRuleTree);
 #include "nsStyleStructList.h"
 #undef STYLE_STRUCT
 #undef STYLE_STRUCT_TEST
 
   // If we have a post-resolve callback, handle that now.
-  if (ruleData.mPostResolveCallback && (NS_LIKELY(res != nullptr)))
+  if (ruleData.mPostResolveCallback && (MOZ_LIKELY(res != nullptr)))
     (*ruleData.mPostResolveCallback)(const_cast<void*>(res), &ruleData);
 
   // Now return the result.
   return res;
 }
 
 const void*
 nsRuleNode::SetDefaultOnRoot(const nsStyleStructID aSID, nsStyleContext* aContext)
 {
   switch (aSID) {
     case eStyleStruct_Font:
     {
       nsStyleFont* fontData = new (mPresContext) nsStyleFont(mPresContext);
-      if (NS_LIKELY(fontData != nullptr)) {
+      if (MOZ_LIKELY(fontData != nullptr)) {
         nscoord minimumFontSize = mPresContext->MinFontSize(fontData->mLanguage);
 
         if (minimumFontSize > 0 && !mPresContext->IsChrome()) {
           fontData->mFont.size = NS_MAX(fontData->mSize, minimumFontSize);
         }
         else {
           fontData->mFont.size = fontData->mSize;
         }
         aContext->SetStyle(eStyleStruct_Font, fontData);
       }
       return fontData;
     }
     case eStyleStruct_Display:
     {
       nsStyleDisplay* disp = new (mPresContext) nsStyleDisplay();
-      if (NS_LIKELY(disp != nullptr)) {
+      if (MOZ_LIKELY(disp != nullptr)) {
         aContext->SetStyle(eStyleStruct_Display, disp);
       }
       return disp;
     }
     case eStyleStruct_Visibility:
     {
       nsStyleVisibility* vis = new (mPresContext) nsStyleVisibility(mPresContext);
-      if (NS_LIKELY(vis != nullptr)) {
+      if (MOZ_LIKELY(vis != nullptr)) {
         aContext->SetStyle(eStyleStruct_Visibility, vis);
       }
       return vis;
     }
     case eStyleStruct_Text:
     {
       nsStyleText* text = new (mPresContext) nsStyleText();
-      if (NS_LIKELY(text != nullptr)) {
+      if (MOZ_LIKELY(text != nullptr)) {
         aContext->SetStyle(eStyleStruct_Text, text);
       }
       return text;
     }
     case eStyleStruct_TextReset:
     {
       nsStyleTextReset* text = new (mPresContext) nsStyleTextReset();
-      if (NS_LIKELY(text != nullptr)) {
+      if (MOZ_LIKELY(text != nullptr)) {
         aContext->SetStyle(eStyleStruct_TextReset, text);
       }
       return text;
     }
     case eStyleStruct_Color:
     {
       nsStyleColor* color = new (mPresContext) nsStyleColor(mPresContext);
-      if (NS_LIKELY(color != nullptr)) {
+      if (MOZ_LIKELY(color != nullptr)) {
         aContext->SetStyle(eStyleStruct_Color, color);
       }
       return color;
     }
     case eStyleStruct_Background:
     {
       nsStyleBackground* bg = new (mPresContext) nsStyleBackground();
-      if (NS_LIKELY(bg != nullptr)) {
+      if (MOZ_LIKELY(bg != nullptr)) {
         aContext->SetStyle(eStyleStruct_Background, bg);
       }
       return bg;
     }
     case eStyleStruct_Margin:
     {
       nsStyleMargin* margin = new (mPresContext) nsStyleMargin();
-      if (NS_LIKELY(margin != nullptr)) {
+      if (MOZ_LIKELY(margin != nullptr)) {
         aContext->SetStyle(eStyleStruct_Margin, margin);
       }
       return margin;
     }
     case eStyleStruct_Border:
     {
       nsStyleBorder* border = new (mPresContext) nsStyleBorder(mPresContext);
-      if (NS_LIKELY(border != nullptr)) {
+      if (MOZ_LIKELY(border != nullptr)) {
         aContext->SetStyle(eStyleStruct_Border, border);
       }
       return border;
     }
     case eStyleStruct_Padding:
     {
       nsStylePadding* padding = new (mPresContext) nsStylePadding();
-      if (NS_LIKELY(padding != nullptr)) {
+      if (MOZ_LIKELY(padding != nullptr)) {
         aContext->SetStyle(eStyleStruct_Padding, padding);
       }
       return padding;
     }
     case eStyleStruct_Outline:
     {
       nsStyleOutline* outline = new (mPresContext) nsStyleOutline(mPresContext);
-      if (NS_LIKELY(outline != nullptr)) {
+      if (MOZ_LIKELY(outline != nullptr)) {
         aContext->SetStyle(eStyleStruct_Outline, outline);
       }
       return outline;
     }
     case eStyleStruct_List:
     {
       nsStyleList* list = new (mPresContext) nsStyleList();
-      if (NS_LIKELY(list != nullptr)) {
+      if (MOZ_LIKELY(list != nullptr)) {
         aContext->SetStyle(eStyleStruct_List, list);
       }
       return list;
     }
     case eStyleStruct_Position:
     {
       nsStylePosition* pos = new (mPresContext) nsStylePosition();
-      if (NS_LIKELY(pos != nullptr)) {
+      if (MOZ_LIKELY(pos != nullptr)) {
         aContext->SetStyle(eStyleStruct_Position, pos);
       }
       return pos;
     }
     case eStyleStruct_Table:
     {
       nsStyleTable* table = new (mPresContext) nsStyleTable();
-      if (NS_LIKELY(table != nullptr)) {
+      if (MOZ_LIKELY(table != nullptr)) {
         aContext->SetStyle(eStyleStruct_Table, table);
       }
       return table;
     }
     case eStyleStruct_TableBorder:
     {
       nsStyleTableBorder* table = new (mPresContext) nsStyleTableBorder(mPresContext);
-      if (NS_LIKELY(table != nullptr)) {
+      if (MOZ_LIKELY(table != nullptr)) {
         aContext->SetStyle(eStyleStruct_TableBorder, table);
       }
       return table;
     }
     case eStyleStruct_Content:
     {
       nsStyleContent* content = new (mPresContext) nsStyleContent();
-      if (NS_LIKELY(content != nullptr)) {
+      if (MOZ_LIKELY(content != nullptr)) {
         aContext->SetStyle(eStyleStruct_Content, content);
       }
       return content;
     }
     case eStyleStruct_Quotes:
     {
       nsStyleQuotes* quotes = new (mPresContext) nsStyleQuotes();
-      if (NS_LIKELY(quotes != nullptr)) {
+      if (MOZ_LIKELY(quotes != nullptr)) {
         aContext->SetStyle(eStyleStruct_Quotes, quotes);
       }
       return quotes;
     }
     case eStyleStruct_UserInterface:
     {
       nsStyleUserInterface* ui = new (mPresContext) nsStyleUserInterface();
-      if (NS_LIKELY(ui != nullptr)) {
+      if (MOZ_LIKELY(ui != nullptr)) {
         aContext->SetStyle(eStyleStruct_UserInterface, ui);
       }
       return ui;
     }
     case eStyleStruct_UIReset:
     {
       nsStyleUIReset* ui = new (mPresContext) nsStyleUIReset();
-      if (NS_LIKELY(ui != nullptr)) {
+      if (MOZ_LIKELY(ui != nullptr)) {
         aContext->SetStyle(eStyleStruct_UIReset, ui);
       }
       return ui;
     }
 
     case eStyleStruct_XUL:
     {
       nsStyleXUL* xul = new (mPresContext) nsStyleXUL();
-      if (NS_LIKELY(xul != nullptr)) {
+      if (MOZ_LIKELY(xul != nullptr)) {
         aContext->SetStyle(eStyleStruct_XUL, xul);
       }
       return xul;
     }
 
     case eStyleStruct_Column:
     {
       nsStyleColumn* column = new (mPresContext) nsStyleColumn(mPresContext);
-      if (NS_LIKELY(column != nullptr)) {
+      if (MOZ_LIKELY(column != nullptr)) {
         aContext->SetStyle(eStyleStruct_Column, column);
       }
       return column;
     }
 
     case eStyleStruct_SVG:
     {
       nsStyleSVG* svg = new (mPresContext) nsStyleSVG();
-      if (NS_LIKELY(svg != nullptr)) {
+      if (MOZ_LIKELY(svg != nullptr)) {
         aContext->SetStyle(eStyleStruct_SVG, svg);
       }
       return svg;
     }
 
     case eStyleStruct_SVGReset:
     {
       nsStyleSVGReset* svgReset = new (mPresContext) nsStyleSVGReset();
-      if (NS_LIKELY(svgReset != nullptr)) {
+      if (MOZ_LIKELY(svgReset != nullptr)) {
         aContext->SetStyle(eStyleStruct_SVGReset, svgReset);
       }
       return svgReset;
     }
     default:
       /*
        * unhandled case: nsStyleStructID_Length.
        * last item of nsStyleStructID, to know its length.
@@ -2344,18 +2345,18 @@ nsRuleNode::AdjustLogicalBoxProp(nsStyle
         data_ = new (mPresContext) nsStyle##type_(*parentdata_);              \
       else                                                                    \
         data_ = new (mPresContext) nsStyle##type_ ctorargs_;                  \
     }                                                                         \
     else                                                                      \
       data_ = new (mPresContext) nsStyle##type_ ctorargs_;                    \
   }                                                                           \
                                                                               \
-  if (NS_UNLIKELY(!data_))                                                    \
-    return nullptr;  /* Out Of Memory */                                       \
+  if (MOZ_UNLIKELY(!data_))                                                   \
+    return nullptr;  /* Out Of Memory */                                      \
   if (!parentdata_)                                                           \
     parentdata_ = data_;
 
 /**
  * Begin an nsRuleNode::Compute*Data function for a reset struct.
  *
  * @param type_ The nsStyle* type this function computes.
  * @param ctorargs_ The arguments used for the default nsStyle* constructor.
@@ -2380,18 +2381,18 @@ nsRuleNode::AdjustLogicalBoxProp(nsStyle
   if (aStartStruct)                                                           \
     /* We only need to compute the delta between this computed data and */    \
     /* our computed data. */                                                  \
     data_ = new (mPresContext)                                                \
             nsStyle##type_(*static_cast<nsStyle##type_*>(aStartStruct));      \
   else                                                                        \
     data_ = new (mPresContext) nsStyle##type_ ctorargs_;                      \
                                                                               \
-  if (NS_UNLIKELY(!data_))                                                    \
-    return nullptr;  /* Out Of Memory */                                       \
+  if (MOZ_UNLIKELY(!data_))                                                   \
+    return nullptr;  /* Out Of Memory */                                      \
                                                                               \
   /* If |canStoreInRuleTree| might be true by the time we're done, we */      \
   /* can't call parentContext->GetStyle##type_() since it could recur into */ \
   /* setting the same struct on the same rule node, causing a leak. */        \
   const nsStyle##type_* parentdata_ = data_;                                  \
   if (parentContext &&                                                        \
       aRuleDetail != eRuleFullReset &&                                        \
       aRuleDetail != eRulePartialReset &&                                     \
@@ -2412,19 +2413,19 @@ nsRuleNode::AdjustLogicalBoxProp(nsStyle
                    "unless all properties have been specified with values "   \
                    "other than inherit");                                     \
   if (canStoreInRuleTree) {                                                   \
     /* We were fully specified and can therefore be cached right on the */    \
     /* rule node. */                                                          \
     if (!aHighestNode->mStyleData.mInheritedData) {                           \
       aHighestNode->mStyleData.mInheritedData =                               \
         new (mPresContext) nsInheritedStyleData;                              \
-      if (NS_UNLIKELY(!aHighestNode->mStyleData.mInheritedData)) {            \
+      if (MOZ_UNLIKELY(!aHighestNode->mStyleData.mInheritedData)) {           \
         data_->Destroy(mPresContext);                                         \
-        return nullptr;                                                        \
+        return nullptr;                                                       \
       }                                                                       \
     }                                                                         \
     NS_ASSERTION(!aHighestNode->mStyleData.mInheritedData->                   \
                    mStyleStructs[eStyleStruct_##type_],                       \
                  "Going to leak style data");                                 \
     aHighestNode->mStyleData.mInheritedData->                                 \
       mStyleStructs[eStyleStruct_##type_] = data_;                            \
     /* Propagate the bit down. */                                             \
@@ -2456,19 +2457,19 @@ nsRuleNode::AdjustLogicalBoxProp(nsStyle
     /* on the style context. */                                               \
     aContext->SetStyle(eStyleStruct_##type_, data_);                          \
   else {                                                                      \
     /* We were fully specified and can therefore be cached right on the */    \
     /* rule node. */                                                          \
     if (!aHighestNode->mStyleData.mResetData) {                               \
       aHighestNode->mStyleData.mResetData =                                   \
         new (mPresContext) nsResetStyleData;                                  \
-      if (NS_UNLIKELY(!aHighestNode->mStyleData.mResetData)) {                \
+      if (MOZ_UNLIKELY(!aHighestNode->mStyleData.mResetData)) {               \
         data_->Destroy(mPresContext);                                         \
-        return nullptr;                                                        \
+        return nullptr;                                                       \
       }                                                                       \
     }                                                                         \
     NS_ASSERTION(!aHighestNode->mStyleData.mResetData->                       \
                    mStyleStructs[eStyleStruct_##type_],                       \
                  "Going to leak style data");                                 \
     aHighestNode->mStyleData.mResetData->                                     \
       mStyleStructs[eStyleStruct_##type_] = data_;                            \
     /* Propagate the bit down. */                                             \
@@ -4710,17 +4711,17 @@ nsRuleNode::ComputeDisplayData(void* aSt
               NS_THEME_NONE, 0, 0, 0, 0);
 
   // binding: url, none, inherit
   const nsCSSValue* bindingValue = aRuleData->ValueForBinding();
   if (eCSSUnit_URL == bindingValue->GetUnit()) {
     mozilla::css::URLValue* url = bindingValue->GetURLStructValue();
     NS_ASSERTION(url, "What's going on here?");
 
-    if (NS_LIKELY(url->GetURI())) {
+    if (MOZ_LIKELY(url->GetURI())) {
       display->mBinding = url;
     } else {
       display->mBinding = nullptr;
     }
   }
   else if (eCSSUnit_None == bindingValue->GetUnit() ||
            eCSSUnit_Initial == bindingValue->GetUnit()) {
     display->mBinding = nullptr;
@@ -7675,26 +7676,26 @@ nsRuleNode::GetStyleData(nsStyleStructID
     // it has is also appropriate for this rule node.  Just go up the
     // rule tree and return the first cached struct we find.
     data = GetParentData(aSID);
     NS_ASSERTION(data, "dependent bits set but no cached struct present");
     return data;
   }
 
   data = mStyleData.GetStyleData(aSID);
-  if (NS_LIKELY(data != nullptr))
+  if (MOZ_LIKELY(data != nullptr))
     return data; // We have a fully specified struct. Just return it.
 
-  if (NS_UNLIKELY(!aComputeData))
+  if (MOZ_UNLIKELY(!aComputeData))
     return nullptr;
 
   // Nothing is cached.  We'll have to delve further and examine our rules.
   data = WalkRuleTree(aSID, aContext);
 
-  if (NS_LIKELY(data != nullptr))
+  if (MOZ_LIKELY(data != nullptr))
     return data;
 
   NS_NOTREACHED("could not create style struct");
   // To ensure that |GetStyleData| never returns null (even when we're
   // out of memory), we'll get the style set and get a copy of the
   // default values for the given style struct from the set.  Note that
   // this works fine even if |this| is a rule node that has been
   // destroyed (leftover from a previous rule tree) but is somehow still
@@ -7713,26 +7714,26 @@ nsRuleNode::GetStyle##name_(nsStyleConte
   if (mDependentBits &                                                        \
       nsCachedStyleData::GetBitForSID(eStyleStruct_##name_)) {                \
     data = GetParent##name_();                                                \
     NS_ASSERTION(data, "dependent bits set but no cached struct present");    \
     return data;                                                              \
   }                                                                           \
                                                                               \
   data = mStyleData.GetStyle##name_();                                        \
-  if (NS_LIKELY(data != nullptr))                                              \
+  if (MOZ_LIKELY(data != nullptr))                                            \
     return data;                                                              \
                                                                               \
-  if (NS_UNLIKELY(!aComputeData))                                             \
-    return nullptr;                                                            \
+  if (MOZ_UNLIKELY(!aComputeData))                                            \
+    return nullptr;                                                           \
                                                                               \
   data = static_cast<const nsStyle##name_ *>                                  \
            (WalkRuleTree(eStyleStruct_##name_, aContext));                    \
                                                                               \
-  if (NS_LIKELY(data != nullptr))                                              \
+  if (MOZ_LIKELY(data != nullptr))                                            \
     return data;                                                              \
                                                                               \
   NS_NOTREACHED("could not create style struct");                             \
   return                                                                      \
     static_cast<const nsStyle##name_ *>(                                      \
                    mPresContext->PresShell()->StyleSet()->                    \
                      DefaultStyleData()->GetStyleData(eStyleStruct_##name_)); \
 }
--- a/layout/style/nsStyleAnimation.cpp
+++ b/layout/style/nsStyleAnimation.cpp
@@ -15,16 +15,17 @@
 #include "nsString.h"
 #include "nsStyleContext.h"
 #include "nsStyleSet.h"
 #include "nsComputedDOMStyle.h"
 #include "nsCSSParser.h"
 #include "mozilla/css/Declaration.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/FloatingPoint.h"
+#include "mozilla/Likely.h"
 #include "prlog.h"
 #include <math.h>
 #include "gfxMatrix.h"
 #include "gfxQuaternion.h"
 #include "nsPrintfCString.h"
 
 using namespace mozilla;
 
@@ -873,23 +874,23 @@ EnsureNotNan(T aValue)
 {
   return aValue;
 }
 template<>
 MOZ_ALWAYS_INLINE float
 EnsureNotNan(float aValue)
 {
   // This would benefit from a MOZ_FLOAT_IS_NaN if we had one.
-  return NS_LIKELY(!MOZ_DOUBLE_IS_NaN(aValue)) ? aValue : 0;
+  return MOZ_LIKELY(!MOZ_DOUBLE_IS_NaN(aValue)) ? aValue : 0;
 }
 template<>
 MOZ_ALWAYS_INLINE double
 EnsureNotNan(double aValue)
 {
-  return NS_LIKELY(!MOZ_DOUBLE_IS_NaN(aValue)) ? aValue : 0;
+  return MOZ_LIKELY(!MOZ_DOUBLE_IS_NaN(aValue)) ? aValue : 0;
 }
 
 template <typename T>
 T
 RestrictValue(uint32_t aRestrictions, T aValue)
 {
   T result = EnsureNotNan(aValue);
   switch (aRestrictions) {
@@ -3374,17 +3375,17 @@ nsStyleAnimation::Value::SetColorValue(n
 }
 
 void
 nsStyleAnimation::Value::SetUnparsedStringValue(const nsString& aString)
 {
   FreeValue();
   mUnit = eUnit_UnparsedString;
   mValue.mString = nsCSSValue::BufferFromString(aString).get();
-  if (NS_UNLIKELY(!mValue.mString)) {
+  if (MOZ_UNLIKELY(!mValue.mString)) {
     // not much we can do here; just make sure that our promise of a
     // non-null mValue.mString holds for string units.
     mUnit = eUnit_Null;
   }
 }
 
 void
 nsStyleAnimation::Value::SetAndAdoptCSSValueValue(nsCSSValue *aValue,
--- a/layout/style/nsStyleStruct.cpp
+++ b/layout/style/nsStyleStruct.cpp
@@ -27,16 +27,18 @@
 #include "nsSVGUtils.h"
 #include "nsBidiUtils.h"
 #include "nsLayoutUtils.h"
 
 #include "imgIRequest.h"
 #include "imgIContainer.h"
 #include "prlog.h"
 
+#include "mozilla/Likely.h"
+
 MOZ_STATIC_ASSERT((((1 << nsStyleStructID_Length) - 1) &
                    ~(NS_STYLE_INHERIT_MASK)) == 0,
                   "Not enough bits in NS_STYLE_INHERIT_MASK");
 
 inline bool IsFixedUnit(const nsStyleCoord& aCoord, bool aEnumOK)
 {
   return aCoord.ConvertsToLength() || 
          (aEnumOK && aCoord.GetUnit() == eStyleUnit_Enumerated);
@@ -379,17 +381,17 @@ nsBorderColors::~nsBorderColors()
 {
   NS_CSS_DELETE_LIST_MEMBER(nsBorderColors, this, mNext);
 }
 
 nsBorderColors*
 nsBorderColors::Clone(bool aDeep) const
 {
   nsBorderColors* result = new nsBorderColors(mColor);
-  if (NS_UNLIKELY(!result))
+  if (MOZ_UNLIKELY(!result))
     return result;
   if (aDeep)
     NS_CSS_CLONE_LIST_MEMBER(nsBorderColors, this, mNext, result, (false));
   return result;
 }
 
 nsStyleBorder::nsStyleBorder(const nsStyleBorder& aSrc)
   : mBorderColors(nullptr),
--- a/layout/tables/nsTableFrame.cpp
+++ b/layout/tables/nsTableFrame.cpp
@@ -33,16 +33,17 @@
 #include "nsFrameManager.h"
 #include "nsError.h"
 #include "nsAutoPtr.h"
 #include "nsCSSFrameConstructor.h"
 #include "nsStyleSet.h"
 #include "nsDisplayList.h"
 #include "nsIScrollableFrame.h"
 #include "nsCSSProps.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 using namespace mozilla::layout;
 
 /********************************************************************************
  ** nsTableReflowState                                                         **
  ********************************************************************************/
 
@@ -1401,17 +1402,17 @@ nsTableFrame::ProcessRowInserted(nscoord
     }
   }
 }
 
 /* virtual */ void
 nsTableFrame::MarkIntrinsicWidthsDirty()
 {
   nsITableLayoutStrategy* tls = LayoutStrategy();
-  if (NS_UNLIKELY(!tls)) {
+  if (MOZ_UNLIKELY(!tls)) {
     // This is a FrameNeedsReflow() from nsBlockFrame::RemoveFrame()
     // walking up the ancestor chain in a table next-in-flow.  In this case
     // our original first-in-flow (which owns the TableLayoutStrategy) has
     // already been destroyed and unhooked from the flow chain and thusly
     // LayoutStrategy() returns null.  All the frames in the flow will be
     // destroyed so no need to mark anything dirty here.  See bug 595758.
     return;
   }
@@ -2186,17 +2187,17 @@ nsTableFrame::HomogenousInsertFrames(Chi
       nsIContent* parentContent = GetContent();
       nsIContent* content;
       aPrevFrame = nullptr;
       while (pseudoFrame  && (parentContent ==
                               (content = pseudoFrame->GetContent()))) {
         pseudoFrame = pseudoFrame->GetFirstPrincipalChild();
       }
       nsCOMPtr<nsIContent> container = content->GetParent();
-      if (NS_LIKELY(container)) { // XXX need this null-check, see bug 411823.
+      if (MOZ_LIKELY(container)) { // XXX need this null-check, see bug 411823.
         int32_t newIndex = container->IndexOf(content);
         nsIFrame* kidFrame;
         bool isColGroup = (NS_STYLE_DISPLAY_TABLE_COLUMN_GROUP ==
                              display->mDisplay);
         nsTableColGroupFrame* lastColGroup;
         if (isColGroup) {
           kidFrame = mColGroups.FirstChild();
           lastColGroup = nsTableColGroupFrame::GetLastRealColGroup(this);
--- a/layout/xul/base/src/nsMenuFrame.cpp
+++ b/layout/xul/base/src/nsMenuFrame.cpp
@@ -32,20 +32,21 @@
 #include "nsIStringBundle.h"
 #include "nsGUIEvent.h"
 #include "nsContentUtils.h"
 #include "nsDisplayList.h"
 #include "nsIReflowCallback.h"
 #include "nsISound.h"
 #include "nsEventStateManager.h"
 #include "nsIDOMXULMenuListElement.h"
-#include "mozilla/Services.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
+#include "mozilla/LookAndFeel.h"
 #include "mozilla/Preferences.h"
-#include "mozilla/LookAndFeel.h"
-#include "mozilla/Attributes.h"
+#include "mozilla/Services.h"
 
 using namespace mozilla;
 
 #define NS_MENU_POPUP_LIST_INDEX 0
 
 #if defined(XP_WIN) || defined(XP_OS2)
 #define NSCONTEXTMENUISMOUSEUP 1
 #endif
@@ -246,17 +247,17 @@ NS_IMETHODIMP
 nsMenuFrame::Init(nsIContent*      aContent,
                   nsIFrame*        aParent,
                   nsIFrame*        aPrevInFlow)
 {
   nsresult  rv = nsBoxFrame::Init(aContent, aParent, aPrevInFlow);
 
   // Set up a mediator which can be used for callbacks on this frame.
   mTimerMediator = new nsMenuTimerMediator(this);
-  if (NS_UNLIKELY(!mTimerMediator))
+  if (MOZ_UNLIKELY(!mTimerMediator))
     return NS_ERROR_OUT_OF_MEMORY;
 
   InitMenuParent(aParent);
 
   BuildAcceleratorText(false);
   nsIReflowCallback* cb = new nsASyncMenuInitialization(this);
   NS_ENSURE_TRUE(cb, NS_ERROR_OUT_OF_MEMORY);
   PresContext()->PresShell()->PostReflowCallback(cb);
@@ -1295,17 +1296,17 @@ nsMenuFrame::InsertFrames(ChildListID   
         FrameNeedsReflow(this, nsIPresShell::eTreeChange,
                          NS_FRAME_HAS_DIRTY_CHILDREN);
     }
   }
 
   if (aFrameList.IsEmpty())
     return NS_OK;
 
-  if (NS_UNLIKELY(aPrevFrame && aPrevFrame == GetPopup())) {
+  if (MOZ_UNLIKELY(aPrevFrame && aPrevFrame == GetPopup())) {
     aPrevFrame = nullptr;
   }
 
   return nsBoxFrame::InsertFrames(aListID, aPrevFrame, aFrameList);
 }
 
 NS_IMETHODIMP
 nsMenuFrame::AppendFrames(ChildListID     aListID,
--- a/layout/xul/base/src/nsSprocketLayout.cpp
+++ b/layout/xul/base/src/nsSprocketLayout.cpp
@@ -14,16 +14,17 @@
 #include "nsSprocketLayout.h"
 #include "nsPresContext.h"
 #include "nsCOMPtr.h"
 #include "nsIContent.h"
 #include "nsIPresShell.h"
 #include "nsContainerFrame.h"
 #include "nsBoxFrame.h"
 #include "StackArena.h"
+#include "mozilla/Likely.h"
 
 nsBoxLayout* nsSprocketLayout::gInstance = nullptr;
 
 //#define DEBUG_GROW
 
 #define DEBUG_SPRING_SIZE 8
 #define DEBUG_BORDER_SIZE 2
 #define COIL_SIZE 8
@@ -832,17 +833,17 @@ nsSprocketLayout::PopulateBoxSizes(nsIFr
     last = currentBox;
     currentBox = currentBox->next;
 
   }
 
   if (childCount > 0) {
     nscoord maxAllowedFlex = nscoord_MAX / childCount;
   
-    if (NS_UNLIKELY(maxFlex > maxAllowedFlex)) {
+    if (MOZ_UNLIKELY(maxFlex > maxAllowedFlex)) {
       // clamp all the flexes
       currentBox = aBoxSizes;
       while (currentBox) {
         currentBox->flex = NS_MIN(currentBox->flex, maxAllowedFlex);
         currentBox = currentBox->next;      
       }
     }
   }
--- a/layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
+++ b/layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
@@ -53,16 +53,18 @@
 #include "nsLayoutUtils.h"
 #include "nsIScrollableFrame.h"
 #include "nsEventDispatcher.h"
 #include "nsDisplayList.h"
 #include "nsTreeBoxObject.h"
 #include "nsRenderingContext.h"
 #include "nsIScriptableRegion.h"
 
+#include "mozilla/Likely.h"
+
 #ifdef ACCESSIBILITY
 #include "nsAccessibilityService.h"
 #endif
 #ifdef IBMBIDI
 #include "nsBidiUtils.h"
 #endif
 
 using namespace mozilla;
@@ -176,17 +178,17 @@ nsSize
 nsTreeBodyFrame::GetMinSize(nsBoxLayoutState& aBoxLayoutState)
 {
   EnsureView();
 
   nsIContent* baseElement = GetBaseElement();
 
   nsSize min(0,0);
   int32_t desiredRows;
-  if (NS_UNLIKELY(!baseElement)) {
+  if (MOZ_UNLIKELY(!baseElement)) {
     desiredRows = 0;
   }
   else if (baseElement->Tag() == nsGkAtoms::select &&
            baseElement->IsHTML()) {
     min.width = CalcMaxRowWidth();
     nsAutoString size;
     baseElement->GetAttr(kNameSpaceID_None, nsGkAtoms::size, size);
     if (!size.IsEmpty()) {
--- a/netwerk/base/public/nsReadLine.h
+++ b/netwerk/base/public/nsReadLine.h
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsReadLine_h__
 #define nsReadLine_h__
 
 #include "prmem.h"
 #include "nsIInputStream.h"
+#include "mozilla/Likely.h"
 
 /**
  * @file
  * Functions to read complete lines from an input stream.
  *
  * To properly use the helper function in here (NS_ReadLine) the caller
  * needs to declare a pointer to an nsLineBuffer, call
  * NS_InitLineBuffer on it, and pass it to NS_ReadLine every time it
@@ -109,17 +110,17 @@ NS_ReadLine (StreamType* aStream, nsLine
   CharT eolchar = 0; // the first eol char or 1 after \r\n or \n\r is found
 
   aLine.Truncate();
 
   while (1) { // will be returning out of this loop on eol or eof
     if (aBuffer->start == aBuffer->end) { // buffer is empty.  Read into it.
       uint32_t bytesRead;
       nsresult rv = aStream->Read(aBuffer->buf, kLineBufferSize, &bytesRead);
-      if (NS_FAILED(rv) || NS_UNLIKELY(bytesRead == 0)) {
+      if (NS_FAILED(rv) || MOZ_UNLIKELY(bytesRead == 0)) {
         *more = false;
         return rv;
       }
       aBuffer->start = aBuffer->buf;
       aBuffer->end = aBuffer->buf + bytesRead;
       *(aBuffer->end) = '\0';
     }
 
@@ -129,27 +130,27 @@ NS_ReadLine (StreamType* aStream, nsLine
      *  1. the eol char is the last char in the buffer
      *  2. the eol char + one more char at the end of the buffer
      *  3. the eol char + two or more chars at the end of the buffer
      * we need at least one char after the first eol char to determine if
      * it's a \r\n or \n\r sequence (and skip over it), and we need one
      * more char after the end-of-line to set |more| correctly.
      */
     CharT* current = aBuffer->start;
-    if (NS_LIKELY(eolchar == 0)) {
+    if (MOZ_LIKELY(eolchar == 0)) {
       for ( ; current < aBuffer->end; ++current) {
         if (*current == '\n' || *current == '\r') {
           eolchar = *current;
           *current++ = '\0';
           aLine.Append(aBuffer->start);
           break;
         }
       }
     }
-    if (NS_LIKELY(eolchar != 0)) {
+    if (MOZ_LIKELY(eolchar != 0)) {
       for ( ; current < aBuffer->end; ++current) {
         if ((eolchar == '\r' && *current == '\n') ||
             (eolchar == '\n' && *current == '\r')) {
           eolchar = 1;
           continue;
         }
         aBuffer->start = current;
         *more = true;
--- a/netwerk/base/src/nsSocketTransportService2.cpp
+++ b/netwerk/base/src/nsSocketTransportService2.cpp
@@ -17,16 +17,17 @@
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIOService.h"
 #include "NetworkActivityMonitor.h"
 #include "nsIObserverService.h"
 #include "mozilla/Services.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/Likely.h"
 
 
 // XXX: There is no good header file to put these in. :(
 namespace mozilla { namespace psm {
 
 void InitializeSSLServerCertVerificationThreads();
 void StopSSLServerCertVerificationThreads();
 
@@ -789,17 +790,17 @@ nsSocketTransportService::DoPollIteratio
             }
             // check for timeout errors unless disabled...
             else if (s.mHandler->mPollTimeout != UINT16_MAX) {
                 // update elapsed time counter
                 // (NOTE: We explicitly cast UINT16_MAX to be an unsigned value
                 // here -- otherwise, some compilers will treat it as signed,
                 // which makes them fire signed/unsigned-comparison build
                 // warnings for the comparison against 'pollInterval'.)
-                if (NS_UNLIKELY(pollInterval >
+                if (MOZ_UNLIKELY(pollInterval >
                                 static_cast<uint32_t>(UINT16_MAX) -
                                 s.mElapsedTime))
                     s.mElapsedTime = UINT16_MAX;
                 else
                     s.mElapsedTime += uint16_t(pollInterval);
                 // check for timeout expiration 
                 if (s.mElapsedTime >= s.mHandler->mPollTimeout) {
                     s.mElapsedTime = 0;
--- a/netwerk/cookie/nsCookieService.cpp
+++ b/netwerk/cookie/nsCookieService.cpp
@@ -43,16 +43,17 @@
 #include "nsNetUtil.h"
 #include "nsNetCID.h"
 #include "nsAppDirectoryServiceDefs.h"
 #include "nsIPrivateBrowsingService.h"
 #include "nsNetCID.h"
 #include "mozilla/storage.h"
 #include "mozilla/Util.h" // for DebugOnly
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 #include "nsIAppsService.h"
 #include "mozIApplication.h"
 
 using namespace mozilla;
 using namespace mozilla::net;
 
 // Create key from baseDomain that will access the default cookie namespace.
 // TODO: When we figure out what the API will look like for nsICookieManager{2}
@@ -2067,21 +2068,21 @@ nsCookieService::CancelAsyncRead(bool aP
 
 void
 nsCookieService::EnsureReadDomain(const nsCookieKey &aKey)
 {
   NS_ASSERTION(!mDBState->dbConn || mDBState == mDefaultDBState,
     "not in default db state");
 
   // Fast path 1: nothing to read, or we've already finished reading.
-  if (NS_LIKELY(!mDBState->dbConn || !mDefaultDBState->pendingRead))
+  if (MOZ_LIKELY(!mDBState->dbConn || !mDefaultDBState->pendingRead))
     return;
 
   // Fast path 2: already read in this particular domain.
-  if (NS_LIKELY(mDefaultDBState->readSet.GetEntry(aKey)))
+  if (MOZ_LIKELY(mDefaultDBState->readSet.GetEntry(aKey)))
     return;
 
   // Read in the data synchronously.
   nsresult rv;
   if (!mDefaultDBState->stmtReadDomain) {
     // Cache the statement, since it's likely to be used again.
     rv = mDefaultDBState->syncConn->CreateStatement(NS_LITERAL_CSTRING(
       "SELECT "
@@ -2162,17 +2163,17 @@ nsCookieService::EnsureReadDomain(const 
 
 void
 nsCookieService::EnsureReadComplete()
 {
   NS_ASSERTION(!mDBState->dbConn || mDBState == mDefaultDBState,
     "not in default db state");
 
   // Fast path 1: nothing to read, or we've already finished reading.
-  if (NS_LIKELY(!mDBState->dbConn || !mDefaultDBState->pendingRead))
+  if (MOZ_LIKELY(!mDBState->dbConn || !mDefaultDBState->pendingRead))
     return;
 
   // Cancel the pending read, so we don't get any more results.
   CancelAsyncRead(false);
 
   // Read in the data synchronously.
   nsCOMPtr<mozIStorageStatement> stmt;
   nsresult rv = mDefaultDBState->syncConn->CreateStatement(NS_LITERAL_CSTRING(
--- a/parser/html/nsHtml5TokenizerCppSupplement.h
+++ b/parser/html/nsHtml5TokenizerCppSupplement.h
@@ -1,12 +1,14 @@
 /* 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 "mozilla/Likely.h"
+
 void
 nsHtml5Tokenizer::StartPlainText()
 {
   stateSave = NS_HTML5TOKENIZER_PLAINTEXT;
 }
 
 void
 nsHtml5Tokenizer::EnableViewSource(nsHtml5Highlighter* aHighlighter)
@@ -32,22 +34,22 @@ nsHtml5Tokenizer::EndViewSource()
   mViewSource->End();
 }
 
 void
 nsHtml5Tokenizer::errWarnLtSlashInRcdata()
 {
 }
 
-// The null checks below annotated NS_LIKELY are not actually necessary.
+// The null checks below annotated MOZ_LIKELY are not actually necessary.
 
 void
 nsHtml5Tokenizer::errUnquotedAttributeValOrNull(PRUnichar c)
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     switch (c) {
       case '<':
         mViewSource->AddErrorToCurrentNode("errUnquotedAttributeLt");
         return;
       case '`':
         mViewSource->AddErrorToCurrentNode("errUnquotedAttributeGrave");
         return;
       case '\'':
@@ -59,17 +61,17 @@ nsHtml5Tokenizer::errUnquotedAttributeVa
         return;
     }
   }
 }
 
 void
 nsHtml5Tokenizer::errLtOrEqualsOrGraveInUnquotedAttributeOrNull(PRUnichar c)
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     switch (c) {
       case '=':
         mViewSource->AddErrorToCurrentNode("errUnquotedAttributeStartEquals");
         return;
       case '<':
         mViewSource->AddErrorToCurrentNode("errUnquotedAttributeStartLt");
         return;
       case '`':
@@ -77,39 +79,39 @@ nsHtml5Tokenizer::errLtOrEqualsOrGraveIn
         return;
     }
   }
 }
 
 void
 nsHtml5Tokenizer::errBadCharBeforeAttributeNameOrNull(PRUnichar c)
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     if (c == '<') {
       mViewSource->AddErrorToCurrentNode("errBadCharBeforeAttributeNameLt");
     } else if (c == '=') {
       errEqualsSignBeforeAttributeName();
     } else if (c != 0xFFFD) {
       errQuoteBeforeAttributeName(c);
     }
   }
 }
 
 void
 nsHtml5Tokenizer::errBadCharAfterLt(PRUnichar c)
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errBadCharAfterLt");
   }
 }
 
 void
 nsHtml5Tokenizer::errQuoteOrLtInAttributeNameOrNull(PRUnichar c)
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     if (c == '<') {
       mViewSource->AddErrorToCurrentNode("errLtInAttributeName");
     } else if (c != 0xFFFD) {
       mViewSource->AddErrorToCurrentNode("errQuoteInAttributeName");
     }
   }
 }
 
@@ -131,398 +133,398 @@ nsHtml5Tokenizer::maybeErrSlashInEndTag(
   if (mViewSource && selfClosing && endTag) {
     mViewSource->AddErrorToCurrentSlash("maybeErrSlashInEndTag");
   }
 }
 
 PRUnichar
 nsHtml5Tokenizer::errNcrNonCharacter(PRUnichar ch)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNcrNonCharacter");
   }
   return ch;
 }
 
 void
 nsHtml5Tokenizer::errAstralNonCharacter(int32_t ch)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNcrNonCharacter");
   }
 }
 
 PRUnichar
 nsHtml5Tokenizer::errNcrControlChar(PRUnichar ch)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNcrControlChar");
   }
   return ch;
 }
 
 void
 nsHtml5Tokenizer::errGarbageAfterLtSlash()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errGarbageAfterLtSlash");
   }
 }
 
 void
 nsHtml5Tokenizer::errLtSlashGt()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errLtSlashGt");
   }
 }
 
 void
 nsHtml5Tokenizer::errCharRefLacksSemicolon()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errCharRefLacksSemicolon");
   }
 }
 
 void
 nsHtml5Tokenizer::errNoDigitsInNCR()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNoDigitsInNCR");
   }
 }
 
 void
 nsHtml5Tokenizer::errGtInSystemId()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errGtInSystemId");
   }
 }
 
 void
 nsHtml5Tokenizer::errGtInPublicId()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errGtInPublicId");
   }
 }
 
 void
 nsHtml5Tokenizer::errNamelessDoctype()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNamelessDoctype");
   }
 }
 
 void
 nsHtml5Tokenizer::errConsecutiveHyphens()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errConsecutiveHyphens");
   }
 }
 
 void
 nsHtml5Tokenizer::errPrematureEndOfComment()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errPrematureEndOfComment");
   }
 }
 
 void
 nsHtml5Tokenizer::errBogusComment()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errBogusComment");
   }
 }
 
 void
 nsHtml5Tokenizer::errSlashNotFollowedByGt()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentSlash("errSlashNotFollowedByGt");
   }
 }
 
 void
 nsHtml5Tokenizer::errNoSpaceBetweenAttributes()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNoSpaceBetweenAttributes");
   }
 }
 
 void
 nsHtml5Tokenizer::errAttributeValueMissing()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errAttributeValueMissing");
   }
 }
 
 void
 nsHtml5Tokenizer::errEqualsSignBeforeAttributeName()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errEqualsSignBeforeAttributeName");
   }
 }
 
 void
 nsHtml5Tokenizer::errLtGt()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errLtGt");
   }
 }
 
 void
 nsHtml5Tokenizer::errProcessingInstruction()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errProcessingInstruction");
   }
 }
 
 void
 nsHtml5Tokenizer::errUnescapedAmpersandInterpretedAsCharacterReference()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentAmpersand("errUnescapedAmpersandInterpretedAsCharacterReference");
   }
 }
 
 void
 nsHtml5Tokenizer::errNotSemicolonTerminated()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNotSemicolonTerminated");
   }
 }
 
 void
 nsHtml5Tokenizer::errNoNamedCharacterMatch()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentAmpersand("errNoNamedCharacterMatch");
   }
 }
 
 void
 nsHtml5Tokenizer::errQuoteBeforeAttributeName(PRUnichar c)
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errQuoteBeforeAttributeName");
   }
 }
 
 void
 nsHtml5Tokenizer::errExpectedPublicId()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errExpectedPublicId");
   }
 }
 
 void
 nsHtml5Tokenizer::errBogusDoctype()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errBogusDoctype");
   }
 }
 
 void
 nsHtml5Tokenizer::errNcrSurrogate()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNcrSurrogate");
   }
 }
 
 void
 nsHtml5Tokenizer::errNcrCr()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNcrCr");
   }
 }
 
 void
 nsHtml5Tokenizer::errNcrInC1Range()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNcrInC1Range");
   }
 }
 
 void
 nsHtml5Tokenizer::errEofInPublicId()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEofInPublicId");
   }
 }
 
 void
 nsHtml5Tokenizer::errEofInComment()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEofInComment");
   }
 }
 
 void
 nsHtml5Tokenizer::errEofInDoctype()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEofInDoctype");
   }
 }
 
 void
 nsHtml5Tokenizer::errEofInAttributeValue()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEofInAttributeValue");
   }
 }
 
 void
 nsHtml5Tokenizer::errEofInAttributeName()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEofInAttributeName");
   }
 }
 
 void
 nsHtml5Tokenizer::errEofWithoutGt()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEofWithoutGt");
   }
 }
 
 void
 nsHtml5Tokenizer::errEofInTagName()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEofInTagName");
   }
 }
 
 void
 nsHtml5Tokenizer::errEofInEndTag()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEofInEndTag");
   }
 }
 
 void
 nsHtml5Tokenizer::errEofAfterLt()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEofAfterLt");
   }
 }
 
 void
 nsHtml5Tokenizer::errNcrOutOfRange()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNcrOutOfRange");
   }
 }
 
 void
 nsHtml5Tokenizer::errNcrUnassigned()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNcrUnassigned");
   }
 }
 
 void
 nsHtml5Tokenizer::errDuplicateAttribute()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errDuplicateAttribute");
   }
 }
 
 void
 nsHtml5Tokenizer::errEofInSystemId()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEofInSystemId");
   }
 }
 
 void
 nsHtml5Tokenizer::errExpectedSystemId()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errExpectedSystemId");
   }
 }
 
 void
 nsHtml5Tokenizer::errMissingSpaceBeforeDoctypeName()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errMissingSpaceBeforeDoctypeName");
   }
 }
 
 void
 nsHtml5Tokenizer::errHyphenHyphenBang()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errHyphenHyphenBang");
   }
 }
 
 void
 nsHtml5Tokenizer::errNcrControlChar()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNcrControlChar");
   }
 }
 
 void
 nsHtml5Tokenizer::errNcrZero()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNcrZero");
   }
 }
 
 void
 nsHtml5Tokenizer::errNoSpaceBetweenDoctypeSystemKeywordAndQuote()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNoSpaceBetweenDoctypeSystemKeywordAndQuote");
   }
 }
 
 void
 nsHtml5Tokenizer::errNoSpaceBetweenPublicAndSystemIds()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNoSpaceBetweenPublicAndSystemIds");
   }
 }
 
 void
 nsHtml5Tokenizer::errNoSpaceBetweenDoctypePublicKeywordAndQuote()
 {
-  if (NS_LIKELY(mViewSource)) {
+  if (MOZ_LIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentNode("errNoSpaceBetweenDoctypePublicKeywordAndQuote");
   }
 }
--- a/parser/html/nsHtml5TreeBuilder.cpp
+++ b/parser/html/nsHtml5TreeBuilder.cpp
@@ -59,16 +59,18 @@
 #include "nsHtml5HtmlAttributes.h"
 #include "nsHtml5StackNode.h"
 #include "nsHtml5UTF16Buffer.h"
 #include "nsHtml5StateSnapshot.h"
 #include "nsHtml5Portability.h"
 
 #include "nsHtml5TreeBuilder.h"
 
+#include "mozilla/Likely.h"
+
 PRUnichar nsHtml5TreeBuilder::REPLACEMENT_CHARACTER[] = { 0xfffd };
 static const char* const QUIRKY_PUBLIC_IDS_DATA[] = { "+//silmaril//dtd html pro v0r11 19970101//", "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", "-//as//dtd html 3.0 aswedit + extensions//", "-//ietf//dtd html 2.0 level 1//", "-//ietf//dtd html 2.0 level 2//", "-//ietf//dtd html 2.0 strict level 1//", "-//ietf//dtd html 2.0 strict level 2//", "-//ietf//dtd html 2.0 strict//", "-//ietf//dtd html 2.0//", "-//ietf//dtd html 2.1e//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.2 final//", "-//ietf//dtd html 3.2//", "-//ietf//dtd html 3//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 3//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict//", "-//ietf//dtd html//", "-//metrius//dtd metrius presentational//", "-//microsoft//dtd internet explorer 2.0 html strict//", "-//microsoft//dtd internet explorer 2.0 html//", "-//microsoft//dtd internet explorer 2.0 tables//", "-//microsoft//dtd internet explorer 3.0 html strict//", "-//microsoft//dtd internet explorer 3.0 html//", "-//microsoft//dtd internet explorer 3.0 tables//", "-//netscape comm. corp.//dtd html//", "-//netscape comm. corp.//dtd strict html//", "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", "-//spyglass//dtd html 2.0 extended//", "-//sq//dtd html 2.0 hotmetal + extensions//", "-//sun microsystems corp.//dtd hotjava html//", "-//sun microsystems corp.//dtd hotjava strict html//", "-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//", "-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//", "-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//", "-//w3c//dtd html 4.0 transitional//", "-//w3c//dtd html experimental 19960712//", "-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//", "-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//", "-//webtechs//dtd mozilla html//" };
 staticJArray<const char*,int32_t> nsHtml5TreeBuilder::QUIRKY_PUBLIC_IDS = { QUIRKY_PUBLIC_IDS_DATA, NS_ARRAY_LENGTH(QUIRKY_PUBLIC_IDS_DATA) };
 void 
 nsHtml5TreeBuilder::startTokenization(nsHtml5Tokenizer* self)
 {
   tokenizer = self;
   stack = jArray<nsHtml5StackNode*,int32_t>::newJArray(64);
@@ -741,17 +743,17 @@ nsHtml5TreeBuilder::startTag(nsHtml5Elem
             case NS_HTML5TREE_BUILDER_TABLE: {
               errTableSeenWhileTableOpen();
               eltPos = findLastInTableScope(name);
               if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
                 MOZ_ASSERT(fragment);
                 NS_HTML5_BREAK(starttagloop);
               }
               generateImpliedEndTags();
-              if (!!NS_UNLIKELY(mViewSource) && !isCurrent(nsHtml5Atoms::table)) {
+              if (!!MOZ_UNLIKELY(mViewSource) && !isCurrent(nsHtml5Atoms::table)) {
                 errNoCheckUnclosedElementsOnStack();
               }
               while (currentPtr >= eltPos) {
                 pop();
               }
               resetTheInsertionMode();
               NS_HTML5_CONTINUE(starttagloop);
             }
@@ -808,17 +810,17 @@ nsHtml5TreeBuilder::startTag(nsHtml5Elem
           case NS_HTML5TREE_BUILDER_TR:
           case NS_HTML5TREE_BUILDER_TD_OR_TH: {
             errStrayStartTag(name);
             eltPos = findLastInTableScope(nsHtml5Atoms::caption);
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
               NS_HTML5_BREAK(starttagloop);
             }
             generateImpliedEndTags();
-            if (!!NS_UNLIKELY(mViewSource) && currentPtr != eltPos) {
+            if (!!MOZ_UNLIKELY(mViewSource) && currentPtr != eltPos) {
               errNoCheckUnclosedElementsOnStack();
             }
             while (currentPtr >= eltPos) {
               pop();
             }
             clearTheListOfActiveFormattingElementsUpToTheLastMarker();
             mode = NS_HTML5TREE_BUILDER_IN_TABLE;
             continue;
@@ -979,17 +981,17 @@ nsHtml5TreeBuilder::startTag(nsHtml5Elem
             }
             case NS_HTML5TREE_BUILDER_LI:
             case NS_HTML5TREE_BUILDER_DD_OR_DT: {
               eltPos = currentPtr;
               for (; ; ) {
                 nsHtml5StackNode* node = stack[eltPos];
                 if (node->getGroup() == group) {
                   generateImpliedEndTagsExceptFor(node->name);
-                  if (!!NS_UNLIKELY(mViewSource) && eltPos != currentPtr) {
+                  if (!!MOZ_UNLIKELY(mViewSource) && eltPos != currentPtr) {
                     errUnclosedElementsImplied(eltPos, name);
                   }
                   while (currentPtr >= eltPos) {
                     pop();
                   }
                   break;
                 } else if (node->isScoping() || (node->isSpecial() && node->name != nsHtml5Atoms::p && node->name != nsHtml5Atoms::address && node->name != nsHtml5Atoms::div)) {
                   break;
@@ -1046,17 +1048,17 @@ nsHtml5TreeBuilder::startTag(nsHtml5Elem
               attributes = nullptr;
               NS_HTML5_BREAK(starttagloop);
             }
             case NS_HTML5TREE_BUILDER_BUTTON: {
               eltPos = findLastInScope(name);
               if (eltPos != NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
                 errFooSeenWhenFooOpen(name);
                 generateImpliedEndTags();
-                if (!!NS_UNLIKELY(mViewSource) && !isCurrent(name)) {
+                if (!!MOZ_UNLIKELY(mViewSource) && !isCurrent(name)) {
                   errUnclosedElementsImplied(eltPos, name);
                 }
                 while (currentPtr >= eltPos) {
                   pop();
                 }
                 NS_HTML5_CONTINUE(starttagloop);
               } else {
                 reconstructTheActiveFormattingElements();
@@ -2186,34 +2188,34 @@ nsHtml5TreeBuilder::endTag(nsHtml5Elemen
       case NS_HTML5TREE_BUILDER_IN_CAPTION: {
         switch(group) {
           case NS_HTML5TREE_BUILDER_CAPTION: {
             eltPos = findLastInTableScope(nsHtml5Atoms::caption);
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
               NS_HTML5_BREAK(endtagloop);
             }
             generateImpliedEndTags();
-            if (!!NS_UNLIKELY(mViewSource) && currentPtr != eltPos) {
+            if (!!MOZ_UNLIKELY(mViewSource) && currentPtr != eltPos) {
               errUnclosedElements(eltPos, name);
             }
             while (currentPtr >= eltPos) {
               pop();
             }
             clearTheListOfActiveFormattingElementsUpToTheLastMarker();
             mode = NS_HTML5TREE_BUILDER_IN_TABLE;
             NS_HTML5_BREAK(endtagloop);
           }
           case NS_HTML5TREE_BUILDER_TABLE: {
             errTableClosedWhileCaptionOpen();
             eltPos = findLastInTableScope(nsHtml5Atoms::caption);
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
               NS_HTML5_BREAK(endtagloop);
             }
             generateImpliedEndTags();
-            if (!!NS_UNLIKELY(mViewSource) && currentPtr != eltPos) {
+            if (!!MOZ_UNLIKELY(mViewSource) && currentPtr != eltPos) {
               errUnclosedElements(eltPos, name);
             }
             while (currentPtr >= eltPos) {
               pop();
             }
             clearTheListOfActiveFormattingElementsUpToTheLastMarker();
             mode = NS_HTML5TREE_BUILDER_IN_TABLE;
             continue;
@@ -2236,17 +2238,17 @@ nsHtml5TreeBuilder::endTag(nsHtml5Elemen
         switch(group) {
           case NS_HTML5TREE_BUILDER_TD_OR_TH: {
             eltPos = findLastInTableScope(name);
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
               errStrayEndTag(name);
               NS_HTML5_BREAK(endtagloop);
             }
             generateImpliedEndTags();
-            if (!!NS_UNLIKELY(mViewSource) && !isCurrent(name)) {
+            if (!!MOZ_UNLIKELY(mViewSource) && !isCurrent(name)) {
               errUnclosedElements(eltPos, name);
             }
             while (currentPtr >= eltPos) {
               pop();
             }
             clearTheListOfActiveFormattingElementsUpToTheLastMarker();
             mode = NS_HTML5TREE_BUILDER_IN_ROW;
             NS_HTML5_BREAK(endtagloop);
@@ -2278,17 +2280,17 @@ nsHtml5TreeBuilder::endTag(nsHtml5Elemen
         switch(group) {
           case NS_HTML5TREE_BUILDER_BODY: {
             if (!isSecondOnStackBody()) {
               MOZ_ASSERT(fragment);
               errStrayEndTag(name);
               NS_HTML5_BREAK(endtagloop);
             }
             MOZ_ASSERT(currentPtr >= 1);
-            if (NS_UNLIKELY(mViewSource)) {
+            if (MOZ_UNLIKELY(mViewSource)) {
               for (int32_t i = 2; i <= currentPtr; i++) {
                 switch(stack[i]->getGroup()) {
                   case NS_HTML5TREE_BUILDER_DD_OR_DT:
                   case NS_HTML5TREE_BUILDER_LI:
                   case NS_HTML5TREE_BUILDER_OPTGROUP:
                   case NS_HTML5TREE_BUILDER_OPTION:
                   case NS_HTML5TREE_BUILDER_P:
                   case NS_HTML5TREE_BUILDER_RT_OR_RP:
@@ -2308,17 +2310,17 @@ nsHtml5TreeBuilder::endTag(nsHtml5Elemen
             NS_HTML5_BREAK(endtagloop);
           }
           case NS_HTML5TREE_BUILDER_HTML: {
             if (!isSecondOnStackBody()) {
               MOZ_ASSERT(fragment);
               errStrayEndTag(name);
               NS_HTML5_BREAK(endtagloop);
             }
-            if (NS_UNLIKELY(mViewSource)) {
+            if (MOZ_UNLIKELY(mViewSource)) {
               for (int32_t i = 0; i <= currentPtr; i++) {
                 switch(stack[i]->getGroup()) {
                   case NS_HTML5TREE_BUILDER_DD_OR_DT:
                   case NS_HTML5TREE_BUILDER_LI:
                   case NS_HTML5TREE_BUILDER_P:
                   case NS_HTML5TREE_BUILDER_TBODY_OR_THEAD_OR_TFOOT:
                   case NS_HTML5TREE_BUILDER_TD_OR_TH:
                   case NS_HTML5TREE_BUILDER_BODY:
@@ -2342,17 +2344,17 @@ nsHtml5TreeBuilder::endTag(nsHtml5Elemen
           case NS_HTML5TREE_BUILDER_FIELDSET:
           case NS_HTML5TREE_BUILDER_BUTTON:
           case NS_HTML5TREE_BUILDER_ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY: {
             eltPos = findLastInScope(name);
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
               errStrayEndTag(name);
             } else {
               generateImpliedEndTags();
-              if (!!NS_UNLIKELY(mViewSource) && !isCurrent(name)) {
+              if (!!MOZ_UNLIKELY(mViewSource) && !isCurrent(name)) {
                 errUnclosedElements(eltPos, name);
               }
               while (currentPtr >= eltPos) {
                 pop();
               }
             }
             NS_HTML5_BREAK(endtagloop);
           }
@@ -2363,17 +2365,17 @@ nsHtml5TreeBuilder::endTag(nsHtml5Elemen
             }
             formPointer = nullptr;
             eltPos = findLastInScope(name);
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
               errStrayEndTag(name);
               NS_HTML5_BREAK(endtagloop);
             }
             generateImpliedEndTags();
-            if (!!NS_UNLIKELY(mViewSource) && !isCurrent(name)) {
+            if (!!MOZ_UNLIKELY(mViewSource) && !isCurrent(name)) {
               errUnclosedElements(eltPos, name);
             }
             removeFromStack(eltPos);
             NS_HTML5_BREAK(endtagloop);
           }
           case NS_HTML5TREE_BUILDER_P: {
             eltPos = findLastInButtonScope(nsHtml5Atoms::p);
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
@@ -2384,77 +2386,77 @@ nsHtml5TreeBuilder::endTag(nsHtml5Elemen
                   pop();
                 }
               }
               appendVoidElementToCurrentMayFoster(elementName, nsHtml5HtmlAttributes::EMPTY_ATTRIBUTES);
               NS_HTML5_BREAK(endtagloop);
             }
             generateImpliedEndTagsExceptFor(nsHtml5Atoms::p);
             MOZ_ASSERT(eltPos != NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK);
-            if (!!NS_UNLIKELY(mViewSource) && eltPos != currentPtr) {
+            if (!!MOZ_UNLIKELY(mViewSource) && eltPos != currentPtr) {
               errUnclosedElements(eltPos, name);
             }
             while (currentPtr >= eltPos) {
               pop();
             }
             NS_HTML5_BREAK(endtagloop);
           }
           case NS_HTML5TREE_BUILDER_LI: {
             eltPos = findLastInListScope(name);
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
               errNoElementToCloseButEndTagSeen(name);
             } else {
               generateImpliedEndTagsExceptFor(name);
-              if (!!NS_UNLIKELY(mViewSource) && eltPos != currentPtr) {
+              if (!!MOZ_UNLIKELY(mViewSource) && eltPos != currentPtr) {
                 errUnclosedElements(eltPos, name);
               }
               while (currentPtr >= eltPos) {
                 pop();
               }
             }
             NS_HTML5_BREAK(endtagloop);
           }
           case NS_HTML5TREE_BUILDER_DD_OR_DT: {
             eltPos = findLastInScope(name);
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
               errNoElementToCloseButEndTagSeen(name);
             } else {
               generateImpliedEndTagsExceptFor(name);
-              if (!!NS_UNLIKELY(mViewSource) && eltPos != currentPtr) {
+              if (!!MOZ_UNLIKELY(mViewSource) && eltPos != currentPtr) {
                 errUnclosedElements(eltPos, name);
               }
               while (currentPtr >= eltPos) {
                 pop();
               }
             }
             NS_HTML5_BREAK(endtagloop);
           }
           case NS_HTML5TREE_BUILDER_H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: {
             eltPos = findLastInScopeHn();
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
               errStrayEndTag(name);
             } else {
               generateImpliedEndTags();
-              if (!!NS_UNLIKELY(mViewSource) && !isCurrent(name)) {
+              if (!!MOZ_UNLIKELY(mViewSource) && !isCurrent(name)) {
                 errUnclosedElements(eltPos, name);
               }
               while (currentPtr >= eltPos) {
                 pop();
               }
             }
             NS_HTML5_BREAK(endtagloop);
           }
           case NS_HTML5TREE_BUILDER_OBJECT:
           case NS_HTML5TREE_BUILDER_MARQUEE_OR_APPLET: {
             eltPos = findLastInScope(name);
             if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
               errStrayEndTag(name);
             } else {
               generateImpliedEndTags();
-              if (!!NS_UNLIKELY(mViewSource) && !isCurrent(name)) {
+              if (!!MOZ_UNLIKELY(mViewSource) && !isCurrent(name)) {
                 errUnclosedElements(eltPos, name);
               }
               while (currentPtr >= eltPos) {
                 pop();
               }
               clearTheListOfActiveFormattingElementsUpToTheLastMarker();
             }
             NS_HTML5_BREAK(endtagloop);
@@ -2511,17 +2513,17 @@ nsHtml5TreeBuilder::endTag(nsHtml5Elemen
               pop();
               NS_HTML5_BREAK(endtagloop);
             }
             eltPos = currentPtr;
             for (; ; ) {
               nsHtml5StackNode* node = stack[eltPos];
               if (node->name == name) {
                 generateImpliedEndTags();
-                if (!!NS_UNLIKELY(mViewSource) && !isCurrent(name)) {
+                if (!!MOZ_UNLIKELY(mViewSource) && !isCurrent(name)) {
                   errUnclosedElements(eltPos, name);
                 }
                 while (currentPtr >= eltPos) {
                   pop();
                 }
                 NS_HTML5_BREAK(endtagloop);
               } else if (node->isSpecial()) {
                 errStrayEndTag(name);
@@ -2991,17 +2993,17 @@ nsHtml5TreeBuilder::isQuirky(nsIAtom* na
   }
   return false;
 }
 
 void 
 nsHtml5TreeBuilder::closeTheCell(int32_t eltPos)
 {
   generateImpliedEndTags();
-  if (!!NS_UNLIKELY(mViewSource) && eltPos != currentPtr) {
+  if (!!MOZ_UNLIKELY(mViewSource) && eltPos != currentPtr) {
     errUnclosedElementsCell(eltPos);
   }
   while (currentPtr >= eltPos) {
     pop();
   }
   clearTheListOfActiveFormattingElementsUpToTheLastMarker();
   mode = NS_HTML5TREE_BUILDER_IN_ROW;
   return;
@@ -3098,17 +3100,17 @@ nsHtml5TreeBuilder::resetTheInsertionMod
 void 
 nsHtml5TreeBuilder::implicitlyCloseP()
 {
   int32_t eltPos = findLastInButtonScope(nsHtml5Atoms::p);
   if (eltPos == NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK) {
     return;
   }
   generateImpliedEndTagsExceptFor(nsHtml5Atoms::p);
-  if (!!NS_UNLIKELY(mViewSource) && eltPos != currentPtr) {
+  if (!!MOZ_UNLIKELY(mViewSource) && eltPos != currentPtr) {
     errUnclosedElementsImplied(eltPos, nsHtml5Atoms::p);
   }
   while (currentPtr >= eltPos) {
     pop();
   }
 }
 
 bool 
--- a/parser/html/nsHtml5TreeBuilderCppSupplement.h
+++ b/parser/html/nsHtml5TreeBuilderCppSupplement.h
@@ -6,16 +6,17 @@
 
 #include "nsError.h"
 #include "nsIPresShell.h"
 #include "nsEvent.h"
 #include "nsGUIEvent.h"
 #include "nsEventDispatcher.h"
 #include "nsNodeUtils.h"
 #include "nsIFrame.h"
+#include "mozilla/Likely.h"
 
 class nsPresContext;
 
 nsHtml5TreeBuilder::nsHtml5TreeBuilder(nsAHtml5TreeOpSink* aOpSink,
                                        nsHtml5TreeOpStage* aStage)
   : scriptingEnabled(false)
   , fragment(false)
   , contextNode(nullptr)
@@ -746,389 +747,389 @@ void
 nsHtml5TreeBuilder::EnableViewSource(nsHtml5Highlighter* aHighlighter)
 {
   mViewSource = aHighlighter;
 }
 
 void
 nsHtml5TreeBuilder::errStrayStartTag(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errStrayStartTag2", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errStrayEndTag(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errStrayEndTag", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errUnclosedElements(int32_t aIndex, nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errUnclosedElements", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errUnclosedElementsImplied(int32_t aIndex, nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errUnclosedElementsImplied",
         aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errUnclosedElementsCell(int32_t aIndex)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errUnclosedElementsCell");
   }
 }
 
 void
 nsHtml5TreeBuilder::errStrayDoctype()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errStrayDoctype");
   }
 }
 
 void
 nsHtml5TreeBuilder::errAlmostStandardsDoctype()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errAlmostStandardsDoctype");
   }
 }
 
 void
 nsHtml5TreeBuilder::errQuirkyDoctype()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errQuirkyDoctype");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNonSpaceInTrailer()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errNonSpaceInTrailer");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNonSpaceAfterFrameset()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errNonSpaceAfterFrameset");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNonSpaceInFrameset()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errNonSpaceInFrameset");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNonSpaceAfterBody()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errNonSpaceAfterBody");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNonSpaceInColgroupInFragment()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errNonSpaceInColgroupInFragment");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNonSpaceInNoscriptInHead()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errNonSpaceInNoscriptInHead");
   }
 }
 
 void
 nsHtml5TreeBuilder::errFooBetweenHeadAndBody(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errFooBetweenHeadAndBody", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errStartTagWithoutDoctype()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errStartTagWithoutDoctype");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNoSelectInTableScope()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errNoSelectInTableScope");
   }
 }
 
 void
 nsHtml5TreeBuilder::errStartSelectWhereEndSelectExpected()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun(
         "errStartSelectWhereEndSelectExpected");
   }
 }
 
 void
 nsHtml5TreeBuilder::errStartTagWithSelectOpen(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errStartTagWithSelectOpen", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errBadStartTagInHead(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errBadStartTagInHead2", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errImage()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errImage");
   }
 }
 
 void
 nsHtml5TreeBuilder::errIsindex()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errIsindex");
   }
 }
 
 void
 nsHtml5TreeBuilder::errFooSeenWhenFooOpen(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errFooSeenWhenFooOpen", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errHeadingWhenHeadingOpen()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errHeadingWhenHeadingOpen");
   }
 }
 
 void
 nsHtml5TreeBuilder::errFramesetStart()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errFramesetStart");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNoCellToClose()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errNoCellToClose");
   }
 }
 
 void
 nsHtml5TreeBuilder::errStartTagInTable(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errStartTagInTable", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errFormWhenFormOpen()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errFormWhenFormOpen");
   }
 }
 
 void
 nsHtml5TreeBuilder::errTableSeenWhileTableOpen()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errTableSeenWhileTableOpen");
   }
 }
 
 void
 nsHtml5TreeBuilder::errStartTagInTableBody(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errStartTagInTableBody", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errEndTagSeenWithoutDoctype()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEndTagSeenWithoutDoctype");
   }
 }
 
 void
 nsHtml5TreeBuilder::errEndTagAfterBody()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEndTagAfterBody");
   }
 }
 
 void
 nsHtml5TreeBuilder::errEndTagSeenWithSelectOpen(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEndTagSeenWithSelectOpen",
         aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errGarbageInColgroup()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errGarbageInColgroup");
   }
 }
 
 void
 nsHtml5TreeBuilder::errEndTagBr()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEndTagBr");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNoElementToCloseButEndTagSeen(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun(
         "errNoElementToCloseButEndTagSeen", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errHtmlStartTagInForeignContext(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errHtmlStartTagInForeignContext",
         aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errTableClosedWhileCaptionOpen()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errTableClosedWhileCaptionOpen");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNoTableRowToClose()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errNoTableRowToClose");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNonSpaceInTable()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errNonSpaceInTable");
   }
 }
 
 void
 nsHtml5TreeBuilder::errUnclosedChildrenInRuby()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errUnclosedChildrenInRuby");
   }
 }
 
 void
 nsHtml5TreeBuilder::errStartTagSeenWithoutRuby(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errStartTagSeenWithoutRuby",
         aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errSelfClosing()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentSlash("errSelfClosing");
   }
 }
 
 void
 nsHtml5TreeBuilder::errNoCheckUnclosedElementsOnStack()
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun(
         "errNoCheckUnclosedElementsOnStack");
   }
 }
 
 void
 nsHtml5TreeBuilder::errEndTagDidNotMatchCurrentOpenElement(nsIAtom* aName,
                                                            nsIAtom* aOther)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun(
         "errEndTagDidNotMatchCurrentOpenElement", aName, aOther);
   }
 }
 
 void
 nsHtml5TreeBuilder::errEndTagViolatesNestingRules(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEndTagViolatesNestingRules", aName);
   }
 }
 
 void
 nsHtml5TreeBuilder::errEndWithUnclosedElements(nsIAtom* aName)
 {
-  if (NS_UNLIKELY(mViewSource)) {
+  if (MOZ_UNLIKELY(mViewSource)) {
     mViewSource->AddErrorToCurrentRun("errEndWithUnclosedElements", aName);
   }
 }
--- a/parser/html/nsHtml5TreeOpExecutor.cpp
+++ b/parser/html/nsHtml5TreeOpExecutor.cpp
@@ -26,16 +26,17 @@
 #include "nsHtml5StreamParser.h"
 #include "mozilla/css/Loader.h"
 #include "mozilla/Util.h" // DebugOnly
 #include "sampler.h"
 #include "nsIScriptError.h"
 #include "nsIScriptContext.h"
 #include "mozilla/Preferences.h"
 #include "nsIHTMLDocument.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla;
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsHtml5TreeOpExecutor)
 
 NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(nsHtml5TreeOpExecutor)
   NS_INTERFACE_TABLE_INHERITED1(nsHtml5TreeOpExecutor, 
                                 nsIContentSink)
@@ -349,17 +350,17 @@ nsHtml5TreeOpExecutor::ContinueInterrupt
 
 void
 nsHtml5TreeOpExecutor::UpdateStyleSheet(nsIContent* aElement)
 {
   // Break out of the doc update created by Flush() to zap a runnable 
   // waiting to call UpdateStyleSheet without the right observer
   EndDocUpdate();
 
-  if (NS_UNLIKELY(!mParser)) {
+  if (MOZ_UNLIKELY(!mParser)) {
     // EndDocUpdate ran stuff that called nsIParser::Terminate()
     return;
   }
 
   nsCOMPtr<nsIStyleSheetLinkingElement> ssle(do_QueryInterface(aElement));
   NS_ASSERTION(ssle, "Node didn't QI to style.");
 
   ssle->SetEnableUpdates(true);
@@ -407,17 +408,17 @@ nsHtml5TreeOpExecutor::FlushSpeculativeL
 {
   nsTArray<nsHtml5SpeculativeLoad> speculativeLoadQueue;
   mStage.MoveSpeculativeLoadsTo(speculativeLoadQueue);
   const nsHtml5SpeculativeLoad* start = speculativeLoadQueue.Elements();
   const nsHtml5SpeculativeLoad* end = start + speculativeLoadQueue.Length();
   for (nsHtml5SpeculativeLoad* iter = const_cast<nsHtml5SpeculativeLoad*>(start);
        iter < end;
        ++iter) {
-    if (NS_UNLIKELY(!mParser)) {
+    if (MOZ_UNLIKELY(!mParser)) {
       // An extension terminated the parser from a HTTP observer.
       return;
     }
     iter->Perform(this);
   }
 }
 
 class nsHtml5FlushLoopGuard
@@ -507,27 +508,27 @@ nsHtml5TreeOpExecutor::RunFlushLoop()
       // Make sure speculative loads never start after the corresponding
       // normal loads for the same URLs.
       const nsHtml5SpeculativeLoad* start = speculativeLoadQueue.Elements();
       const nsHtml5SpeculativeLoad* end = start + speculativeLoadQueue.Length();
       for (nsHtml5SpeculativeLoad* iter = (nsHtml5SpeculativeLoad*)start;
            iter < end;
            ++iter) {
         iter->Perform(this);
-        if (NS_UNLIKELY(!mParser)) {
+        if (MOZ_UNLIKELY(!mParser)) {
           // An extension terminated the parser from a HTTP observer.
           mOpQueue.Clear(); // clear in order to be able to assert in destructor
           return;
         }
       }
     } else {
       FlushSpeculativeLoads(); // Make sure speculative loads never start after
                                // the corresponding normal loads for the same
                                // URLs.
-      if (NS_UNLIKELY(!mParser)) {
+      if (MOZ_UNLIKELY(!mParser)) {
         // An extension terminated the parser from a HTTP observer.
         mOpQueue.Clear(); // clear in order to be able to assert in destructor
         return;
       }
       // Not sure if this grip is still needed, but previously, the code
       // gripped before calling ParseUntilBlocked();
       nsRefPtr<nsHtml5StreamParser> streamKungFuDeathGrip = 
         GetParser()->GetStreamParser();
@@ -550,29 +551,29 @@ nsHtml5TreeOpExecutor::RunFlushLoop()
 
     uint32_t numberOfOpsToFlush = mOpQueue.Length();
 
     mElementsSeenInThisAppendBatch.SetCapacity(numberOfOpsToFlush * 2);
 
     const nsHtml5TreeOperation* first = mOpQueue.Elements();
     const nsHtml5TreeOperation* last = first + numberOfOpsToFlush - 1;
     for (nsHtml5TreeOperation* iter = const_cast<nsHtml5TreeOperation*>(first);;) {
-      if (NS_UNLIKELY(!mParser)) {
+      if (MOZ_UNLIKELY(!mParser)) {
         // The previous tree op caused a call to nsIParser::Terminate().
         break;
       }
       NS_ASSERTION(mFlushState == eInDocUpdate, 
         "Tried to perform tree op outside update batch.");
       iter->Perform(this, &scriptElement);
 
       // Be sure not to check the deadline if the last op was just performed.
-      if (NS_UNLIKELY(iter == last)) {
+      if (MOZ_UNLIKELY(iter == last)) {
         break;
-      } else if (NS_UNLIKELY(nsContentSink::DidProcessATokenImpl() == 
-                             NS_ERROR_HTMLPARSER_INTERRUPTED)) {
+      } else if (MOZ_UNLIKELY(nsContentSink::DidProcessATokenImpl() == 
+                 NS_ERROR_HTMLPARSER_INTERRUPTED)) {
         mOpQueue.RemoveElementsAt(0, (iter - first) + 1);
         
         EndDocUpdate();
 
         mFlushState = eNotFlushing;
 
         #ifdef DEBUG_NS_HTML5_TREE_OP_EXECUTOR_FLUSH
           printf("REFLUSH SCHEDULED (executing ops): %d\n", 
@@ -585,17 +586,17 @@ nsHtml5TreeOpExecutor::RunFlushLoop()
     }
     
     mOpQueue.Clear();
     
     EndDocUpdate();
 
     mFlushState = eNotFlushing;
 
-    if (NS_UNLIKELY(!mParser)) {
+    if (MOZ_UNLIKELY(!mParser)) {
       // The parse ended already.
       return;
     }
 
     if (scriptElement) {
       // must be tail call when mFlushState is eNotFlushing
       RunScript(scriptElement);
       
@@ -615,17 +616,17 @@ nsHtml5TreeOpExecutor::RunFlushLoop()
 }
 
 void
 nsHtml5TreeOpExecutor::FlushDocumentWrite()
 {
   FlushSpeculativeLoads(); // Make sure speculative loads never start after the
                 // corresponding normal loads for the same URLs.
 
-  if (NS_UNLIKELY(!mParser)) {
+  if (MOZ_UNLIKELY(!mParser)) {
     // The parse has ended.
     mOpQueue.Clear(); // clear in order to be able to assert in destructor
     return;
   }
   
   if (mFlushState != eNotFlushing) {
     // XXX Can this happen? In case it can, let's avoid crashing.
     return;
@@ -652,32 +653,32 @@ nsHtml5TreeOpExecutor::FlushDocumentWrit
 
   mElementsSeenInThisAppendBatch.SetCapacity(numberOfOpsToFlush * 2);
 
   const nsHtml5TreeOperation* start = mOpQueue.Elements();
   const nsHtml5TreeOperation* end = start + numberOfOpsToFlush;
   for (nsHtml5TreeOperation* iter = const_cast<nsHtml5TreeOperation*>(start);
        iter < end;
        ++iter) {
-    if (NS_UNLIKELY(!mParser)) {
+    if (MOZ_UNLIKELY(!mParser)) {
       // The previous tree op caused a call to nsIParser::Terminate().
       break;
     }
     NS_ASSERTION(mFlushState == eInDocUpdate, 
       "Tried to perform tree op outside update batch.");
     iter->Perform(this, &scriptElement);
   }
 
   mOpQueue.Clear();
   
   EndDocUpdate();
 
   mFlushState = eNotFlushing;
 
-  if (NS_UNLIKELY(!mParser)) {
+  if (MOZ_UNLIKELY(!mParser)) {
     // Ending the doc update caused a call to nsIParser::Terminate().
     return;
   }
 
   if (scriptElement) {
     // must be tail call when mFlushState is eNotFlushing
     RunScript(scriptElement);
   }
@@ -731,17 +732,17 @@ nsHtml5TreeOpExecutor::SetDocumentMode(n
 void
 nsHtml5TreeOpExecutor::StartLayout() {
   if (mLayoutStarted || !mDocument) {
     return;
   }
 
   EndDocUpdate();
 
-  if (NS_UNLIKELY(!mParser)) {
+  if (MOZ_UNLIKELY(!mParser)) {
     // got terminate
     return;
   }
 
   nsContentSink::StartLayout(false);
 
   BeginDocUpdate();
 }
@@ -828,17 +829,17 @@ nsHtml5TreeOpExecutor::Start()
 
 void
 nsHtml5TreeOpExecutor::NeedsCharsetSwitchTo(const char* aEncoding,
                                             int32_t aSource,
                                             uint32_t aLineNumber)
 {
   EndDocUpdate();
 
-  if (NS_UNLIKELY(!mParser)) {
+  if (MOZ_UNLIKELY(!mParser)) {
     // got terminate
     return;
   }
   
   nsCOMPtr<nsIWebShellServices> wss = do_QueryInterface(mDocShell);
   if (!wss) {
     return;
   }
--- a/parser/html/nsHtml5TreeOperation.cpp
+++ b/parser/html/nsHtml5TreeOperation.cpp
@@ -30,42 +30,43 @@
 #include "nsIServiceManager.h"
 #include "nsEscape.h"
 #include "mozilla/dom/Element.h"
 #include "nsHtml5SVGLoadDispatcher.h"
 #include "nsIURI.h"
 #include "nsIProtocolHandler.h"
 #include "nsNetUtil.h"
 #include "nsIHTMLDocument.h"
+#include "mozilla/Likely.h"
 
 namespace dom = mozilla::dom;
 
 static NS_DEFINE_CID(kFormProcessorCID, NS_FORMPROCESSOR_CID);
 
 /**
  * Helper class that opens a notification batch if the current doc
  * is different from the executor doc.
  */
 class NS_STACK_CLASS nsHtml5OtherDocUpdate {
   public:
     nsHtml5OtherDocUpdate(nsIDocument* aCurrentDoc, nsIDocument* aExecutorDoc)
     {
       NS_PRECONDITION(aCurrentDoc, "Node has no doc?");
       NS_PRECONDITION(aExecutorDoc, "Executor has no doc?");
-      if (NS_LIKELY(aCurrentDoc == aExecutorDoc)) {
+      if (MOZ_LIKELY(aCurrentDoc == aExecutorDoc)) {
         mDocument = nullptr;
       } else {
         mDocument = aCurrentDoc;
         aCurrentDoc->BeginUpdate(UPDATE_CONTENT_MODEL);        
       }
     }
 
     ~nsHtml5OtherDocUpdate()
     {
-      if (NS_UNLIKELY(mDocument)) {
+      if (MOZ_UNLIKELY(mDocument)) {
         mDocument->EndUpdate(UPDATE_CONTENT_MODEL);
       }
     }
   private:
     nsIDocument* mDocument;
 };
 
 nsHtml5TreeOperation::nsHtml5TreeOperation()
@@ -174,17 +175,17 @@ nsHtml5TreeOperation::Append(nsIContent*
                              nsHtml5TreeOpExecutor* aBuilder)
 {
   nsresult rv = NS_OK;
   nsIDocument* executorDoc = aBuilder->GetDocument();
   NS_ASSERTION(executorDoc, "Null doc on executor");
   nsIDocument* parentDoc = aParent->OwnerDoc();
   NS_ASSERTION(parentDoc, "Null owner doc on old node.");
 
-  if (NS_LIKELY(executorDoc == parentDoc)) {
+  if (MOZ_LIKELY(executorDoc == parentDoc)) {
     // the usual case. the parent is in the parser's doc
     rv = aParent->AppendChildTo(aNode, false);
     if (NS_SUCCEEDED(rv)) {
       aBuilder->PostPendingAppendNotification(aParent, aNode);
     }
     return rv;
   }
 
@@ -325,17 +326,17 @@ nsHtml5TreeOperation::Perform(nsHtml5Tre
     case eTreeOpCreateElementNetwork:
     case eTreeOpCreateElementNotNetwork: {
       nsIContent** target = mOne.node;
       int32_t ns = mFour.integer;
       nsCOMPtr<nsIAtom> name = Reget(mTwo.atom);
       nsHtml5HtmlAttributes* attributes = mThree.attributes;
       
       bool isKeygen = (name == nsHtml5Atoms::keygen && ns == kNameSpaceID_XHTML);
-      if (NS_UNLIKELY(isKeygen)) {
+      if (MOZ_UNLIKELY(isKeygen)) {
         name = nsHtml5Atoms::select;
       }
       
       nsCOMPtr<nsIContent> newContent;
       nsCOMPtr<nsINodeInfo> nodeInfo = aBuilder->GetNodeInfoManager()->
         GetNodeInfo(name, nullptr, ns, nsIDOMNode::ELEMENT_NODE);
       NS_ASSERTION(nodeInfo, "Got null nodeinfo.");
       NS_NewElement(getter_AddRefs(newContent),
@@ -344,23 +345,23 @@ nsHtml5TreeOperation::Perform(nsHtml5Tre
                      dom::FROM_PARSER_NETWORK
                      : (aBuilder->BelongsToStringParser() ?
                         dom::FROM_PARSER_FRAGMENT :
                         dom::FROM_PARSER_DOCUMENT_WRITE)));
       NS_ASSERTION(newContent, "Element creation created null pointer.");
 
       aBuilder->HoldElement(*target = newContent);      
 
-      if (NS_UNLIKELY(name == nsHtml5Atoms::style || name == nsHtml5Atoms::link)) {
+      if (MOZ_UNLIKELY(name == nsHtml5Atoms::style || name == nsHtml5Atoms::link)) {
         nsCOMPtr<nsIStyleSheetLinkingElement> ssle(do_QueryInterface(newContent));
         if (ssle) {
           ssle->InitStyleLinkElement(false);
           ssle->SetEnableUpdates(false);
         }
-      } else if (NS_UNLIKELY(isKeygen)) {
+      } else if (MOZ_UNLIKELY(isKeygen)) {
         // Adapted from CNavDTD
         nsCOMPtr<nsIFormProcessor> theFormProcessor =
           do_GetService(kFormProcessorCID, &rv);
         NS_ENSURE_SUCCESS(rv, rv);
         
         nsTArray<nsString> theContent;
         nsAutoString theAttribute;
          
--- a/parser/htmlparser/src/nsHTMLTokenizer.cpp
+++ b/parser/htmlparser/src/nsHTMLTokenizer.cpp
@@ -16,16 +16,17 @@
 
 #include "nsIAtom.h"
 #include "nsHTMLTokenizer.h"
 #include "nsScanner.h"
 #include "nsElementTable.h"
 #include "nsReadableUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsParserConstants.h"
+#include "mozilla/Likely.h"
 
 /************************************************************************
   And now for the main class -- nsHTMLTokenizer...
  ************************************************************************/
 
 /**
  * Satisfy the nsISupports interface.
  */
@@ -626,17 +627,17 @@ nsHTMLTokenizer::ConsumeAttributes(PRUni
 
   nsTokenAllocator* theAllocator = this->GetTokenAllocator();
 
   while (!done && result == NS_OK) {
     CAttributeToken* theToken =
       static_cast<CAttributeToken*>
                  (theAllocator->CreateTokenOfType(eToken_attribute,
                                                      eHTMLTag_unknown));
-    if (NS_LIKELY(theToken != nullptr)) {
+    if (MOZ_LIKELY(theToken != nullptr)) {
       // Tell the new token to finish consuming text...
       result = theToken->Consume(aChar, aScanner, mFlags);
 
       if (NS_SUCCEEDED(result)) {
         ++theAttrCount;
         AddToken((CToken*&)theToken, result, &mTokenDeque, theAllocator);
       } else {
         IF_FREE(theToken, mTokenAllocator);
@@ -832,17 +833,17 @@ nsHTMLTokenizer::ConsumeStartTag(PRUnich
               endToken->SetInError(false);
             }
           } else if (result == kFakeEndTag &&
                     !(mFlags & NS_IPARSER_FLAG_VIEW_SOURCE)) {
             result = NS_OK;
             endToken = theAllocator->CreateTokenOfType(eToken_end, theTag,
                                                        endTagName);
             AddToken(endToken, result, &mTokenDeque, theAllocator);
-            if (NS_LIKELY(endToken != nullptr)) {
+            if (MOZ_LIKELY(endToken != nullptr)) {
               endToken->SetInError(true);
             }
             else {
               result = NS_ERROR_OUT_OF_MEMORY;
             }
           } else if (result == kFakeEndTag) {
             // If we are here, we are both faking having seen the end tag
             // and are in view-source.
--- a/security/manager/ssl/src/nsNTLMAuthModule.cpp
+++ b/security/manager/ssl/src/nsNTLMAuthModule.cpp
@@ -14,16 +14,17 @@
 #include "nsNTLMAuthModule.h"
 #include "nsNativeCharsetUtils.h"
 #include "nsReadableUtils.h"
 #include "nsString.h"
 #include "prsystem.h"
 #include "nss.h"
 #include "pk11func.h"
 #include "md4.h"
+#include "mozilla/Likely.h"
 
 #ifdef PR_LOGGING
 PRLogModuleInfo *gNTLMLog = PR_NewLogModule("NTLM");
 
 #define LOG(x) PR_LOG(gNTLMLog, PR_LOG_DEBUG, x)
 #define LOG_ENABLED() PR_LOG_TEST(gNTLMLog, PR_LOG_DEBUG)
 #else
 #define LOG(x)
@@ -515,17 +516,17 @@ ParseType2Msg(const void *inBuf, uint32_
   // ... read target length.
   uint32_t targetLen = ReadUint16(cursor);
   // ... skip next 16-bit "allocated space" value.
   ReadUint16(cursor);
   // ... read offset from inBuf.
   uint32_t offset = ReadUint32(cursor);
   // Check the offset / length combo is in range of the input buffer, including
   // integer overflow checking.
-  if (NS_LIKELY(offset < offset + targetLen && offset + targetLen <= inLen)) {
+  if (MOZ_LIKELY(offset < offset + targetLen && offset + targetLen <= inLen)) {
     msg->targetLen = targetLen;
     msg->target = ((const uint8_t *) inBuf) + offset;
   }
   else
   {
     // Do not error out, for (conservative) backward compatibility.
     msg->targetLen = 0;
     msg->target = nullptr;
--- a/toolkit/components/places/SQLFunctions.cpp
+++ b/toolkit/components/places/SQLFunctions.cpp
@@ -14,16 +14,17 @@
 #include "nsUTF8Utils.h"
 #include "nsINavHistoryService.h"
 #include "nsPrintfCString.h"
 #include "nsNavHistory.h"
 #if defined(XP_OS2)
 #include "nsIRandomGenerator.h"
 #endif
 #include "mozilla/Telemetry.h"
+#include "mozilla/Likely.h"
 
 using namespace mozilla::storage;
 
 ////////////////////////////////////////////////////////////////////////////////
 //// Anonymous Helpers
 
 namespace {
 
@@ -146,17 +147,17 @@ namespace {
             // sourceCur doesn't match tokenCur (or there's an error), so break
             // out of this loop.
             break;
           }
         }
       }
 
       // If something went wrong above, get out of here!
-      if (NS_UNLIKELY(error)) {
+      if (MOZ_UNLIKELY(error)) {
         return false;
       }
 
       // We didn't match the token.  If we're searching for matches on word
       // boundaries, skip to the next word boundary.  Otherwise, advance
       // forward one character, using the sourceNext pointer we saved earlier.
 
       if (aBehavior == eFindOnBoundary) {
--- a/toolkit/components/telemetry/Telemetry.cpp
+++ b/toolkit/components/telemetry/Telemetry.cpp
@@ -24,16 +24,17 @@
 #include "nsBaseHashtable.h"
 #include "nsXULAppAPI.h"
 #include "nsThreadUtils.h"
 #include "mozilla/ProcessedStack.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/FileUtils.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 
 namespace {
 
 using namespace base;
 using namespace mozilla;
 
 template<class EntryType>
 class AutoHashtable : public nsTHashtable<EntryType>
@@ -662,17 +663,17 @@ TelemetryImpl::GetHistogramEnumId(const 
   }
 
   // Cache names
   // Note the histogram names are statically allocated
   TelemetryImpl::HistogramMapType *map = &sTelemetry->mHistogramMap;
   if (!map->Count()) {
     for (uint32_t i = 0; i < Telemetry::HistogramCount; i++) {
       CharPtrEntryType *entry = map->PutEntry(gHistograms[i].id());
-      if (NS_UNLIKELY(!entry)) {
+      if (MOZ_UNLIKELY(!entry)) {
         map->Clear();
         return NS_ERROR_OUT_OF_MEMORY;
       }
       entry->mData = (Telemetry::ID) i;
     }
   }
 
   CharPtrEntryType *entry = map->GetEntry(name);
@@ -807,31 +808,31 @@ TelemetryImpl::RegisterAddonHistogram(co
                                       const nsACString &name,
                                       uint32_t min, uint32_t max,
                                       uint32_t bucketCount,
                                       uint32_t histogramType)
 {
   AddonEntryType *addonEntry = mAddonMap.GetEntry(id);
   if (!addonEntry) {
     addonEntry = mAddonMap.PutEntry(id);
-    if (NS_UNLIKELY(!addonEntry)) {
+    if (MOZ_UNLIKELY(!addonEntry)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
     addonEntry->mData = new AddonHistogramMapType();
   }
 
   AddonHistogramMapType *histogramMap = addonEntry->mData;
   AddonHistogramEntryType *histogramEntry = histogramMap->GetEntry(name);
   // Can't re-register the same histogram.
   if (histogramEntry) {
     return NS_ERROR_FAILURE;
   }
 
   histogramEntry = histogramMap->PutEntry(name);
-  if (NS_UNLIKELY(!histogramEntry)) {
+  if (MOZ_UNLIKELY(!histogramEntry)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   AddonHistogramInfo &info = histogramEntry->mData;
   info.min = min;
   info.max = max;
   info.bucketCount = bucketCount;
   info.histogramType = histogramType;
@@ -1314,17 +1315,17 @@ TelemetryImpl::StoreSlowSQL(const nsACSt
   else
     slowSQLMap = &(sTelemetry->mPrivateSQL);
 
   MutexAutoLock hashMutex(sTelemetry->mHashMutex);
 
   SlowSQLEntryType *entry = slowSQLMap->GetEntry(sql);
   if (!entry) {
     entry = slowSQLMap->PutEntry(sql);
-    if (NS_UNLIKELY(!entry))
+    if (MOZ_UNLIKELY(!entry))
       return;
     entry->mData.mainThread.hitCount = 0;
     entry->mData.mainThread.totalTime = 0;
     entry->mData.otherThreads.hitCount = 0;
     entry->mData.otherThreads.totalTime = 0;
   }
 
   if (NS_IsMainThread()) {
--- a/toolkit/xre/nsAppRunner.cpp
+++ b/toolkit/xre/nsAppRunner.cpp
@@ -20,16 +20,17 @@
 #endif
 #endif // MOZ_WIDGET_QT
 
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/ContentChild.h"
 
 #include "mozilla/Util.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 
 #include "nsAppRunner.h"
 #include "mozilla/AppData.h"
 #include "nsUpdateDriver.h"
 #include "ProfileReset.h"
 
 #ifdef MOZ_INSTRUMENT_EVENT_LOOP
 #include "EventTracer.h"
@@ -1056,19 +1057,19 @@ bool gLogConsoleErrors
 #ifdef DEBUG
          = true;
 #else
          = false;
 #endif
 
 #define NS_ENSURE_TRUE_LOG(x, ret)               \
   PR_BEGIN_MACRO                                 \
-  if (NS_UNLIKELY(!(x))) {                       \
+  if (MOZ_UNLIKELY(!(x))) {                      \
     NS_WARNING("NS_ENSURE_TRUE(" #x ") failed"); \
-    gLogConsoleErrors = true;                 \
+    gLogConsoleErrors = true;                    \
     return ret;                                  \
   }                                              \
   PR_END_MACRO
 
 #define NS_ENSURE_SUCCESS_LOG(res, ret)          \
   NS_ENSURE_TRUE_LOG(NS_SUCCEEDED(res), ret)
 
 /**
--- a/view/src/nsView.cpp
+++ b/view/src/nsView.cpp
@@ -8,16 +8,17 @@
 #include "nsWidgetsCID.h"
 #include "nsViewManager.h"
 #include "nsIFrame.h"
 #include "nsGUIEvent.h"
 #include "nsIComponentManager.h"
 #include "nsGfxCIID.h"
 #include "nsIInterfaceRequestor.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 #include "nsXULPopupManager.h"
 #include "nsIWidgetListener.h"
 
 nsView::nsView(nsViewManager* aViewManager, nsViewVisibility aVisibility)
 {
   MOZ_COUNT_CTOR(nsView);
 
   mVis = aVisibility;
@@ -708,17 +709,17 @@ void nsView::SetZIndex(bool aAuto, int32
   if (HasWidget() || !oldIsAuto || !aAuto) {
     UpdateNativeWidgetZIndexes(this, FindNonAutoZIndex(this));
   }
 }
 
 void nsView::AssertNoWindow()
 {
   // XXX: it would be nice to make this a strong assert
-  if (NS_UNLIKELY(mWindow)) {
+  if (MOZ_UNLIKELY(mWindow)) {
     NS_ERROR("We already have a window for this view? BAD");
     mWindow->SetWidgetListener(nullptr);
     mWindow->Destroy();
     NS_RELEASE(mWindow);
   }
 }
 
 //
--- a/widget/android/AndroidBridge.h
+++ b/widget/android/AndroidBridge.h
@@ -22,16 +22,18 @@
 
 #include "nsIMutableArray.h"
 #include "nsIMIMEInfo.h"
 #include "nsColor.h"
 #include "gfxRect.h"
 
 #include "nsIAndroidBridge.h"
 
+#include "mozilla/Likely.h"
+
 // Some debug #defines
 // #define DEBUG_ANDROID_EVENTS
 // #define DEBUG_ANDROID_WIDGET
 
 class nsWindow;
 class nsIDOMMozSmsMessage;
 
 /* See the comment in AndroidBridge about this function before using it */
@@ -110,23 +112,23 @@ public:
 
     static void ConstructBridge(JNIEnv *jEnv, jclass jGeckoAppShellClass);
 
     static AndroidBridge *Bridge() {
         return sBridge;
     }
 
     static JavaVM *GetVM() {
-        if (NS_LIKELY(sBridge))
+        if (MOZ_LIKELY(sBridge))
             return sBridge->mJavaVM;
         return nullptr;
     }
 
     static JNIEnv *GetJNIEnv() {
-        if (NS_LIKELY(sBridge)) {
+        if (MOZ_LIKELY(sBridge)) {
             if ((void*)pthread_self() != sBridge->mThread) {
                 __android_log_print(ANDROID_LOG_INFO, "AndroidBridge",
                                     "###!!!!!!! Something's grabbing the JNIEnv from the wrong thread! (thr %p should be %p)",
                                     (void*)pthread_self(), (void*)sBridge->mThread);
                 return nullptr;
             }
             return sBridge->mJNIEnv;
 
--- a/widget/gtk2/nsGtkIMModule.cpp
+++ b/widget/gtk2/nsGtkIMModule.cpp
@@ -12,16 +12,17 @@
 #ifdef MOZ_LOGGING
 #define FORCE_PR_LOG /* Allow logging in the release build */
 #endif // MOZ_LOGGING
 #include "prlog.h"
 
 #include "nsGtkIMModule.h"
 #include "nsWindow.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/Likely.h"
 
 #ifdef MOZ_PLATFORM_MAEMO
 #include "nsServiceManagerUtils.h"
 #include "nsIObserverService.h"
 #include "mozilla/Services.h"
 #endif
 
 using namespace mozilla;
@@ -302,31 +303,31 @@ nsGtkIMModule::PrepareToDestroyContext(G
         // Mute unused variable warning:
         gtk_iiim_context_class = gtk_iiim_context_class;
     }
 }
 
 void
 nsGtkIMModule::OnFocusWindow(nsWindow* aWindow)
 {
-    if (NS_UNLIKELY(IsDestroyed())) {
+    if (MOZ_UNLIKELY(IsDestroyed())) {
         return;
     }
 
     PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
         ("GtkIMModule(%p): OnFocusWindow, aWindow=%p, mLastFocusedWindow=%p",
          this, aWindow, mLastFocusedWindow));
     mLastFocusedWindow = aWindow;
     Focus();
 }
 
 void
 nsGtkIMModule::OnBlurWindow(nsWindow* aWindow)
 {
-    if (NS_UNLIKELY(IsDestroyed())) {
+    if (MOZ_UNLIKELY(IsDestroyed())) {
         return;
     }
 
     PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
         ("GtkIMModule(%p): OnBlurWindow, aWindow=%p, mLastFocusedWindow=%p, mIsIMFocused=%s",
          this, aWindow, mLastFocusedWindow, mIsIMFocused ? "YES" : "NO"));
 
     if (!mIsIMFocused || mLastFocusedWindow != aWindow) {
@@ -337,17 +338,17 @@ nsGtkIMModule::OnBlurWindow(nsWindow* aW
 }
 
 bool
 nsGtkIMModule::OnKeyEvent(nsWindow* aCaller, GdkEventKey* aEvent,
                           bool aKeyDownEventWasSent /* = false */)
 {
     NS_PRECONDITION(aEvent, "aEvent must be non-null");
 
-    if (!IsEditable() || NS_UNLIKELY(IsDestroyed())) {
+    if (!IsEditable() || MOZ_UNLIKELY(IsDestroyed())) {
         return false;
     }
 
     PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
         ("GtkIMModule(%p): OnKeyEvent, aCaller=%p, aKeyDownEventWasSent=%s",
          this, aCaller, aKeyDownEventWasSent ? "TRUE" : "FALSE"));
     PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
         ("    aEvent: type=%s, keyval=%s, unicode=0x%X",
@@ -359,17 +360,17 @@ nsGtkIMModule::OnKeyEvent(nsWindow* aCal
     if (aCaller != mLastFocusedWindow) {
         PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
             ("    FAILED, the caller isn't focused window, mLastFocusedWindow=%p",
              mLastFocusedWindow));
         return false;
     }
 
     GtkIMContext* im = GetContext();
-    if (NS_UNLIKELY(!im)) {
+    if (MOZ_UNLIKELY(!im)) {
         PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
             ("    FAILED, there are no context"));
         return false;
     }
 
     mKeyDownEventWasSent = aKeyDownEventWasSent;
     mFilterKeyEvent = true;
     mProcessingKeyEvent = aEvent;
@@ -439,30 +440,30 @@ nsGtkIMModule::OnFocusChangeInGecko(bool
 void
 nsGtkIMModule::ResetIME()
 {
     PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
         ("GtkIMModule(%p): ResetIME, mCompositionState=%s, mIsIMFocused=%s",
          this, GetCompositionStateName(), mIsIMFocused ? "YES" : "NO"));
 
     GtkIMContext *im = GetContext();
-    if (NS_UNLIKELY(!im)) {
+    if (MOZ_UNLIKELY(!im)) {
         PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
             ("    FAILED, there are no context"));
         return;
     }
 
     mIgnoreNativeCompositionEvent = true;
     gtk_im_context_reset(im);
 }
 
 nsresult
 nsGtkIMModule::ResetInputState(nsWindow* aCaller)
 {
-    if (NS_UNLIKELY(IsDestroyed())) {
+    if (MOZ_UNLIKELY(IsDestroyed())) {
         return NS_OK;
     }
 
     PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
         ("GtkIMModule(%p): ResetInputState, aCaller=%p, mCompositionState=%s",
          this, aCaller, GetCompositionStateName()));
 
     if (aCaller != mLastFocusedWindow) {
@@ -481,17 +482,17 @@ nsGtkIMModule::ResetInputState(nsWindow*
     CommitCompositionBy(mDispatchedCompositionString);
 
     return NS_OK;
 }
 
 nsresult
 nsGtkIMModule::CancelIMEComposition(nsWindow* aCaller)
 {
-    if (NS_UNLIKELY(IsDestroyed())) {
+    if (MOZ_UNLIKELY(IsDestroyed())) {
         return NS_OK;
     }
 
     PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
         ("GtkIMModule(%p): CancelIMEComposition, aCaller=%p",
          this, aCaller));
 
     if (aCaller != mLastFocusedWindow) {
@@ -501,34 +502,34 @@ nsGtkIMModule::CancelIMEComposition(nsWi
         return NS_OK;
     }
 
     if (!IsComposing()) {
         return NS_OK;
     }
 
     GtkIMContext *im = GetContext();
-    if (NS_UNLIKELY(!im)) {
+    if (MOZ_UNLIKELY(!im)) {
         PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
             ("    FAILED, there are no context"));
         return NS_OK;
     }
 
     ResetIME();
     CommitCompositionBy(EmptyString());
 
     return NS_OK;
 }
 
 void
 nsGtkIMModule::SetInputContext(nsWindow* aCaller,
                                const InputContext* aContext,
                                const InputContextAction* aAction)
 {
-    if (NS_UNLIKELY(IsDestroyed())) {
+    if (MOZ_UNLIKELY(IsDestroyed())) {
         return;
     }
 
     PR_LOG(gGtkIMLog, PR_LOG_ALWAYS,
         ("GtkIMModule(%p): SetInputContext, aCaller=%p, aState=%s mHTMLInputType=%s",
          this, aCaller, GetEnabledStateName(aContext->mIMEState.mEnabled),
          NS_ConvertUTF16toUTF8(aContext->mHTMLInputType).get()));
 
--- a/widget/gtk2/nsWindow.cpp
+++ b/widget/gtk2/nsWindow.cpp
@@ -55,16 +55,17 @@
 
 #include "nsGkAtoms.h"
 
 #ifdef MOZ_ENABLE_STARTUP_NOTIFICATION
 #define SN_API_NOT_YET_FROZEN
 #include <startup-notification-1.0/libsn/sn.h>
 #endif
 
+#include "mozilla/Likely.h"
 #include "mozilla/Preferences.h"
 #include "nsIPrefService.h"
 #include "nsIGConfService.h"
 #include "nsIServiceManager.h"
 #include "nsIStringBundle.h"
 #include "nsGfxCIID.h"
 #include "nsIObserverService.h"
 #include "LayersTypes.h"
@@ -2022,25 +2023,25 @@ nsWindow::OnExposeEvent(cairo_t *cr)
         if (!mGdkWindow)
             return TRUE;
     }
 
 #if defined(MOZ_WIDGET_GTK2)
     GdkRectangle *rects;
     gint nrects;
     gdk_region_get_rectangles(aEvent->region, &rects, &nrects);
-    if (NS_UNLIKELY(!rects)) // OOM
+    if (MOZ_UNLIKELY(!rects)) // OOM
         return FALSE;
 #else
 #ifdef cairo_copy_clip_rectangle_list
 #error "Looks like we're including Mozilla's cairo instead of system cairo"
 #else
     cairo_rectangle_list_t *rects;
     rects = cairo_copy_clip_rectangle_list(cr);  
-    if (NS_UNLIKELY(rects->status != CAIRO_STATUS_SUCCESS)) {
+    if (MOZ_UNLIKELY(rects->status != CAIRO_STATUS_SUCCESS)) {
        NS_WARNING("Failed to obtain cairo rectangle list.");
        return FALSE;
     }
 #endif
 #endif
 
 // GTK3 TODO?
 #if defined(MOZ_WIDGET_GTK2)
@@ -2202,17 +2203,17 @@ nsWindow::OnExposeEvent(cairo_t *cr)
       AutoLayerManagerSetup setupLayerManager(this, ctx, layerBuffering);
       painted = listener->PaintWindow(this, region, nsIWidgetListener::SENT_WILL_PAINT | nsIWidgetListener::WILL_SEND_DID_PAINT);
     }
 
 #ifdef MOZ_X11
     // PaintWindow can Destroy us (bug 378273), avoid doing any paint
     // operations below if that happened - it will lead to XError and exit().
     if (shaped) {
-        if (NS_LIKELY(!mIsDestroyed)) {
+        if (MOZ_LIKELY(!mIsDestroyed)) {
             if (painted) {
                 nsRefPtr<gfxPattern> pattern = ctx->PopGroup();
 
                 nsRefPtr<gfxImageSurface> img =
                     new gfxImageSurface(gfxIntSize(boundsRect.width, boundsRect.height),
                                         gfxImageSurface::ImageFormatA8);
                 if (img && !img->CairoStatus()) {
                     img->SetDeviceOffset(gfxPoint(-boundsRect.x, -boundsRect.y));
@@ -2231,17 +2232,17 @@ nsWindow::OnExposeEvent(cairo_t *cr)
 
                 ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
                 ctx->SetPattern(pattern);
                 ctx->Paint();
             }
         }
     }
 #  ifdef MOZ_HAVE_SHMIMAGE
-    if (nsShmImage::UseShm() && NS_LIKELY(!mIsDestroyed)) {
+    if (nsShmImage::UseShm() && MOZ_LIKELY(!mIsDestroyed)) {
 #if defined(MOZ_WIDGET_GTK2)
         mShmImage->Put(mGdkWindow, rects, r_end);
 #else
         mShmImage->Put(mGdkWindow, rects);
 #endif
     }
 #  endif  // MOZ_HAVE_SHMIMAGE
 #endif // MOZ_X11
@@ -2729,17 +2730,17 @@ nsWindow::OnButtonPressEvent(GdkEventBut
     event.button = domButton;
     InitButtonEvent(event, aEvent);
     event.pressure = mLastMotionPressure;
 
     DispatchEvent(&event, status);
 
     // right menu click on linux should also pop up a context menu
     if (domButton == nsMouseEvent::eRightButton &&
-        NS_LIKELY(!mIsDestroyed)) {
+        MOZ_LIKELY(!mIsDestroyed)) {
         nsMouseEvent contextMenuEvent(true, NS_CONTEXTMENU, this,
                                       nsMouseEvent::eReal);
         InitButtonEvent(contextMenuEvent, aEvent);
         contextMenuEvent.pressure = mLastMotionPressure;
         DispatchEvent(&contextMenuEvent, status);
     }
 }
 
@@ -2935,17 +2936,17 @@ nsWindow::OnKeyPressEvent(GdkEventKey *a
     // Dispatch keydown event always.  At auto repeating, we should send
     // KEYDOWN -> KEYPRESS -> KEYDOWN -> KEYPRESS ... -> KEYUP
     // However, old distributions (e.g., Ubuntu 9.10) sent native key
     // release event, so, on such platform, the DOM events will be:
     // KEYDOWN -> KEYPRESS -> KEYUP -> KEYDOWN -> KEYPRESS -> KEYUP...
 
     bool isKeyDownCancelled = false;
     if (DispatchKeyDownEvent(aEvent, &isKeyDownCancelled) &&
-        NS_UNLIKELY(mIsDestroyed)) {
+        MOZ_UNLIKELY(mIsDestroyed)) {
         return TRUE;
     }
 
     // If a keydown event handler causes to enable IME, i.e., it moves
     // focus from IME unusable content to IME usable editor, we should
     // send the native key event to IME for the first input on the editor.
     if (!IMEWasEnabled && mIMModule && mIMModule->IsEnabled()) {
         // Notice our keydown event was already dispatched.  This prevents
@@ -3219,17 +3220,17 @@ nsWindow::OnWindowStateEvent(GtkWidget *
       mWidgetListener->SizeModeChanged(mSizeState);
 }
 
 void
 nsWindow::ThemeChanged()
 {
     NotifyThemeChanged();
 
-    if (!mGdkWindow || NS_UNLIKELY(mIsDestroyed))
+    if (!mGdkWindow || MOZ_UNLIKELY(mIsDestroyed))
         return;
 
     // Dispatch theme change notification to all child windows
     GList *children =
         gdk_window_peek_children(mGdkWindow);
     while (children) {
         GdkWindow *gdkWin = GDK_WINDOW(children->data);
 
--- a/widget/qt/nsWindow.cpp
+++ b/widget/qt/nsWindow.cpp
@@ -59,16 +59,17 @@ using namespace QtMobility;
 
 #include "nsIdleService.h"
 #include "nsRenderingContext.h"
 #include "nsIRollupListener.h"
 #include "nsWidgetsCID.h"
 #include "nsQtKeyUtils.h"
 #include "mozilla/Services.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/Likely.h"
 #include "nsIWidgetListener.h"
 
 #include "nsIStringBundle.h"
 #include "nsGfxCIID.h"
 
 #include "imgIContainer.h"
 #include "nsGfxCIID.h"
 #include "nsIInterfaceRequestorUtils.h"
@@ -1051,17 +1052,17 @@ nsWindow::DoPaint(QPainter* aPainter, co
 #endif
     } else if (renderMode == gfxQtPlatform::RENDER_DIRECT) {
         if (!UpdateOffScreenBuffers(depth, aWidget->size(), aWidget)) {
             return false;
         }
         targetSurface = gBufferSurface;
     }
 
-    if (NS_UNLIKELY(!targetSurface))
+    if (MOZ_UNLIKELY(!targetSurface))
         return false;
 
     nsRefPtr<gfxContext> ctx = new gfxContext(targetSurface);
 
     // We will paint to 0, 0 position in offscrenn buffer
     if (renderMode == gfxQtPlatform::RENDER_BUFFERED) {
         ctx->Translate(gfxPoint(-r.x(), -r.y()));
     }
@@ -1086,17 +1087,17 @@ nsWindow::DoPaint(QPainter* aPainter, co
         if (mWidgetListener) {
           nsIntRegion region(rect);
           painted = mWidgetListener->PaintWindow(this, region, nsIWidgetListener::SENT_WILL_PAINT | nsIWidgetListener::WILL_SEND_DID_PAINT);
         }
     }
 
     // DispatchEvent can Destroy us (bug 378273), avoid doing any paint
     // operations below if that happened - it will lead to XError and exit().
-    if (NS_UNLIKELY(mIsDestroyed))
+    if (MOZ_UNLIKELY(mIsDestroyed))
         return painted;
 
     if (!painted)
         return false;
 
     LOGDRAW(("[%p] draw done\n", this));
 
     // Handle buffered painting mode
@@ -1319,17 +1320,17 @@ nsWindow::OnButtonPressEvent(QGraphicsSc
     InitButtonEvent(event, aEvent, 1);
 
     LOG(("%s [%p] button: %d\n", __PRETTY_FUNCTION__, (void*)this, domButton));
 
     nsEventStatus status = DispatchEvent(&event);
 
     // right menu click on linux should also pop up a context menu
     if (domButton == nsMouseEvent::eRightButton &&
-        NS_LIKELY(!mIsDestroyed)) {
+        MOZ_LIKELY(!mIsDestroyed)) {
         nsMouseEvent contextMenuEvent(true, NS_CONTEXTMENU, this,
                                       nsMouseEvent::eReal);
         InitButtonEvent(contextMenuEvent, aEvent, 1);
         DispatchEvent(&contextMenuEvent, status);
     }
 
     return status;
 }
@@ -1569,17 +1570,17 @@ nsWindow::OnKeyPressEvent(QKeyEvent *aEv
         nsKeyEvent downEvent(true, NS_KEY_DOWN, this);
         InitKeyEvent(downEvent, aEvent);
 
         downEvent.keyCode = domKeyCode;
 
         nsEventStatus status = DispatchEvent(&downEvent);
 
         // DispatchEvent can Destroy us (bug 378273)
-        if (NS_UNLIKELY(mIsDestroyed)) {
+        if (MOZ_UNLIKELY(mIsDestroyed)) {
             qWarning() << "Returning[" << __LINE__ << "]: " << "Window destroyed";
             return status;
         }
 
         // If prevent default on keydown, do same for keypress
         if (status == nsEventStatus_eConsumeNoDefault)
             setNoDefault = true;
     }
--- a/widget/xpwidgets/nsPrimitiveHelpers.cpp
+++ b/widget/xpwidgets/nsPrimitiveHelpers.cpp
@@ -30,16 +30,17 @@
 #include "nsReadableUtils.h"
 
 #include "nsIServiceManager.h"
 #include "nsICharsetConverterManager.h"
 // unicode conversion
 #  include "nsIPlatformCharset.h"
 #include "nsISaveAsCharset.h"
 #include "nsAutoPtr.h"
+#include "mozilla/Likely.h"
 
 
 //
 // CreatePrimitiveForData
 //
 // Given some data and the flavor it corresponds to, creates the appropriate
 // nsISupports* wrapper for passing across IDL boundaries. Right now, everything
 // creates a two-byte |nsISupportsString|, except for "text/plain" and native
@@ -62,17 +63,17 @@ nsPrimitiveHelpers :: CreatePrimitiveFor
     }
   }
   else {
     nsCOMPtr<nsISupportsString> primitive =
         do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID);
     if (primitive ) {
       if (aDataLen % 2) { 
         nsAutoArrayPtr<char> buffer(new char[aDataLen + 1]);
-        if (!NS_LIKELY(buffer))
+        if (!MOZ_LIKELY(buffer))
           return;
       
         memcpy(buffer, aDataBuff, aDataLen);
         buffer[aDataLen] = 0;
         const PRUnichar* start = reinterpret_cast<const PRUnichar*>(buffer.get());
         // recall that length takes length as characters, not bytes
         primitive->SetData(Substring(start, start + (aDataLen + 1) / 2));
       } else {
--- a/xpcom/base/nsCycleCollector.cpp
+++ b/xpcom/base/nsCycleCollector.cpp
@@ -132,18 +132,19 @@
 #include <io.h>
 #include <process.h>
 #endif
 
 #ifdef XP_WIN
 #include <windows.h>
 #endif
 
+#include "mozilla/CondVar.h"
+#include "mozilla/Likely.h"
 #include "mozilla/Mutex.h"
-#include "mozilla/CondVar.h"
 #include "mozilla/StandardInteger.h"
 #include "mozilla/Telemetry.h"
 
 using namespace mozilla;
 
 //#define COLLECT_TIME_DEBUG
 
 #define DEFAULT_SHUTDOWN_COLLECTIONS 5
@@ -1683,17 +1684,17 @@ public:
 
 private:
     NS_IMETHOD_(void) NoteRoot(void *root,
                                nsCycleCollectionParticipant *participant)
     {
         MOZ_ASSERT(root);
         MOZ_ASSERT(participant);
 
-        if (!participant->CanSkipInCC(root) || NS_UNLIKELY(WantAllTraces())) {
+        if (!participant->CanSkipInCC(root) || MOZ_UNLIKELY(WantAllTraces())) {
             AddNode(root, participant);
         }
     }
 
     NS_IMETHOD_(void) NoteChild(void *child, nsCycleCollectionParticipant *cp,
                                 nsCString edgeName)
     {
         PtrInfo *childPi = AddNode(child, cp);
@@ -1749,17 +1750,17 @@ GCGraphBuilder::GCGraphBuilder(GCGraph &
         mListener->GetWantAllTraces(&all);
         if (all) {
             flags |= nsCycleCollectionTraversalCallback::WANT_ALL_TRACES;
         }
     }
 
     mFlags |= flags;
 
-    mMergeCompartments = mMergeCompartments && NS_LIKELY(!WantAllTraces());
+    mMergeCompartments = mMergeCompartments && MOZ_LIKELY(!WantAllTraces());
 }
 
 GCGraphBuilder::~GCGraphBuilder()
 {
     if (mPtrToNodeMap.ops)
         PL_DHashTableFinish(&mPtrToNodeMap);
 }
 
@@ -1926,22 +1927,22 @@ GCGraphBuilder::NoteNativeChild(void *ch
 NS_IMETHODIMP_(void)
 GCGraphBuilder::NoteJSChild(void *child) 
 {
     if (!child) {
         return;
     }
 
     nsCString edgeName;
-    if (NS_UNLIKELY(WantDebugInfo())) {
+    if (MOZ_UNLIKELY(WantDebugInfo())) {
         edgeName.Assign(mNextEdgeName);
         mNextEdgeName.Truncate();
     }
 
-    if (xpc_GCThingIsGrayCCThing(child) || NS_UNLIKELY(WantAllTraces())) {
+    if (xpc_GCThingIsGrayCCThing(child) || MOZ_UNLIKELY(WantAllTraces())) {
         if (JSCompartment *comp = MergeCompartment(child)) {
             NoteChild(comp, mJSCompParticipant, edgeName);
         } else {
             NoteChild(child, mJSParticipant, edgeName);
         }
     }
 }
 
--- a/xpcom/base/nsError.h
+++ b/xpcom/base/nsError.h
@@ -5,16 +5,17 @@
 
 #ifndef nsError_h__
 #define nsError_h__
 
 #ifndef nscore_h___
 #include "nscore.h"  /* needed for nsresult */
 #endif
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 
 /*
  * To add error code to your module, you need to do the following:
  *
  * 1) Add a module offset code.  Add yours to the bottom of the list
  *    right below this comment, adding 1.
  *
  * 2) In your module, define a header file which uses one of the
@@ -148,22 +149,22 @@
  * @name Standard Error Handling Macros
  * @return 0 or 1 (false/true with bool type for C++)
  */
 
 #ifdef __cplusplus
 inline uint32_t NS_FAILED_impl(nsresult _nsresult) {
   return static_cast<uint32_t>(_nsresult) & 0x80000000;
 }
-#define NS_FAILED(_nsresult)    ((bool)NS_UNLIKELY(NS_FAILED_impl(_nsresult)))
-#define NS_SUCCEEDED(_nsresult) ((bool)NS_LIKELY(!NS_FAILED_impl(_nsresult)))
+#define NS_FAILED(_nsresult)    ((bool)MOZ_UNLIKELY(NS_FAILED_impl(_nsresult)))
+#define NS_SUCCEEDED(_nsresult) ((bool)MOZ_LIKELY(!NS_FAILED_impl(_nsresult)))
 #else
 #define NS_FAILED_impl(_nsresult) ((_nsresult) & 0x80000000)
-#define NS_FAILED(_nsresult)    (NS_UNLIKELY(NS_FAILED_impl(_nsresult)))
-#define NS_SUCCEEDED(_nsresult) (NS_LIKELY(!NS_FAILED_impl(_nsresult)))
+#define NS_FAILED(_nsresult)    (MOZ_UNLIKELY(NS_FAILED_impl(_nsresult)))
+#define NS_SUCCEEDED(_nsresult) (MOZ_LIKELY(!NS_FAILED_impl(_nsresult)))
 #endif
 
 /**
  * @name Standard Error Generating Macros
  */
 
 #define NS_ERROR_GENERATE(sev, module, code) \
     (nsresult)(((uint32_t)(sev) << 31) | \
--- a/xpcom/base/nscore.h
+++ b/xpcom/base/nscore.h
@@ -358,41 +358,16 @@ typedef uint32_t nsrefcnt;
 #define NS_INT32_TO_PTR(x)  ((void *)   (intptr_t) (x))
 
 /*
  * Use NS_STRINGIFY to form a string literal from the value of a macro.
  */
 #define NS_STRINGIFY_HELPER(x_) #x_
 #define NS_STRINGIFY(x_) NS_STRINGIFY_HELPER(x_)
 
-/*
- * These macros allow you to give a hint to the compiler about branch
- * probability so that it can better optimize.  Use them like this:
- *
- *  if (NS_LIKELY(v == 1)) {
- *    ... expected code path ...
- *  }
- *
- *  if (NS_UNLIKELY(v == 0)) {
- *    ... non-expected code path ...
- *  }
- *
- * These macros are guaranteed to always return 0 or 1.
- * The NS_FAILED/NS_SUCCEEDED macros depends on this.
- * @return 0 or 1
- */
-
-#if defined(__GNUC__) && (__GNUC__ > 2)
-#define NS_LIKELY(x)    (__builtin_expect(!!(x), 1))
-#define NS_UNLIKELY(x)  (__builtin_expect(!!(x), 0))
-#else
-#define NS_LIKELY(x)    (!!(x))
-#define NS_UNLIKELY(x)  (!!(x))
-#endif
-
  /*
   * If we're being linked as standalone glue, we don't want a dynamic
   * dependency on NSPR libs, so we skip the debug thread-safety
   * checks, and we cannot use the THREADSAFE_ISUPPORTS macros.
   */
 #if defined(XPCOM_GLUE) && !defined(XPCOM_GLUE_USE_NSPR)
 #define XPCOM_GLUE_AVOID_NSPR
 #endif
--- a/xpcom/glue/nsCycleCollectionParticipant.h
+++ b/xpcom/glue/nsCycleCollectionParticipant.h
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 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/. */
 
 #ifndef nsCycleCollectionParticipant_h__
 #define nsCycleCollectionParticipant_h__
 
+#include "mozilla/Likely.h"
 #include "mozilla/TypeTraits.h"
 #include "nsISupports.h"
 
 #define NS_CYCLECOLLECTIONPARTICIPANT_IID                                      \
 {                                                                              \
     0x9674489b,                                                                \
     0x1f6f,                                                                    \
     0x4550,                                                                    \
@@ -512,17 +513,17 @@ public:
                          (NS_CYCLE_COLLECTION_CLASSNAME(_class) *that, void *p,\
                           nsCycleCollectionTraversalCallback &cb)              \
   {                                                                            \
     _class *tmp = static_cast<_class*>(p);                                     \
     NS_IMPL_CYCLE_COLLECTION_DESCRIBE(_class, tmp->mRefCnt.get())
 
 #define NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(_cb, _name)                         \
   PR_BEGIN_MACRO                                                               \
-    if (NS_UNLIKELY((_cb).WantDebugInfo())) {                                  \
+    if (MOZ_UNLIKELY((_cb).WantDebugInfo())) {                                 \
       (_cb).NoteNextEdgeName(_name);                                           \
     }                                                                          \
   PR_END_MACRO
 
 #define NS_IMPL_CYCLE_COLLECTION_TRAVERSE_RAWPTR(_field)                       \
   PR_BEGIN_MACRO                                                               \
     NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, #_field);                           \
     cb.NoteXPCOMChild(tmp->_field);                                            \
@@ -883,17 +884,17 @@ struct Skippable
     static NS_METHOD UnrootImpl(void *n);                                      \
     static NS_METHOD TraverseImpl(NS_CYCLE_COLLECTION_CLASSNAME(_class) *that, \
                            void *n, nsCycleCollectionTraversalCallback &cb);
 
 #define NS_DECL_CYCLE_COLLECTION_NATIVE_UNMARK_IF_PURPLE(_class)               \
     static NS_METHOD_(void) UnmarkIfPurpleImpl(void *p)                        \
     {                                                                          \
         _class *tmp = static_cast<_class *>(p);                                \
-        if (NS_LIKELY(tmp->mRefCnt.HasPurpleBufferEntry()))                    \
+        if (MOZ_LIKELY(tmp->mRefCnt.HasPurpleBufferEntry()))                   \
             tmp->mRefCnt.ReleasePurpleBufferEntry();                           \
     }
 
 #define NS_DECL_CYCLE_COLLECTION_STUB_UNMARK_IF_PURPLE(_class)                 \
     static NS_METHOD_(void) UnmarkIfPurpleImpl(void *p) {}
 
 #define NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(_class)                          \
   class NS_CYCLE_COLLECTION_INNERCLASS                                         \
--- a/xpcom/glue/nsDebug.h
+++ b/xpcom/glue/nsDebug.h
@@ -11,16 +11,17 @@
 #endif
 
 #ifndef nsError_h__
 #include "nsError.h"
 #endif 
 
 #include "nsXPCOM.h"
 #include "mozilla/Assertions.h"
+#include "mozilla/Likely.h"
 
 #ifdef DEBUG
 #include "prprf.h"
 #endif
 
 #ifdef DEBUG
 
 /**
@@ -243,28 +244,28 @@
 
 /* Macros for checking the trueness of an expression passed in within an 
  * interface implementation.  These need to be compiled regardless of the */
 /* DEBUG flag
 ******************************************************************************/
 
 #define NS_ENSURE_TRUE(x, ret)                                \
   do {                                                        \
-    if (NS_UNLIKELY(!(x))) {                                  \
+    if (MOZ_UNLIKELY(!(x))) {                                 \
        NS_WARNING("NS_ENSURE_TRUE(" #x ") failed");           \
        return ret;                                            \
     }                                                         \
   } while(0)
 
 #define NS_ENSURE_FALSE(x, ret)                               \
   NS_ENSURE_TRUE(!(x), ret)
 
 #define NS_ENSURE_TRUE_VOID(x)                                \
   do {                                                        \
-    if (NS_UNLIKELY(!(x))) {                                  \
+    if (MOZ_UNLIKELY(!(x))) {                                 \
        NS_WARNING("NS_ENSURE_TRUE(" #x ") failed");           \
        return;                                                \
     }                                                         \
   } while(0)
 
 #define NS_ENSURE_FALSE_VOID(x)                               \
   NS_ENSURE_TRUE_VOID(!(x))
 
--- a/xpcom/glue/nsISupportsImpl.h
+++ b/xpcom/glue/nsISupportsImpl.h
@@ -26,16 +26,17 @@
 #endif
 
 #include "nsDebug.h"
 #include "nsTraceRefcnt.h"
 #include "nsCycleCollector.h"
 #include "nsCycleCollectorUtils.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/Assertions.h"
+#include "mozilla/Likely.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // Macros to help detect thread-safety:
 
 #if defined(DEBUG) && !defined(XPCOM_GLUE_AVOID_NSPR)
 
 class nsAutoOwningThread {
 public:
@@ -111,17 +112,17 @@ public:
 
   nsCycleCollectingAutoRefCnt(nsrefcnt aValue)
     : mTagged(NS_CCAR_REFCNT_TO_TAGGED(aValue))
   {
   }
 
   MOZ_ALWAYS_INLINE nsrefcnt incr(void *owner)
   {
-    if (NS_UNLIKELY(mTagged == NS_CCAR_TAGGED_STABILIZED_REFCNT)) {
+    if (MOZ_UNLIKELY(mTagged == NS_CCAR_TAGGED_STABILIZED_REFCNT)) {
       // The sentinel value "purple bit alone, refcount 0" means
       // that we're stabilized, during finalization. In this
       // state we lie about our actual refcount if anyone asks
       // and say it's 2, which is basically true: the caller who
       // is incrementing has a reference, as does the decr() frame
       // that stabilized-and-is-deleting us.
       return 2;
     }
@@ -155,25 +156,25 @@ public:
 
   MOZ_ALWAYS_INLINE nsrefcnt decr(nsISupports *owner)
   {
     return decr(owner, nullptr);
   }
 
   MOZ_ALWAYS_INLINE nsrefcnt decr(void *owner, nsCycleCollectionParticipant *p)
   {
-    if (NS_UNLIKELY(mTagged == NS_CCAR_TAGGED_STABILIZED_REFCNT))
+    if (MOZ_UNLIKELY(mTagged == NS_CCAR_TAGGED_STABILIZED_REFCNT))
       return 1;
 
     nsrefcnt refcount;
     if (HasPurpleBufferEntry()) {
       nsPurpleBufferEntry *e = NS_CCAR_TAGGED_TO_PURPLE_ENTRY(mTagged);
       NS_ASSERTION(e->mObject == owner, "wrong entry");
       refcount = --(e->mRefCnt);
-      if (NS_UNLIKELY(refcount == 0)) {
+      if (MOZ_UNLIKELY(refcount == 0)) {
 #ifdef DEBUG_CC
         nsCycleCollector_logPurpleRemoval(
           NS_CCAR_TAGGED_TO_PURPLE_ENTRY(mTagged)->mObject);
 #endif
         e->mObject = nullptr;
         mTagged = NS_CCAR_REFCNT_TO_TAGGED(0);
       } else {
 #ifdef DEBUG_CC
@@ -184,17 +185,17 @@ public:
 #endif
         e->mNotPurple = false;
       }
     } else {
       refcount = NS_CCAR_TAGGED_TO_REFCNT(mTagged);
       --refcount;
 
       nsPurpleBufferEntry *e;
-      if (NS_LIKELY(refcount > 0) &&
+      if (MOZ_LIKELY(refcount > 0) &&
           ((e = NS_CycleCollectorSuspect2(owner, p)))) {
         e->mRefCnt = refcount;
         mTagged = NS_CCAR_PURPLE_ENTRY_TO_TAGGED(e);
       } else {
         mTagged = NS_CCAR_REFCNT_TO_TAGGED(refcount);
       }
     }
 
@@ -230,20 +231,20 @@ public:
   MOZ_ALWAYS_INLINE bool IsPurple() const
   {
     return HasPurpleBufferEntry() &&
       !(NS_CCAR_TAGGED_TO_PURPLE_ENTRY(mTagged)->mNotPurple);
   }
 
   MOZ_ALWAYS_INLINE nsrefcnt get() const
   {
-    if (NS_UNLIKELY(mTagged == NS_CCAR_TAGGED_STABILIZED_REFCNT))
+    if (MOZ_UNLIKELY(mTagged == NS_CCAR_TAGGED_STABILIZED_REFCNT))
       return 1;
 
-    return NS_UNLIKELY(HasPurpleBufferEntry())
+    return MOZ_UNLIKELY(HasPurpleBufferEntry())
              ? NS_CCAR_TAGGED_TO_PURPLE_ENTRY(mTagged)->mRefCnt
              : NS_CCAR_TAGGED_TO_REFCNT(mTagged);
   }
 
   MOZ_ALWAYS_INLINE operator nsrefcnt() const
   {
     return get();
   }
@@ -293,17 +294,17 @@ public:
 #define NS_DECL_CYCLE_COLLECTING_ISUPPORTS                                    \
 public:                                                                       \
   NS_IMETHOD QueryInterface(REFNSIID aIID,                                    \
                             void** aInstancePtr);                             \
   NS_IMETHOD_(nsrefcnt) AddRef(void);                                         \
   NS_IMETHOD_(nsrefcnt) Release(void);                                        \
   void UnmarkIfPurple()                                                       \
   {                                                                           \
-    if (NS_LIKELY(mRefCnt.HasPurpleBufferEntry()))                            \
+    if (MOZ_LIKELY(mRefCnt.HasPurpleBufferEntry()))                           \
       mRefCnt.ReleasePurpleBufferEntry();                                     \
   }                                                                           \
 protected:                                                                    \
   nsCycleCollectingAutoRefCnt mRefCnt;                                        \
   NS_DECL_OWNINGTHREAD                                                        \
 public:
 
 
--- a/xpcom/glue/nsProxyRelease.h
+++ b/xpcom/glue/nsProxyRelease.h
@@ -5,16 +5,17 @@
 
 #ifndef nsProxyRelease_h__
 #define nsProxyRelease_h__
 
 #include "nsIEventTarget.h"
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsThreadUtils.h"
+#include "mozilla/Likely.h"
 
 #ifdef XPCOM_GLUE_AVOID_NSPR
 #error NS_ProxyRelease implementation depends on NSPR.
 #endif
 
 /**
  * Ensure that a nsCOMPtr is released on the target thread.
  *
@@ -123,17 +124,17 @@ public:
         return;
       }
       NS_ProxyRelease(mainThread, mRawPtr);
     }
   }
 
   T* get() {
     // Nobody should be touching the raw pointer off-main-thread.
-    if (NS_UNLIKELY(!NS_IsMainThread()))
+    if (MOZ_UNLIKELY(!NS_IsMainThread()))
       MOZ_CRASH();
     return mRawPtr;
   }
 
   NS_IMETHOD_(nsrefcnt) Release();
   NS_IMETHOD_(nsrefcnt) AddRef();
 
 private:
--- a/xpcom/glue/nsThreadUtils.cpp
+++ b/xpcom/glue/nsThreadUtils.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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 "nsThreadUtils.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 
 #ifdef MOZILLA_INTERNAL_API
 # include "nsThreadManager.h"
 #else
 # include "nsXPCOMCIDInternal.h"
 # include "nsIThreadManager.h"
 # include "nsServiceManagerUtils.h"
 #endif
@@ -309,19 +310,19 @@ nsAutoLowPriorityIO::nsAutoLowPriorityIO
 #else
   lowIOPrioritySet = false;
 #endif
 }
 
 nsAutoLowPriorityIO::~nsAutoLowPriorityIO()
 {
 #if defined(XP_WIN)
-  if (NS_LIKELY(lowIOPrioritySet)) {
+  if (MOZ_LIKELY(lowIOPrioritySet)) {
     // On Windows the old thread priority is automatically restored
     SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
   }
 #elif defined(XP_MACOSX)
-  if (NS_LIKELY(lowIOPrioritySet)) {
+  if (MOZ_LIKELY(lowIOPrioritySet)) {
     setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_THREAD, oldPriority);
   }
 #endif
 }
 
--- a/xpcom/glue/nsThreadUtils.h
+++ b/xpcom/glue/nsThreadUtils.h
@@ -11,16 +11,17 @@
 #include "prinrval.h"
 #include "nsIThreadManager.h"
 #include "nsIThread.h"
 #include "nsIRunnable.h"
 #include "nsStringGlue.h"
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "mozilla/threads/nsThreadIDs.h"
+#include "mozilla/Likely.h"
 
 // This is needed on some systems to prevent collisions between the symbols
 // appearing in xpcom_core and xpcomglue.  It may be unnecessary in the future
 // with better toolchain support.
 #ifdef MOZILLA_INTERNAL_API
 # define NS_SetThreadName NS_SetThreadName_P
 # define NS_NewThread NS_NewThread_P
 # define NS_NewNamedThread NS_NewNamedThread_P
@@ -340,17 +341,17 @@ class nsRunnableMethodImpl
 public:
   nsRunnableMethodImpl(ClassType *obj,
                        Method method)
     : mReceiver(obj)
     , mMethod(method)
   {}
 
   NS_IMETHOD Run() {
-    if (NS_LIKELY(mReceiver.mObj))
+    if (MOZ_LIKELY(mReceiver.mObj))
       ((*mReceiver.mObj).*mMethod)();
     return NS_OK;
   }
 
   void Revoke() {
     mReceiver.Revoke();
   }
 };
--- a/xpcom/glue/pldhash.cpp
+++ b/xpcom/glue/pldhash.cpp
@@ -11,16 +11,17 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include "prbit.h"
 #include "pldhash.h"
 #include "mozilla/HashFunctions.h"
 #include "nsDebug.h"     /* for PR_ASSERT */
 #include "nsAlgorithm.h"
+#include "mozilla/Likely.h"
 
 #ifdef PL_DHASHMETER
 # if defined MOZILLA_CLIENT && defined DEBUG_XXXbrendan
 #  include "nsTraceMalloc.h"
 # endif
 # define METER(x)       x
 #else
 # define METER(x)       /* nothing */
@@ -407,17 +408,17 @@ SearchTable(PLDHashTable *table, const v
     sizeLog2 = PL_DHASH_BITS - table->hashShift;
     hash2 = HASH2(keyHash, sizeLog2, hashShift);
     sizeMask = (1u << sizeLog2) - 1;
 
     /* Save the first removed entry pointer so PL_DHASH_ADD can recycle it. */
     firstRemoved = NULL;
 
     for (;;) {
-        if (NS_UNLIKELY(ENTRY_IS_REMOVED(entry))) {
+        if (MOZ_UNLIKELY(ENTRY_IS_REMOVED(entry))) {
             if (!firstRemoved)
                 firstRemoved = entry;
         } else {
             if (op == PL_DHASH_ADD)
                 entry->keyHash |= COLLISION_FLAG;
         }
 
         METER(table->stats.steps++);
--- a/xpcom/io/nsStorageStream.cpp
+++ b/xpcom/io/nsStorageStream.cpp
@@ -17,16 +17,17 @@
 #include "nsSegmentedBuffer.h"
 #include "nsStreamUtils.h"
 #include "nsCOMPtr.h"
 #include "prbit.h"
 #include "nsIInputStream.h"
 #include "nsISeekableStream.h"
 #include "prlog.h"
 #include "mozilla/Attributes.h"
+#include "mozilla/Likely.h"
 
 #if defined(PR_LOGGING)
 //
 // Log module for StorageStream logging...
 //
 // To enable logging (see prlog.h for full details):
 //
 //    set NSPR_LOG_MODULES=StorageStreamLog:5
@@ -150,17 +151,17 @@ nsStorageStream::Write(const char *aBuff
     readCursor = aBuffer;
     // If no segments have been created yet, create one even if we don't have
     // to write any data; this enables creating an input stream which reads from
     // the very end of the data for any amount of data in the stream (i.e.
     // this stream contains N bytes of data and newInputStream(N) is called),
     // even for N=0 (with the caveat that we require .write("", 0) be called to
     // initialize internal buffers).
     bool firstTime = mSegmentedBuffer->GetSegmentCount() == 0;
-    while (remaining || NS_UNLIKELY(firstTime)) {
+    while (remaining || MOZ_UNLIKELY(firstTime)) {
         firstTime = false;
         availableInSegment = mSegmentEnd - mWriteCursor;
         if (!availableInSegment) {
             mWriteCursor = mSegmentedBuffer->AppendNewSegment();
             if (!mWriteCursor) {
                 mSegmentEnd = 0;
                 rv = NS_ERROR_OUT_OF_MEMORY;
                 goto out;