Bug 835542 - Implement mozilla::Abs. r=Ms2ger
authorJeff Walden <jwalden@mit.edu>
Fri, 15 Feb 2013 19:55:36 -0800
changeset 134111 5a8b3e397ffcc45895074dfdc68ee4ed947ec8b0
parent 134110 645cf7ea0876a38cc9aead0fbabd408deca51109
child 134112 b4d1bc6b9d1a541f0a3fa98ae8aa22e4cc7776ae
push id2452
push userlsblakk@mozilla.com
push dateMon, 13 May 2013 16:59:38 +0000
treeherdermozilla-beta@d4b152d29d8d [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersMs2ger
bugs835542
milestone22.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 835542 - Implement mozilla::Abs. r=Ms2ger
content/canvas/src/CanvasRenderingContext2D.cpp
content/events/src/nsEventStateManager.cpp
content/html/content/src/nsHTMLMediaElement.cpp
content/media/MediaDecoder.cpp
docshell/shistory/src/nsSHistory.cpp
editor/libeditor/html/nsHTMLEditRules.cpp
editor/libeditor/html/nsHTMLObjectResizer.cpp
gfx/layers/basic/BasicTiledThebesLayer.cpp
gfx/thebes/gfxFont.cpp
js/src/ion/RangeAnalysis.cpp
js/src/ion/RangeAnalysis.h
js/src/ion/arm/Assembler-arm.h
js/src/ion/arm/MacroAssembler-arm.cpp
js/src/jsmath.cpp
js/src/methodjit/FastArithmetic.cpp
js/src/methodjit/LoopState.cpp
js/src/prmjtime.cpp
js/src/vm/DateTime.h
layout/base/nsCSSColorUtils.h
layout/base/nsCSSRendering.cpp
layout/generic/nsTextFrameThebes.cpp
layout/mathml/nsMathMLChar.cpp
layout/style/nsStyleAnimation.cpp
layout/tables/nsTableFrame.cpp
layout/xul/tree/nsTreeBodyFrame.cpp
mfbt/MathAlgorithms.h
widget/gtk2/nsNativeKeyBindings.cpp
widget/nsGUIEvent.h
widget/windows/nsWindow.cpp
xpcom/ds/TimeStamp_windows.cpp
xpcom/io/nsMultiplexInputStream.cpp
xpfe/appshell/src/nsXULWindow.cpp
--- a/content/canvas/src/CanvasRenderingContext2D.cpp
+++ b/content/canvas/src/CanvasRenderingContext2D.cpp
@@ -78,29 +78,28 @@
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/ImageData.h"
 #include "mozilla/dom/PBrowserParent.h"
 #include "mozilla/dom/TypedArray.h"
 #include "mozilla/gfx/2D.h"
 #include "mozilla/gfx/PathHelpers.h"
 #include "mozilla/ipc/DocumentRendererParent.h"
 #include "mozilla/ipc/PDocumentRendererParent.h"
+#include "mozilla/MathAlgorithms.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/unused.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsWrapperCacheInlines.h"
 #include "nsJSUtils.h"
 #include "XPCQuickStubs.h"
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/dom/HTMLImageElement.h"
 #include "nsHTMLVideoElement.h"
 #include "mozilla/dom/CanvasRenderingContext2DBinding.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 #ifdef XP_WIN
 #include "gfxWindowsPlatform.h"
 #endif
 
 // windows.h (included by chromium code) defines this, in its infinite wisdom
 #undef DrawText
 
@@ -3684,18 +3683,18 @@ CanvasRenderingContext2D::CreateImageDat
   if (!sw || !sh) {
     error.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
     return NULL;
   }
 
   int32_t wi = JS_DoubleToInt32(sw);
   int32_t hi = JS_DoubleToInt32(sh);
 
-  uint32_t w = std::abs(wi);
-  uint32_t h = std::abs(hi);
+  uint32_t w = Abs(wi);
+  uint32_t h = Abs(hi);
   return mozilla::dom::CreateImageData(cx, this, w, h, error);
 }
 
 already_AddRefed<ImageData>
 CanvasRenderingContext2D::CreateImageData(JSContext* cx,
                                           ImageData& imagedata,
                                           ErrorResult& error)
 {
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -1,14 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 sw=2 et 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 "mozilla/Attributes.h"
+#include "mozilla/MathAlgorithms.h"
 #include "mozilla/dom/TabParent.h"
 
 #include "nsCOMPtr.h"
 #include "nsEventStateManager.h"
 #include "nsEventListenerManager.h"
 #include "nsIMEStateManager.h"
 #include "nsContentEventHandler.h"
 #include "nsIContent.h"
@@ -88,22 +90,19 @@
 #include "nsIController.h"
 #include "nsICommandParams.h"
 #include "mozilla/Services.h"
 #include "mozAutoDocUpdate.h"
 #include "mozilla/dom/HTMLLabelElement.h"
 
 #include "mozilla/Preferences.h"
 #include "mozilla/LookAndFeel.h"
-#include "mozilla/Attributes.h"
 #include "sampler.h"
 
 #include "nsIDOMClientRect.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 #ifdef XP_MACOSX
 #import <ApplicationServices/ApplicationServices.h>
 #endif
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
@@ -2048,18 +2047,18 @@ nsEventStateManager::GenerateDragGesture
       if (!pixelThresholdX)
         pixelThresholdX = 5;
       if (!pixelThresholdY)
         pixelThresholdY = 5;
     }
 
     // fire drag gesture if mouse has moved enough
     nsIntPoint pt = aEvent->refPoint + aEvent->widget->WidgetToScreenOffset();
-    if (std::abs(pt.x - mGestureDownPoint.x) > pixelThresholdX ||
-        std::abs(pt.y - mGestureDownPoint.y) > pixelThresholdY) {
+    if (Abs(pt.x - mGestureDownPoint.x) > pixelThresholdX ||
+        Abs(pt.y - mGestureDownPoint.y) > pixelThresholdY) {
       if (mClickHoldContextMenu) {
         // stop the click-hold before we fire off the drag gesture, in case
         // it takes a long time
         KillClickHoldTimer();
       }
 
       nsRefPtr<nsDOMDataTransfer> dataTransfer = new nsDOMDataTransfer();
       if (!dataTransfer)
@@ -2875,24 +2874,24 @@ nsEventStateManager::DoScrollText(nsIScr
   }
 
   // We shouldn't scroll more one page at once except when over one page scroll
   // is allowed for the event.
   nsSize pageSize = aScrollableFrame->GetPageScrollAmount();
   nsIntSize devPixelPageSize(pc->AppUnitsToDevPixels(pageSize.width),
                              pc->AppUnitsToDevPixels(pageSize.height));
   if (!WheelPrefs::GetInstance()->IsOverOnePageScrollAllowedX(aEvent) &&
-      std::abs(actualDevPixelScrollAmount.x) > devPixelPageSize.width) {
+      Abs(actualDevPixelScrollAmount.x) > devPixelPageSize.width) {
     actualDevPixelScrollAmount.x =
       (actualDevPixelScrollAmount.x >= 0) ? devPixelPageSize.width :
                                             -devPixelPageSize.width;
   }
 
   if (!WheelPrefs::GetInstance()->IsOverOnePageScrollAllowedY(aEvent) &&
-      std::abs(actualDevPixelScrollAmount.y) > devPixelPageSize.height) {
+      Abs(actualDevPixelScrollAmount.y) > devPixelPageSize.height) {
     actualDevPixelScrollAmount.y =
       (actualDevPixelScrollAmount.y >= 0) ? devPixelPageSize.height :
                                             -devPixelPageSize.height;
   }
 
   bool isDeltaModePixel =
     (aEvent->deltaMode == nsIDOMWheelEvent::DOM_DELTA_PIXEL);
 
@@ -5574,18 +5573,18 @@ nsEventStateManager::WheelPrefs::CancelA
 
 nsEventStateManager::WheelPrefs::Action
 nsEventStateManager::WheelPrefs::ComputeActionFor(widget::WheelEvent* aEvent)
 {
   Index index = GetIndexFor(aEvent);
   Init(index);
 
   bool deltaXPreferred =
-    (std::abs(aEvent->deltaX) > std::abs(aEvent->deltaY) &&
-     std::abs(aEvent->deltaX) > std::abs(aEvent->deltaZ));
+    (Abs(aEvent->deltaX) > Abs(aEvent->deltaY) &&
+     Abs(aEvent->deltaX) > Abs(aEvent->deltaZ));
   Action* actions = deltaXPreferred ? mOverriddenActionsX : mActions;
   if (actions[index] == ACTION_NONE || actions[index] == ACTION_SCROLL) {
     return actions[index];
   }
 
   // Momentum events shouldn't run special actions.
   if (aEvent->isMomentum) {
     // Use the default action.  Note that user might kill the wheel scrolling.
@@ -5609,21 +5608,21 @@ nsEventStateManager::WheelPrefs::NeedToC
 }
 
 bool
 nsEventStateManager::WheelPrefs::IsOverOnePageScrollAllowedX(
                                    widget::WheelEvent* aEvent)
 {
   Index index = GetIndexFor(aEvent);
   Init(index);
-  return std::abs(mMultiplierX[index]) >=
+  return Abs(mMultiplierX[index]) >=
            MIN_MULTIPLIER_VALUE_ALLOWING_OVER_ONE_PAGE_SCROLL;
 }
 
 bool
 nsEventStateManager::WheelPrefs::IsOverOnePageScrollAllowedY(
                                    widget::WheelEvent* aEvent)
 {
   Index index = GetIndexFor(aEvent);
   Init(index);
-  return std::abs(mMultiplierY[index]) >=
+  return Abs(mMultiplierY[index]) >=
            MIN_MULTIPLIER_VALUE_ALLOWING_OVER_ONE_PAGE_SCROLL;
 }
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -1,15 +1,16 @@
 /* -*- 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 "nsHTMLMediaElement.h"
+#include "mozilla/MathAlgorithms.h"
 #include "mozilla/Util.h"
 
 #include "base/basictypes.h"
 #include "nsIDOMHTMLMediaElement.h"
 #include "nsIDOMHTMLSourceElement.h"
 #include "TimeRanges.h"
 #include "nsGenericHTMLElement.h"
 #include "nsAttrValueInlines.h"
@@ -67,18 +68,16 @@
 
 #include "AudioChannelService.h"
 
 #include "nsCSSParser.h"
 #include "nsIMediaList.h"
 
 #include "ImageContainer.h"
 #include "nsIPowerManagerService.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 #include <algorithm>
 
 #ifdef MOZ_OGG
 #include "OggDecoder.h"
 #endif
 #ifdef MOZ_WAVE
 #include "WaveDecoder.h"
 #endif
@@ -3515,20 +3514,20 @@ void nsHTMLMediaElement::NotifyAudioAvai
   }
 }
 
 static double ClampPlaybackRate(double aPlaybackRate)
 {
   if (aPlaybackRate == 0.0) {
     return aPlaybackRate;
   }
-  if (std::abs(aPlaybackRate) < MIN_PLAYBACKRATE) {
+  if (Abs(aPlaybackRate) < MIN_PLAYBACKRATE) {
     return aPlaybackRate < 0 ? -MIN_PLAYBACKRATE : MIN_PLAYBACKRATE;
   }
-  if (std::abs(aPlaybackRate) > MAX_PLAYBACKRATE) {
+  if (Abs(aPlaybackRate) > MAX_PLAYBACKRATE) {
     return aPlaybackRate < 0 ? -MAX_PLAYBACKRATE : MAX_PLAYBACKRATE;
   }
   return aPlaybackRate;
 }
 
 /* attribute double defaultPlaybackRate; */
 NS_IMETHODIMP nsHTMLMediaElement::GetDefaultPlaybackRate(double* aDefaultPlaybackRate)
 {
--- a/content/media/MediaDecoder.cpp
+++ b/content/media/MediaDecoder.cpp
@@ -1,34 +1,33 @@
 /* -*- 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 "MediaDecoder.h"
+#include "mozilla/FloatingPoint.h"
+#include "mozilla/MathAlgorithms.h"
 #include <limits>
 #include "nsNetUtil.h"
 #include "AudioStream.h"
 #include "nsHTMLVideoElement.h"
 #include "nsIObserver.h"
 #include "nsIObserverService.h"
 #include "nsTArray.h"
 #include "VideoUtils.h"
 #include "MediaDecoderStateMachine.h"
 #include "mozilla/dom/TimeRanges.h"
 #include "nsContentUtils.h"
 #include "ImageContainer.h"
 #include "MediaResource.h"
 #include "nsError.h"
 #include "mozilla/Preferences.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 #include <algorithm>
-#include <mozilla/FloatingPoint.h>
 
 #ifdef MOZ_WMF
 #include "WMFDecoder.h"
 #endif
 
 using namespace mozilla::layers;
 using namespace mozilla::dom;
 
@@ -590,21 +589,21 @@ nsresult MediaDecoder::Seek(double aTime
       // |range + 1| can't be negative, because the only possible negative value
       // for |range| is -1.
       if (uint32_t(range + 1) < length) {
         double leftBound, rightBound;
         res = seekable.End(range, &leftBound);
         NS_ENSURE_SUCCESS(res, NS_OK);
         res = seekable.Start(range + 1, &rightBound);
         NS_ENSURE_SUCCESS(res, NS_OK);
-        double distanceLeft = std::abs(leftBound - aTime);
-        double distanceRight = std::abs(rightBound - aTime);
+        double distanceLeft = Abs(leftBound - aTime);
+        double distanceRight = Abs(rightBound - aTime);
         if (distanceLeft == distanceRight) {
-          distanceLeft = std::abs(leftBound - mCurrentTime);
-          distanceRight = std::abs(rightBound - mCurrentTime);
+          distanceLeft = Abs(leftBound - mCurrentTime);
+          distanceRight = Abs(rightBound - mCurrentTime);
         } 
         aTime = (distanceLeft < distanceRight) ? leftBound : rightBound;
       } else {
         // Seek target is after the end last range in seekable data.
         // Clamp the seek target to the end of the last seekable range.
         res = seekable.End(length - 1, &aTime);
         NS_ENSURE_SUCCESS(res, NS_OK);
       }
--- a/docshell/shistory/src/nsSHistory.cpp
+++ b/docshell/shistory/src/nsSHistory.cpp
@@ -30,18 +30,17 @@
 #include "mozilla/Services.h"
 #include "nsTArray.h"
 #include "nsCOMArray.h"
 #include "nsDocShell.h"
 #include "mozilla/Attributes.h"
 
 // For calculating max history entries and max cachable contentviewers
 #include "nspr.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double), and std::log(double)
+#include "mozilla/MathAlgorithms.h"
 
 using namespace mozilla;
 
 #define PREF_SHISTORY_SIZE "browser.sessionhistory.max_entries"
 #define PREF_SHISTORY_MAX_TOTAL_VIEWERS "browser.sessionhistory.max_total_viewers"
 
 static const char* kObservedPrefs[] = {
   PREF_SHISTORY_SIZE,
@@ -1097,27 +1096,26 @@ nsSHistory::GloballyEvictContentViewers(
         // Because one content viewer might belong to multiple SHEntries, we
         // have to search through shTransactions to see if we already know
         // about this content viewer.  If we find the viewer, update its
         // distance from the SHistory's index and continue.
         bool found = false;
         for (uint32_t j = 0; j < shTransactions.Length(); j++) {
           TransactionAndDistance &container = shTransactions[j];
           if (container.mViewer == contentViewer) {
-            container.mDistance = std::min(container.mDistance,
-                                         std::abs(i - shist->mIndex));
+            container.mDistance = std::min(container.mDistance, Abs(i - shist->mIndex));
             found = true;
             break;
           }
         }
 
         // If we didn't find a TransactionAndDistance for this content viewer, make a new
         // one.
         if (!found) {
-          TransactionAndDistance container(trans, std::abs(i - shist->mIndex));
+          TransactionAndDistance container(trans, Abs(i - shist->mIndex));
           shTransactions.AppendElement(container);
         }
       }
 
       nsISHTransaction *temp = trans;
       temp->GetNext(getter_AddRefs(trans));
     }
 
--- a/editor/libeditor/html/nsHTMLEditRules.cpp
+++ b/editor/libeditor/html/nsHTMLEditRules.cpp
@@ -2,16 +2,17 @@
 /* vim: set ts=2 sw=2 et tw=79: */
 /* 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 <stdlib.h>
 
 #include "mozilla/Assertions.h"
+#include "mozilla/MathAlgorithms.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Selection.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/mozalloc.h"
 #include "nsAString.h"
 #include "nsAlgorithm.h"
 #include "nsCOMArray.h"
 #include "nsCRT.h"
@@ -49,18 +50,16 @@
 #include "nsReadableUtils.h"
 #include "nsString.h"
 #include "nsStringFwd.h"
 #include "nsTArray.h"
 #include "nsTextEditUtils.h"
 #include "nsThreadUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsWSRunObject.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 #include <algorithm>
 
 class nsISupports;
 class nsRulesInfo;
 
 using namespace mozilla;
 
 //const static char* kMOZEditorBogusNodeAttr="MOZ_EDITOR_BOGUS_NODE";
@@ -1924,17 +1923,17 @@ nsHTMLEditRules::WillDeleteSelection(Sel
         res = range->GetStartOffset(&so);
         NS_ENSURE_SUCCESS(res, res);
         res = range->GetEndOffset(&eo);
         NS_ENSURE_SUCCESS(res, res);
       }
       res = nsWSRunObject::PrepareToDeleteRange(mHTMLEditor, address_of(visNode), &so, address_of(visNode), &eo);
       NS_ENSURE_SUCCESS(res, res);
       nsCOMPtr<nsIDOMCharacterData> nodeAsText(do_QueryInterface(visNode));
-      res = mHTMLEditor->DeleteText(nodeAsText, std::min(so, eo), std::abs(eo - so));
+      res = mHTMLEditor->DeleteText(nodeAsText, std::min(so, eo), Abs(eo - so));
       *aHandled = true;
       NS_ENSURE_SUCCESS(res, res);    
       res = InsertBRIfNeeded(aSelection);
       return res;
     } else if (wsType == WSType::special || wsType == WSType::br ||
                nsHTMLEditUtils::IsHR(visNode)) {
       // short circuit for invisible breaks.  delete them and recurse.
       if (nsTextEditUtils::IsBreak(visNode) && !mHTMLEditor->IsVisBreak(visNode))
@@ -4384,17 +4383,17 @@ nsHTMLEditRules::CreateStyleForInsertTex
     NS_ENSURE_SUCCESS(res, res);
     node = newNode;
     offset = 0;
     weDidSomething = true;
 
     if (relFontSize) {
       // dir indicated bigger versus smaller.  1 = bigger, -1 = smaller
       int32_t dir = relFontSize > 0 ? 1 : -1;
-      for (int32_t j = 0; j < abs(relFontSize); j++) {
+      for (int32_t j = 0; j < Abs(relFontSize); j++) {
         res = mHTMLEditor->RelativeFontChangeOnTextNode(dir, nodeAsText,
                                                         0, -1);
         NS_ENSURE_SUCCESS(res, res);
       }
     }
 
     while (item) {
       res = mHTMLEditor->SetInlinePropertyOnNode(node, item->tag, &item->attr,
--- a/editor/libeditor/html/nsHTMLObjectResizer.cpp
+++ b/editor/libeditor/html/nsHTMLObjectResizer.cpp
@@ -1,14 +1,15 @@
 /* -*- 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/LookAndFeel.h"
+#include "mozilla/MathAlgorithms.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/mozalloc.h"
 #include "nsAString.h"
 #include "nsAlgorithm.h"
 #include "nsAutoPtr.h"
 #include "nsCOMArray.h"
 #include "nsCOMPtr.h"
 #include "nsDebug.h"
@@ -37,18 +38,16 @@
 #include "nsIPresShell.h"
 #include "nsISupportsUtils.h"
 #include "nsPIDOMWindow.h"
 #include "nsReadableUtils.h"
 #include "nsString.h"
 #include "nsStringFwd.h"
 #include "nsSubstringTuple.h"
 #include "nscore.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 #include <algorithm>
 
 class nsISelection;
 
 using namespace mozilla;
 
 class nsHTMLEditUtils;
 
@@ -871,18 +870,18 @@ nsHTMLEditor::MouseMove(nsIDOMEvent* aMo
     mouseEvent->GetClientX(&clientX);
     mouseEvent->GetClientY(&clientY);
 
     int32_t xThreshold =
       LookAndFeel::GetInt(LookAndFeel::eIntID_DragThresholdX, 1);
     int32_t yThreshold =
       LookAndFeel::GetInt(LookAndFeel::eIntID_DragThresholdY, 1);
 
-    if (std::abs(clientX - mOriginalX ) * 2 >= xThreshold ||
-        std::abs(clientY - mOriginalY ) * 2 >= yThreshold) {
+    if (Abs(clientX - mOriginalX) * 2 >= xThreshold ||
+        Abs(clientY - mOriginalY) * 2 >= yThreshold) {
       mGrabberClicked = false;
       StartMoving(nullptr);
     }
   }
   if (mIsMoving) {
     nsCOMPtr<nsIDOMMouseEvent> mouseEvent ( do_QueryInterface(aMouseEvent) );
     int32_t clientX, clientY;
     mouseEvent->GetClientX(&clientX);
--- a/gfx/layers/basic/BasicTiledThebesLayer.cpp
+++ b/gfx/layers/basic/BasicTiledThebesLayer.cpp
@@ -1,19 +1,18 @@
 /* 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/layers/PLayersChild.h"
+#include "mozilla/MathAlgorithms.h"
 #include "BasicTiledThebesLayer.h"
 #include "gfxImageSurface.h"
 #include "sampler.h"
 #include "gfxPlatform.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 #ifdef GFX_TILEDLAYER_DEBUG_OVERLAY
 #include "cairo.h"
 #include <sstream>
 using mozilla::layers::Layer;
 static void DrawDebugOverlay(gfxImageSurface* imgSurf, int x, int y)
 {
   gfxContext c(imgSurf);
@@ -372,17 +371,17 @@ BasicTiledThebesLayer::ComputeProgressiv
   // This loop will always terminate, as there is at least one tile area
   // along the first/last row/column intersecting with regionToPaint, or its
   // bounds would have been smaller.
   while (true) {
     aRegionToPaint.And(aInvalidRegion, tileBounds);
     if (!aRegionToPaint.IsEmpty()) {
       break;
     }
-    if (std::abs(scrollDiffY) >= std::abs(scrollDiffX)) {
+    if (Abs(scrollDiffY) >= Abs(scrollDiffX)) {
       tileBounds.x += incX;
     } else {
       tileBounds.y += incY;
     }
   }
 
   if (!aRegionToPaint.Contains(aInvalidRegion)) {
     // The region needed to paint is larger then our progressive chunk size
--- a/gfx/thebes/gfxFont.cpp
+++ b/gfx/thebes/gfxFont.cpp
@@ -1,14 +1,15 @@
 /* -*- 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 "mozilla/DebugOnly.h"
+#include "mozilla/MathAlgorithms.h"
 
 #ifdef MOZ_LOGGING
 #define FORCE_PR_LOG /* Allow logging in the release build */
 #endif
 #include "prlog.h"
 
 #include "nsServiceManagerUtils.h"
 #include "nsReadableUtils.h"
@@ -43,18 +44,16 @@
 #include "gfxFontTest.h"
 
 #include "harfbuzz/hb.h"
 
 #include "nsCRT.h"
 #include "sampler.h"
 
 #include <algorithm>
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 using namespace mozilla;
 using namespace mozilla::gfx;
 using namespace mozilla::unicode;
 using mozilla::services::GetObserverService;
 
 gfxFontCache *gfxFontCache::gGlobalCache = nullptr;
 
@@ -783,17 +782,17 @@ CalcStyleMatch(gfxFontEntry *aFontEntry,
          // italics
          bool wantItalic =
              (aStyle->style & (NS_FONT_STYLE_ITALIC | NS_FONT_STYLE_OBLIQUE)) != 0;
          if (aFontEntry->IsItalic() == wantItalic) {
              rank += 10;
          }
 
         // measure of closeness of weight to the desired value
-        rank += 9 - abs(aFontEntry->Weight() / 100 - aStyle->ComputeWeight());
+        rank += 9 - Abs(aFontEntry->Weight() / 100 - aStyle->ComputeWeight());
     } else {
         // if no font to match, prefer non-bold, non-italic fonts
         if (!aFontEntry->IsItalic()) {
             rank += 3;
         }
         if (!aFontEntry->IsBold()) {
             rank += 2;
         }
@@ -2959,18 +2958,18 @@ gfxFont::InitMetricsFromSfntTables(Metri
     if (NS_SUCCEEDED(mFontEntry->GetFontTable(kOS_2TableTag, os2data))) {
         OS2Table *os2 = reinterpret_cast<OS2Table*>(os2data.Elements());
 
         if (os2data.Length() >= offsetof(OS2Table, sxHeight) +
                                 sizeof(int16_t) &&
             uint16_t(os2->version) >= 2) {
             // version 2 and later includes the x-height field
             SET_SIGNED(xHeight, os2->sxHeight);
-            // std::abs because of negative xHeight seen in Kokonor (Tibetan) font
-            aMetrics.xHeight = std::abs(aMetrics.xHeight);
+            // Abs because of negative xHeight seen in Kokonor (Tibetan) font
+            aMetrics.xHeight = Abs(aMetrics.xHeight);
         }
         // this should always be present
         if (os2data.Length() >= offsetof(OS2Table, yStrikeoutPosition) +
                                 sizeof(int16_t)) {
             SET_SIGNED(aveCharWidth, os2->xAvgCharWidth);
             SET_SIGNED(subscriptOffset, os2->ySubscriptYOffset);
             SET_SIGNED(superscriptOffset, os2->ySuperscriptYOffset);
             SET_SIGNED(strikeoutSize, os2->yStrikeoutSize);
--- a/js/src/ion/RangeAnalysis.cpp
+++ b/js/src/ion/RangeAnalysis.cpp
@@ -1,30 +1,34 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=4 sw=4 et tw=99:
  *
  * 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/MathAlgorithms.h"
+
 #include <math.h>
 #include <stdio.h>
 
 #include "vm/NumericConversions.h"
 
 #include "Ion.h"
 #include "IonAnalysis.h"
 #include "MIR.h"
 #include "MIRGraph.h"
 #include "RangeAnalysis.h"
 #include "IonSpewer.h"
 
 using namespace js;
 using namespace js::ion;
 
+using mozilla::Abs;
+
 // This algorithm is based on the paper "Eliminating Range Checks Using
 // Static Single Assignment Form" by Gough and Klaren.
 //
 // We associate a range object with each SSA name, and the ranges are consulted
 // in order to determine whether overflow is possible for arithmetic
 // computations.
 //
 // An important source of range information that requires care to take
@@ -663,18 +667,17 @@ void
 MAbs::computeRange()
 {
     if (specialization_ != MIRType_Int32 && specialization_ != MIRType_Double)
         return;
 
     Range other(getOperand(0));
 
     Range *range = new Range(0,
-                             Max(Range::abs64((int64_t) other.lower()),
-                                 Range::abs64((int64_t) other.upper())),
+                             Max(Abs<int64_t>(other.lower()), Abs<int64_t>(other.upper())),
                              other.isDecimal(),
                              other.exponent());
     setRange(range);
 }
 
 void
 MAdd::computeRange()
 {
@@ -711,18 +714,18 @@ MMul::computeRange()
 
 void
 MMod::computeRange()
 {
     if (specialization() != MIRType_Int32 && specialization() != MIRType_Double)
         return;
     Range lhs(getOperand(0));
     Range rhs(getOperand(1));
-    int64_t a = Range::abs64((int64_t) rhs.lower());
-    int64_t b = Range::abs64((int64_t) rhs.upper());
+    int64_t a = Abs<int64_t>(rhs.lower());
+    int64_t b = Abs<int64_t>(rhs.upper());
     if (a == 0 && b == 0)
         return;
     int64_t bound = Max(1-a, b-1);
     setRange(new Range(-bound, bound, lhs.isDecimal() || rhs.isDecimal()));
 }
 
 void
 MToDouble::computeRange()
--- a/js/src/ion/RangeAnalysis.h
+++ b/js/src/ion/RangeAnalysis.h
@@ -4,16 +4,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 jsion_range_analysis_h__
 #define jsion_range_analysis_h__
 
 #include "mozilla/FloatingPoint.h"
+#include "mozilla/MathAlgorithms.h"
 
 #include "wtf/Platform.h"
 #include "MIR.h"
 #include "CompileInfo.h"
 #include "IonAnalysis.h"
 
 namespace js {
 namespace ion {
@@ -194,24 +195,16 @@ class Range : public TempObject {
         JS_ASSERT_IF(lower_infinite_, lower_ == JSVAL_INT_MIN);
         JS_ASSERT_IF(upper_infinite_, upper_ == JSVAL_INT_MAX);
     }
 
     Range(const MDefinition *def);
 
     static Range *Truncate(int64_t l, int64_t h);
 
-    static int64_t abs64(int64_t x) {
-#ifdef WTF_OS_WINDOWS
-        return _abs64(x);
-#else
-        return llabs(x);
-#endif
-    }
-
     void print(Sprinter &sp) const;
     bool update(const Range *other);
     bool update(const Range &other) {
         return update(&other);
     }
 
     // Unlike the other operations, unionWith is an in-place
     // modification. This is to avoid a bunch of useless extra
@@ -346,17 +339,18 @@ class Range : public TempObject {
     //     exponent of JSVAL_INT_MIN == 32
     //     exponent of JSVAL_INT_MAX == 31
     inline void rectifyExponent() {
         if (!isInt32()) {
             JS_ASSERT(max_exponent_ >= MaxInt32Exponent);
             return;
         }
 
-        uint32_t max = Max(abs64((int64_t) lower()), abs64((int64_t) upper()));
+        uint32_t max = Max(mozilla::Abs<int64_t>(lower()),
+                           mozilla::Abs<int64_t>(upper()));
         JS_ASSERT_IF(lower() == JSVAL_INT_MIN, max == (uint32_t) JSVAL_INT_MIN);
         JS_ASSERT(max <= (uint32_t) JSVAL_INT_MIN);
         // The number of bits needed to encode |max| is the power of 2 plus one.
         max_exponent_ = max ? js_FloorLog2wImpl(max) : max;
     }
 
     const SymbolicBound *symbolicLower() const {
         return symbolicLower_;
--- a/js/src/ion/arm/Assembler-arm.h
+++ b/js/src/ion/arm/Assembler-arm.h
@@ -3,23 +3,25 @@
  *
  * 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 jsion_cpu_arm_assembler_h__
 #define jsion_cpu_arm_assembler_h__
 
+#include "mozilla/MathAlgorithms.h"
+#include "mozilla/Util.h"
+
 #include "ion/shared/Assembler-shared.h"
 #include "assembler/assembler/AssemblerBufferWithConstantPool.h"
 #include "ion/CompactBuffer.h"
 #include "ion/IonCode.h"
 #include "ion/arm/Architecture-arm.h"
 #include "ion/shared/IonAssemblerBufferWithConstantPools.h"
-#include "mozilla/Util.h"
 
 namespace js {
 namespace ion {
 
 //NOTE: there are duplicates in this list!
 // sometimes we want to specifically refer to the
 // link register as a link register (bl lr is much
 // clearer than bl r14).  HOWEVER, this register can
@@ -698,17 +700,17 @@ class DtrOff
   public:
     uint32_t encode() { return data; }
 };
 
 class DtrOffImm : public DtrOff
 {
   public:
     DtrOffImm(int32_t imm)
-      : DtrOff(datastore::Imm12Data(abs(imm)), imm >= 0 ? IsUp : IsDown)
+      : DtrOff(datastore::Imm12Data(mozilla::Abs(imm)), imm >= 0 ? IsUp : IsDown)
     {
         JS_ASSERT((imm < 4096) && (imm > -4096));
     }
 };
 
 class DtrOffReg : public DtrOff
 {
     // These are designed to be called by a constructor of a subclass.
@@ -783,17 +785,17 @@ class EDtrOff
         return data;
     }
 };
 
 class EDtrOffImm : public EDtrOff
 {
   public:
     EDtrOffImm(int32_t imm)
-      : EDtrOff(datastore::Imm8Data(abs(imm)), (imm >= 0) ? IsUp : IsDown)
+      : EDtrOff(datastore::Imm8Data(mozilla::Abs(imm)), (imm >= 0) ? IsUp : IsDown)
     { }
 };
 
 // this is the most-derived class, since the extended data
 // transfer instructions don't support any sort of modifying the
 // "index" operand
 class EDtrOffReg : public EDtrOff
 {
@@ -831,17 +833,17 @@ class VFPOff
         return data;
     }
 };
 
 class VFPOffImm : public VFPOff
 {
   public:
     VFPOffImm(int32_t imm)
-      : VFPOff(datastore::Imm8VFPOffData(abs(imm) >> 2), imm < 0 ? IsDown : IsUp)
+      : VFPOff(datastore::Imm8VFPOffData(mozilla::Abs(imm) >> 2), imm < 0 ? IsDown : IsUp)
     { }
 };
 class VFPAddr
 {
     friend class Operand;
 
     uint32_t data;
 
--- a/js/src/ion/arm/MacroAssembler-arm.cpp
+++ b/js/src/ion/arm/MacroAssembler-arm.cpp
@@ -1,23 +1,26 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=4 sw=4 et tw=99:
  *
  * 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/DebugOnly.h"
+#include "mozilla/MathAlgorithms.h"
 
 #include "ion/arm/MacroAssembler-arm.h"
 #include "ion/MoveEmitter.h"
 
 using namespace js;
 using namespace ion;
 
+using mozilla::Abs;
+
 bool
 isValueDTRDCandidate(ValueOperand &val)
 {
     // In order to be used for a DTRD memory function, the two target registers
     // need to be a) Adjacent, with the tag larger than the payload, and
     // b) Aligned to a multiple of two.
     if ((val.typeReg().code() != (val.payloadReg().code() + 1)))
         return false;
@@ -2518,17 +2521,17 @@ void
 MacroAssemblerARMCompat::storeValue(ValueOperand val, Operand dst) {
     ma_str(val.payloadReg(), ToPayload(dst));
     ma_str(val.typeReg(), ToType(dst));
 }
 
 void
 MacroAssemblerARMCompat::storeValue(ValueOperand val, const BaseIndex &dest)
 {
-    if (isValueDTRDCandidate(val) && (abs(dest.offset) <= 255)) {
+    if (isValueDTRDCandidate(val) && Abs(dest.offset) <= 255) {
         Register tmpIdx;
         if (dest.offset == 0) {
             if (dest.scale == TimesOne) {
                 tmpIdx = dest.index;
             } else {
                 ma_lsl(Imm32(dest.scale), dest.index, ScratchRegister);
                 tmpIdx = ScratchRegister;
             }
@@ -2542,17 +2545,17 @@ MacroAssemblerARMCompat::storeValue(Valu
         ma_alu(dest.base, lsl(dest.index, dest.scale), ScratchRegister, op_add);
         storeValue(val, Address(ScratchRegister, dest.offset));
     }
 }
 
 void
 MacroAssemblerARMCompat::loadValue(const BaseIndex &addr, ValueOperand val)
 {
-    if (isValueDTRDCandidate(val) && (abs(addr.offset) <= 255)) {
+    if (isValueDTRDCandidate(val) && Abs(addr.offset) <= 255) {
         Register tmpIdx;
         if (addr.offset == 0) {
             if (addr.scale == TimesOne) {
                 tmpIdx = addr.index;
             } else {
                 ma_lsl(Imm32(addr.scale), addr.index, ScratchRegister);
                 tmpIdx = ScratchRegister;
             }
--- a/js/src/jsmath.cpp
+++ b/js/src/jsmath.cpp
@@ -6,16 +6,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /*
  * JS math package.
  */
 
 #include "mozilla/Constants.h"
 #include "mozilla/FloatingPoint.h"
+#include "mozilla/MathAlgorithms.h"
 
 #include <stdlib.h>
 #include "jstypes.h"
 #include "prmjtime.h"
 #include "jsapi.h"
 #include "jsatom.h"
 #include "jscntxt.h"
 #include "jsversion.h"
@@ -25,16 +26,18 @@
 #include "jslibmath.h"
 #include "jscompartment.h"
 
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 
 using namespace js;
 
+using mozilla::Abs;
+
 #ifndef M_E
 #define M_E             2.7182818284590452354
 #endif
 #ifndef M_LOG2E
 #define M_LOG2E         1.4426950408889634074
 #endif
 #ifndef M_LOG10E
 #define M_LOG10E        0.43429448190325182765
@@ -97,17 +100,17 @@ js_math_abs(JSContext *cx, unsigned argc
     double x, z;
 
     if (argc == 0) {
         vp->setDouble(js_NaN);
         return JS_TRUE;
     }
     if (!ToNumber(cx, vp[2], &x))
         return JS_FALSE;
-    z = fabs(x);
+    z = Abs(x);
     vp->setNumber(z);
     return JS_TRUE;
 }
 
 double
 js::math_acos_impl(MathCache *cache, double x)
 {
 #if defined(SOLARIS) && defined(__GNUC__)
--- a/js/src/methodjit/FastArithmetic.cpp
+++ b/js/src/methodjit/FastArithmetic.cpp
@@ -1,27 +1,33 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=4 sw=4 et tw=99:
  *
  * 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/MathAlgorithms.h"
+
 #include "jsbool.h"
 #include "jslibmath.h"
 #include "jsnum.h"
+
 #include "methodjit/MethodJIT.h"
 #include "methodjit/Compiler.h"
 #include "methodjit/StubCalls.h"
 #include "methodjit/FrameState-inl.h"
 
 using namespace js;
 using namespace js::mjit;
 using namespace js::analyze;
 using namespace JSC;
 
+using mozilla::Abs;
+
 typedef JSC::MacroAssembler::FPRegisterID FPRegisterID;
 
 bool
 mjit::Compiler::tryBinaryConstantFold(JSContext *cx, FrameState &frame, JSOp op,
                                       FrameEntry *lhs, FrameEntry *rhs, Value *vp)
 {
     if (!lhs->isConstant() || !rhs->isConstant())
         return false;
@@ -322,17 +328,18 @@ mjit::Compiler::jsop_binary_double(Frame
     /*
      * Try to convert result to integer, if the result has unknown or integer type.
      * Skip this for 1/x or -1/x, as the result is unlikely to fit in an int.
      */
     if (op == JSOP_DIV &&
         (type == JSVAL_TYPE_INT32 ||
          (type == JSVAL_TYPE_UNKNOWN &&
           !(lhs->isConstant() && lhs->isType(JSVAL_TYPE_INT32) &&
-            abs(lhs->getValue().toInt32()) == 1)))) {
+            Abs(lhs->getValue().toInt32()) == 1))))
+    {
         RegisterID reg = frame.allocReg();
         FPRegisterID fpReg = frame.allocFPReg();
         JumpList isDouble;
         masm.branchConvertDoubleToInt32(fpLeft, reg, isDouble, fpReg);
 
         masm.storeValueFromComponents(ImmType(JSVAL_TYPE_INT32), reg,
                                       frame.addressOf(lhs));
 
--- a/js/src/methodjit/LoopState.cpp
+++ b/js/src/methodjit/LoopState.cpp
@@ -1,27 +1,31 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=4 sw=4 et tw=99:
  *
  * 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/MathAlgorithms.h"
+
 #include "methodjit/Compiler.h"
 #include "methodjit/LoopState.h"
 #include "methodjit/FrameState-inl.h"
 #include "methodjit/StubCalls.h"
 
 #include "jstypedarrayinlines.h"
 
 using namespace js;
 using namespace js::mjit;
 using namespace js::analyze;
 using namespace js::types;
 
+using mozilla::Abs;
+
 LoopState::LoopState(JSContext *cx, analyze::CrossScriptSSA *ssa,
                      mjit::Compiler *cc, FrameState *frame)
     : cx(cx), ssa(ssa),
       outerScript(ssa->outerScript()), outerAnalysis(outerScript->analysis()),
       cc(*cc), frame(*frame),
       lifetime(NULL), alloc(NULL), reachedEntryPoint(false), loopRegs(0), skipAnalysis(false),
       loopJoins(CompilerAllocPolicy(cx, *cc)),
       loopPatches(CompilerAllocPolicy(cx, *cc)),
@@ -2020,17 +2024,17 @@ LoopState::computeInterval(const CrossSS
       }
 
       case JSOP_MOD: {
         int32_t rhsmin, rhsmax;
         CrossSSAValue rhsv(cv.frame, analysis->poppedValue(pc, 0));
         if (!computeInterval(rhsv, &rhsmin, &rhsmax) || rhsmin != rhsmax)
             return false;
 
-        int32_t rhs = abs(rhsmax);
+        int32_t rhs = Abs(rhsmax);
         *pmin = -(rhs - 1);
         *pmax = rhs - 1;
         return true;
       }
 
       case JSOP_ADD: {
         int32_t lhsmin, lhsmax, rhsmin, rhsmax;
         CrossSSAValue lhsv(cv.frame, analysis->poppedValue(pc, 1));
@@ -2050,18 +2054,18 @@ LoopState::computeInterval(const CrossSS
       }
 
       case JSOP_MUL: {
         int32_t lhsmin, lhsmax, rhsmin, rhsmax;
         CrossSSAValue lhsv(cv.frame, analysis->poppedValue(pc, 1));
         CrossSSAValue rhsv(cv.frame, analysis->poppedValue(pc, 0));
         if (!computeInterval(lhsv, &lhsmin, &lhsmax) || !computeInterval(rhsv, &rhsmin, &rhsmax))
             return false;
-        int32_t nlhs = Max(abs(lhsmin), abs(lhsmax));
-        int32_t nrhs = Max(abs(rhsmin), abs(rhsmax));
+        int32_t nlhs = Max(Abs(lhsmin), Abs(lhsmax));
+        int32_t nrhs = Max(Abs(rhsmin), Abs(rhsmax));
 
         if (!SafeMul(nlhs, nrhs, pmax))
             return false;
 
         if (lhsmin < 0 || rhsmin < 0) {
             /* pmax is nonnegative, so can be negated without overflow. */
             *pmin = -*pmax;
         } else {
--- a/js/src/prmjtime.cpp
+++ b/js/src/prmjtime.cpp
@@ -1,17 +1,18 @@
 /* -*- Mode: C++; tab-width: 8; 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/. */
 
-/*
- * PR time code.
- */
+/* PR time code. */
+
+#include "mozilla/MathAlgorithms.h"
+
 #ifdef SOLARIS
 #define _REENTRANT 1
 #endif
 #include <string.h>
 #include <time.h>
 
 #include "jstypes.h"
 #include "jsutil.h"
@@ -23,17 +24,16 @@
 #define PRMJ_DO_MILLISECONDS 1
 
 #ifdef XP_OS2
 #include <sys/timeb.h>
 #endif
 #ifdef XP_WIN
 #include <windef.h>
 #include <winbase.h>
-#include <math.h>     /* for fabs */
 #include <mmsystem.h> /* for timeBegin/EndPeriod */
 /* VC++ 8.0 or later */
 #if _MSC_VER >= 1400
 #define NS_HAVE_INVALID_PARAMETER_HANDLER 1
 #endif
 #ifdef NS_HAVE_INVALID_PARAMETER_HANDLER
 #include <stdlib.h>   /* for _set_invalid_parameter_handler */
 #include <crtdbg.h>   /* for _CrtSetReportMode */
@@ -353,17 +353,17 @@ PRMJ_Now(void)
             /* Check for clock skew */
             diff = lowresTime - highresTime;
 
             /* For some reason that I have not determined, the skew can be
                up to twice a kernel tick. This does not seem to happen by
                itself, but I have only seen it triggered by another program
                doing some kind of file I/O. The symptoms are a negative diff
                followed by an equally large positive diff. */
-            if (fabs(diff) > 2*skewThreshold) {
+            if (mozilla::Abs(diff) > 2 * skewThreshold) {
                 /*fprintf(stderr,"Clock skew detected (diff = %f)!\n", diff);*/
 
                 if (calibrated) {
                     /* If we already calibrated once this instance, and the
                        clock is still skewed, then either the processor(s) are
                        wildly changing clockspeed or the system is so busy that
                        we get switched out for long periods of time. In either
                        case, it would be infeasible to make use of high
--- a/js/src/vm/DateTime.h
+++ b/js/src/vm/DateTime.h
@@ -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/. */
 
 #ifndef DateTime_h___
 #define DateTime_h___
 
 #include "mozilla/FloatingPoint.h"
+#include "mozilla/MathAlgorithms.h"
 #include "mozilla/StandardInteger.h"
 
 #include <math.h>
 
 #include "NumericConversions.h"
 
 namespace js {
 
@@ -36,17 +37,17 @@ const double msPerDay = msPerHour * Hour
 const unsigned SecondsPerHour = 60 * 60;
 const unsigned SecondsPerDay = SecondsPerHour * 24;
 
 /* ES5 15.9.1.14. */
 inline double
 TimeClip(double time)
 {
     /* Steps 1-2. */
-    if (!MOZ_DOUBLE_IS_FINITE(time) || fabs(time) > 8.64e15)
+    if (!MOZ_DOUBLE_IS_FINITE(time) || mozilla::Abs(time) > 8.64e15)
         return js_NaN;
 
     /* Step 3. */
     return ToInteger(time + (+0.0));
 }
 
 /*
  * Stores date/time information, particularly concerning the current local
--- a/layout/base/nsCSSColorUtils.h
+++ b/layout/base/nsCSSColorUtils.h
@@ -3,26 +3,26 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* functions that manipulate colors */
 
 #ifndef __nsCSSColorUtils_h
 #define __nsCSSColorUtils_h
 
+#include "mozilla/MathAlgorithms.h"
+
 #include "nsColor.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 // "Sufficient contrast" is determined by
 // "Techniques For Accessibility Evalution And Repair Tools".
 // See http://www.w3.org/TR/AERT#color-contrast
 #define NS_SUFFICIENT_LUMINOSITY_DIFFERENCE 125000
 #define NS_LUMINOSITY_DIFFERENCE(a, b) \
-          std::abs(NS_GetLuminosity(a) - NS_GetLuminosity(b))
+          mozilla::Abs(NS_GetLuminosity(a) - NS_GetLuminosity(b))
 
 // To determine colors based on the background brightness and border color
 void NS_GetSpecial3DColors(nscolor aResult[2],
                            nscolor aBackgroundColor,
                            nscolor aBorderColor);
 
 // Determins brightness for a specific color
 int NS_GetBrightness(uint8_t aRed, uint8_t aGreen, uint8_t aBlue);
--- a/layout/base/nsCSSRendering.cpp
+++ b/layout/base/nsCSSRendering.cpp
@@ -1,22 +1,21 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 // vim:cindent:ts=2:et: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/. */
 
 /* utility functions for drawing borders and backgrounds */
 
-#include <cmath> // for std::abs(float/double)
-#include <cstdlib> // for std::abs(int/long)
 #include <ctime>
 
 #include "mozilla/DebugOnly.h"
 #include "mozilla/HashFunctions.h"
+#include "mozilla/MathAlgorithms.h"
 #include "mozilla/Types.h"
 
 #include "nsStyleConsts.h"
 #include "nsPresContext.h"
 #include "nsIFrame.h"
 #include "nsPoint.h"
 #include "nsRect.h"
 #include "nsViewManager.h"
@@ -1981,20 +1980,20 @@ ComputeRadialGradientLine(nsPresContext*
       ConvertGradientValueToPixels(aGradient->mBgPosX, aBoxSize.width,
                                    appUnitsPerPixel),
       ConvertGradientValueToPixels(aGradient->mBgPosY, aBoxSize.height,
                                    appUnitsPerPixel));
   }
 
   // Compute gradient shape: the x and y radii of an ellipse.
   double radiusX, radiusY;
-  double leftDistance = std::abs(aLineStart->x);
-  double rightDistance = std::abs(aBoxSize.width - aLineStart->x);
-  double topDistance = std::abs(aLineStart->y);
-  double bottomDistance = std::abs(aBoxSize.height - aLineStart->y);
+  double leftDistance = Abs(aLineStart->x);
+  double rightDistance = Abs(aBoxSize.width - aLineStart->x);
+  double topDistance = Abs(aLineStart->y);
+  double bottomDistance = Abs(aBoxSize.height - aLineStart->y);
   switch (aGradient->mSize) {
   case NS_STYLE_GRADIENT_SIZE_CLOSEST_SIDE:
     radiusX = std::min(leftDistance, rightDistance);
     radiusY = std::min(topDistance, bottomDistance);
     if (aGradient->mShape == NS_STYLE_GRADIENT_SHAPE_CIRCULAR) {
       radiusX = radiusY = std::min(radiusX, radiusY);
     }
     break;
--- a/layout/generic/nsTextFrameThebes.cpp
+++ b/layout/generic/nsTextFrameThebes.cpp
@@ -2,22 +2,20 @@
 /* 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/. */
 
 /* rendering object for textual content of elements */
 
 #include "nsTextFrame.h"
 
-#include <cmath> // for std::abs(float/double)
-#include <cstdlib> // for std::abs(int/long)
-
 #include "mozilla/Attributes.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Likely.h"
+#include "mozilla/MathAlgorithms.h"
 
 #include "nsCOMPtr.h"
 #include "nsBlockFrame.h"
 #include "nsHTMLParts.h"
 #include "nsCRT.h"
 #include "nsSplittableFrame.h"
 #include "nsLineLayout.h"
 #include "nsString.h"
@@ -5643,17 +5641,17 @@ nsTextFrame::PaintTextSelectionDecoratio
   nsTextRangeStyle selectedStyle;
   while (iterator.GetNextSegment(&xOffset, &offset, &length, &hyphenWidth,
                                  &type, &selectedStyle)) {
     gfxFloat advance = hyphenWidth +
       mTextRun->GetAdvanceWidth(offset, length, &aProvider);
     if (type == aSelectionType) {
       pt.x = (aFramePt.x + xOffset -
              (mTextRun->IsRightToLeft() ? advance : 0)) / app;
-      gfxFloat width = std::abs(advance) / app;
+      gfxFloat width = Abs(advance) / app;
       gfxFloat xInFrame = pt.x - (aFramePt.x / app);
       DrawSelectionDecorations(aCtx, dirtyRect, aSelectionType, this,
                                aTextPaintStyle, selectedStyle, pt, xInFrame,
                                width, mAscent / app, decorationMetrics,
                                aCallbacks);
     }
     iterator.UpdateWithAdvance(advance);
   }
--- a/layout/mathml/nsMathMLChar.cpp
+++ b/layout/mathml/nsMathMLChar.cpp
@@ -1,13 +1,15 @@
 /* -*- 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/MathAlgorithms.h"
+
 #include "nsCOMPtr.h"
 #include "nsFrame.h"
 #include "nsPresContext.h"
 #include "nsStyleContext.h"
 #include "nsStyleConsts.h"
 #include "nsString.h"
 #include "nsUnicharUtils.h"
 #include "nsRenderingContext.h"
@@ -25,18 +27,16 @@
 #include "mozilla/LookAndFeel.h"
 #include "nsCSSRendering.h"
 #include "prprf.h"         // For PR_snprintf()
 
 #include "nsDisplayList.h"
 
 #include "nsMathMLOperators.h"
 #include "nsMathMLChar.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 #include <algorithm>
 
 using namespace mozilla;
 
 //#define NOISY_SEARCH 1
 
 // -----------------------------------------------------------------------------
 static const PRUnichar   kSpaceCh   = PRUnichar(' ');
@@ -742,27 +742,27 @@ static bool
 IsSizeOK(nsPresContext* aPresContext, nscoord a, nscoord b, uint32_t aHint)
 {
   // Normal: True if 'a' is around +/-10% of the target 'b' (10% is
   // 1-DelimiterFactor). This often gives a chance to the base size to
   // win, especially in the context of <mfenced> without tall elements
   // or in sloppy markups without protective <mrow></mrow>
   bool isNormal =
     (aHint & NS_STRETCH_NORMAL)
-    && bool(float(std::abs(a - b))
+    && bool(float(Abs(a - b))
               < (1.0f - NS_MATHML_DELIMITER_FACTOR) * float(b));
   // Nearer: True if 'a' is around max{ +/-10% of 'b' , 'b' - 5pt },
   // as documented in The TeXbook, Ch.17, p.152.
   // i.e. within 10% and within 5pt
   bool isNearer = false;
   if (aHint & (NS_STRETCH_NEARER | NS_STRETCH_LARGEOP)) {
     float c = std::max(float(b) * NS_MATHML_DELIMITER_FACTOR,
                      float(b) - nsPresContext::
                      CSSPointsToAppUnits(NS_MATHML_DELIMITER_SHORTFALL_POINTS));
-    isNearer = bool(float(std::abs(b - a)) <= (float(b) - c));
+    isNearer = bool(float(Abs(b - a)) <= (float(b) - c));
   }
   // Smaller: Mainly for transitory use, to compare two candidate
   // choices
   bool isSmaller =
     (aHint & NS_STRETCH_SMALLER)
     && bool((float(a) >= (NS_MATHML_DELIMITER_FACTOR * float(b)))
               && (a <= b));
   // Larger: Critical to the sqrt code to ensure that the radical
@@ -779,17 +779,17 @@ IsSizeBetter(nscoord a, nscoord olda, ns
   if (0 == olda)
     return true;
   if (aHint & (NS_STRETCH_LARGER | NS_STRETCH_LARGEOP))
     return (a >= olda) ? (olda < b) : (a >= b);
   if (aHint & NS_STRETCH_SMALLER)
     return (a <= olda) ? (olda > b) : (a <= b);
 
   // XXXkt prob want log scale here i.e. 1.5 is closer to 1 than 0.5
-  return std::abs(a - b) < std::abs(olda - b);
+  return Abs(a - b) < Abs(olda - b);
 }
 
 // We want to place the glyphs even when they don't fit at their
 // full extent, i.e., we may clip to tolerate a small amount of
 // overlap between the parts. This is important to cater for fonts
 // with long glues.
 static nscoord
 ComputeSizeFromParts(nsPresContext* aPresContext,
--- a/layout/style/nsStyleAnimation.cpp
+++ b/layout/style/nsStyleAnimation.cpp
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* Utilities for animation of computed style values */
 
+#include "mozilla/MathAlgorithms.h"
 #include "mozilla/Util.h"
-#include "mozilla/MathAlgorithms.h"
 
 #include "nsStyleAnimation.h"
 #include "nsStyleTransformMatrix.h"
 #include "nsCOMArray.h"
 #include "nsIStyleRule.h"
 #include "mozilla/css/StyleRule.h"
 #include "nsString.h"
 #include "nsStyleContext.h"
@@ -19,18 +19,16 @@
 #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 "gfxMatrix.h"
 #include "gfxQuaternion.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 using namespace mozilla;
 
 // HELPER METHODS
 // --------------
 /*
  * Given two units, this method returns a common unit that they can both be
  * converted into, if possible.  This is intended to facilitate
@@ -378,17 +376,17 @@ nsStyleAnimation::ComputeDistance(nsCSSP
       return false;
 
     case eUnit_Enumerated:
       switch (aProperty) {
         case eCSSProperty_font_stretch: {
           // just like eUnit_Integer.
           int32_t startInt = aStartValue.GetIntValue();
           int32_t endInt = aEndValue.GetIntValue();
-          aDistance = std::abs(endInt - startInt);
+          aDistance = Abs(endInt - startInt);
           return true;
         }
         default:
           return false;
       }
    case eUnit_Visibility: {
       int32_t startEnum = aStartValue.GetIntValue();
       int32_t endEnum = aEndValue.GetIntValue();
@@ -401,29 +399,29 @@ nsStyleAnimation::ComputeDistance(nsCSSP
         return false;
       }
       aDistance = 1;
       return true;
     }
     case eUnit_Integer: {
       int32_t startInt = aStartValue.GetIntValue();
       int32_t endInt = aEndValue.GetIntValue();
-      aDistance = std::abs(endInt - startInt);
+      aDistance = Abs(endInt - startInt);
       return true;
     }
     case eUnit_Coord: {
       nscoord startCoord = aStartValue.GetCoordValue();
       nscoord endCoord = aEndValue.GetCoordValue();
-      aDistance = fabs(double(endCoord - startCoord));
+      aDistance = Abs<double>(endCoord - startCoord);
       return true;
     }
     case eUnit_Percent: {
       float startPct = aStartValue.GetPercentValue();
       float endPct = aEndValue.GetPercentValue();
-      aDistance = fabs(double(endPct - startPct));
+      aDistance = Abs<double>(endPct - startPct);
       return true;
     }
     case eUnit_Float: {
 #ifdef MOZ_FLEXBOX
       // Special case for flex-grow and flex-shrink: animations are
       // disallowed between 0 and other values.
       if ((aProperty == eCSSProperty_flex_grow ||
            aProperty == eCSSProperty_flex_shrink) &&
@@ -431,17 +429,17 @@ nsStyleAnimation::ComputeDistance(nsCSSP
            aEndValue.GetFloatValue() == 0.0f) &&
           aStartValue.GetFloatValue() != aEndValue.GetFloatValue()) {
         return false;
       }
 #endif // MOZ_FLEXBOX
 
       float startFloat = aStartValue.GetFloatValue();
       float endFloat = aEndValue.GetFloatValue();
-      aDistance = fabs(double(endFloat - startFloat));
+      aDistance = Abs<double>(endFloat - startFloat);
       return true;
     }
     case eUnit_Color: {
       // http://www.w3.org/TR/smil-animation/#animateColorElement says
       // that we should use Euclidean RGB cube distance.  However, we
       // have to extend that to RGBA.  For now, we'll just use the
       // Euclidean distance in the (part of the) 4-cube of premultiplied
       // colors.
@@ -1294,17 +1292,17 @@ Decompose2DMatrix(const gfxMatrix &aMatr
   D -= B * XYshear;
 
   float scaleY = sqrt(C * C + D * D);
   C /= scaleY;
   D /= scaleY;
   XYshear /= scaleY;
 
   // A*D - B*C should now be 1 or -1
-  NS_ASSERTION(0.99 < std::abs(A*D - B*C) && std::abs(A*D - B*C) < 1.01,
+  NS_ASSERTION(0.99 < Abs(A*D - B*C) && Abs(A*D - B*C) < 1.01,
                "determinant should now be 1 or -1");
   if (A * D < B * C) {
     A = -A;
     B = -B;
     C = -C;
     D = -D;
     XYshear = -XYshear;
     scaleX = -scaleX;
--- a/layout/tables/nsTableFrame.cpp
+++ b/layout/tables/nsTableFrame.cpp
@@ -1,13 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 sw=2 et 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 "mozilla/Likely.h"
+#include "mozilla/MathAlgorithms.h"
+
 #include "nsCOMPtr.h"
 #include "nsTableFrame.h"
 #include "nsRenderingContext.h"
 #include "nsStyleContext.h"
 #include "nsStyleConsts.h"
 #include "nsIContent.h"
 #include "nsCellMap.h"
 #include "nsTableCellFrame.h"
@@ -33,19 +37,16 @@
 #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"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 #include <algorithm>
 
 using namespace mozilla;
 using namespace mozilla::layout;
 
 /********************************************************************************
  ** nsTableReflowState                                                         **
  ********************************************************************************/
@@ -6241,17 +6242,17 @@ BCPaintBorderIterator::SetDamageArea(con
       if (!colFrame) ABORT1(false);
       nsSize size = colFrame->GetSize();
       mInitialOffsetX += mColInc * size.width;
     }
   }
   if (!haveIntersect)
     return false;
   mDamageArea = nsIntRect(startColIndex, startRowIndex,
-                          1 + std::abs(int32_t(endColIndex - startColIndex)),
+                          1 + Abs<int32_t>(endColIndex - startColIndex),
                           1 + endRowIndex - startRowIndex);
 
   Reset();
   mVerInfo = new BCVerticalSeg[mDamageArea.width + 1];
   if (!mVerInfo)
     return false;
   return true;
 }
--- a/layout/xul/tree/nsTreeBodyFrame.cpp
+++ b/layout/xul/tree/nsTreeBodyFrame.cpp
@@ -1,17 +1,15 @@
 /* -*- 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 <cmath> // for std::abs(float/double)
-#include <cstdlib> // for std::abs(int/long)
-
 #include "mozilla/DebugOnly.h"
+#include "mozilla/MathAlgorithms.h"
 #include "mozilla/Likely.h"
 
 #include "nsCOMPtr.h"
 #include "nsISupportsArray.h"
 #include "nsPresContext.h"
 #include "nsINameSpaceManager.h"
 
 #include "nsTreeBodyFrame.h"
@@ -1825,17 +1823,17 @@ nsTreeBodyFrame::RowCountChanged(int32_t
 
   mRowCount += aCount;
 #ifdef DEBUG
   int32_t rowCount = mRowCount;
   mView->GetRowCount(&rowCount);
   NS_ASSERTION(rowCount == mRowCount, "row count did not change by the amount suggested, check caller");
 #endif
 
-  int32_t count = std::abs(aCount);
+  int32_t count = Abs(aCount);
   int32_t last = GetLastVisibleRow();
   if (aIndex >= mTopRowIndex && aIndex <= last)
     InvalidateRange(aIndex, last);
     
   ScrollParts parts = GetScrollParts();
 
   if (mTopRowIndex == 0) {    
     // Just update the scrollbar and return.
--- a/mfbt/MathAlgorithms.h
+++ b/mfbt/MathAlgorithms.h
@@ -4,16 +4,21 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* mfbt maths algorithms. */
 
 #ifndef mozilla_MathAlgorithms_h_
 #define mozilla_MathAlgorithms_h_
 
 #include "mozilla/Assertions.h"
+#include "mozilla/StandardInteger.h"
+#include "mozilla/TypeTraits.h"
+
+#include <limits.h>
+#include <math.h>
 
 namespace mozilla {
 
 // Greatest Common Divisor
 template<typename IntegerType>
 MOZ_ALWAYS_INLINE IntegerType
 EuclidGCD(IntegerType a, IntegerType b)
 {
@@ -37,11 +42,80 @@ EuclidGCD(IntegerType a, IntegerType b)
 template<typename IntegerType>
 MOZ_ALWAYS_INLINE IntegerType
 EuclidLCM(IntegerType a, IntegerType b)
 {
   // Divide first to reduce overflow risk.
   return (a / EuclidGCD(a, b)) * b;
 }
 
+namespace detail {
+
+// For now mozilla::Abs only takes intN_T, the signed natural types, and
+// float/double/long double.  Feel free to add overloads for other standard,
+// signed types if you need them.
+
+template<typename T>
+struct SupportedForAbsFixed : FalseType {};
+
+template<> struct SupportedForAbsFixed<int8_t> : TrueType {};
+template<> struct SupportedForAbsFixed<int16_t> : TrueType {};
+template<> struct SupportedForAbsFixed<int32_t> : TrueType {};
+template<> struct SupportedForAbsFixed<int64_t> : TrueType {};
+
+template<typename T>
+struct SupportedForAbs : SupportedForAbsFixed<T> {};
+
+template<> struct SupportedForAbs<char> : IntegralConstant<bool, char(-1) < char(0)> {};
+template<> struct SupportedForAbs<signed char> : TrueType {};
+template<> struct SupportedForAbs<short> : TrueType {};
+template<> struct SupportedForAbs<int> : TrueType {};
+template<> struct SupportedForAbs<long> : TrueType {};
+template<> struct SupportedForAbs<long long> : TrueType {};
+template<> struct SupportedForAbs<float> : TrueType {};
+template<> struct SupportedForAbs<double> : TrueType {};
+template<> struct SupportedForAbs<long double> : TrueType {};
+
+} // namespace detail
+
+template<typename T>
+inline typename mozilla::EnableIf<detail::SupportedForAbs<T>::value, T>::Type
+Abs(const T t)
+{
+  // The absolute value of the smallest possible value of a signed-integer type
+  // won't fit in that type (on twos-complement systems -- and we're blithely
+  // assuming we're on such systems, for the non-<stdint.h> types listed above),
+  // so assert that the input isn't that value.
+  //
+  // This is the case if: the value is non-negative; or if adding one (giving a
+  // value in the range [-maxvalue, 0]), then negating (giving a value in the
+  // range [0, maxvalue]), doesn't produce maxvalue (because in twos-complement,
+  // (minvalue + 1) == -maxvalue).
+  MOZ_ASSERT(t >= 0 ||
+             -(t + 1) != T((1ULL << (CHAR_BIT * sizeof(T) - 1)) - 1),
+             "You can't negate the smallest possible negative integer!");
+  return t >= 0 ? t : -t;
+}
+
+template<>
+inline float
+Abs<float>(const float f)
+{
+  return fabsf(f);
+}
+
+template<>
+inline double
+Abs<double>(const double d)
+{
+  return fabs(d);
+}
+
+template<>
+inline long double
+Abs<long double>(const long double d)
+{
+  return fabsl(d);
+}
+
 } /* namespace mozilla */
 
 #endif  /* mozilla_MathAlgorithms_h_ */
--- a/widget/gtk2/nsNativeKeyBindings.cpp
+++ b/widget/gtk2/nsNativeKeyBindings.cpp
@@ -1,26 +1,25 @@
 /* -*- 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/MathAlgorithms.h"
 #include "mozilla/Util.h"
 
 #include "nsNativeKeyBindings.h"
 #include "nsString.h"
 #include "nsMemory.h"
 #include "nsGtkKeyUtils.h"
 #include "nsGUIEvent.h"
 
 #include <gtk/gtk.h>
 #include <gdk/gdkkeysyms.h>
 #include <gdk/gdk.h>
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 using namespace mozilla;
 using namespace mozilla::widget;
 
 static nsINativeKeyBindings::DoCommandCallback gCurrentCallback;
 static void *gCurrentCallbackData;
 static bool gHandled;
 
@@ -95,17 +94,17 @@ delete_from_cursor_cb(GtkWidget *w, GtkD
       gCurrentCallback("cmd_endLine", gCurrentCallbackData);
     }
   }
 
   const char *cmd = sDeleteCommands[del_type][forward];
   if (!cmd)
     return; // unsupported command
 
-  count = std::abs(count);
+  count = Abs(count);
   for (int i = 0; i < count; ++i) {
     gCurrentCallback(cmd, gCurrentCallbackData);
   }
 }
 
 static const char *const sMoveCommands[][2][2] = {
   // non-extend { backward, forward }, extend { backward, forward }
   // GTK differentiates between logical position, which is prev/next,
@@ -165,17 +164,17 @@ move_cursor_cb(GtkWidget *w, GtkMovement
     return;
   }
 
   const char *cmd = sMoveCommands[step][extend_selection][forward];
   if (!cmd)
     return; // unsupported command
 
   
-  count = std::abs(count);
+  count = Abs(count);
   for (int i = 0; i < count; ++i) {
     gCurrentCallback(cmd, gCurrentCallbackData);
   }
 }
 
 static void
 paste_clipboard_cb(GtkWidget *w, gpointer user_data)
 {
--- a/widget/nsGUIEvent.h
+++ b/widget/nsGUIEvent.h
@@ -1,16 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsGUIEvent_h__
 #define nsGUIEvent_h__
 
+#include "mozilla/MathAlgorithms.h"
+
 #include "nsCOMArray.h"
 #include "nsPoint.h"
 #include "nsRect.h"
 #include "nsRegion.h"
 #include "nsEvent.h"
 #include "nsStringGlue.h"
 #include "nsCOMPtr.h"
 #include "nsIAtom.h"
@@ -23,18 +25,16 @@
 #include "nsWeakPtr.h"
 #include "nsIWidget.h"
 #include "nsTArray.h"
 #include "nsTraceRefcnt.h"
 #include "nsITransferable.h"
 #include "nsIVariant.h"
 #include "nsStyleConsts.h"
 #include "nsAutoPtr.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 namespace mozilla {
 namespace dom {
   class PBrowserParent;
   class PBrowserChild;
 }
 namespace plugins {
   class PPluginInstanceChild;
@@ -1337,17 +1337,17 @@ public:
     }
     if (lineOrPageDeltaX && !lineOrPageDeltaY) {
       return lineOrPageDeltaX;
     }
     if ((lineOrPageDeltaX < 0 && lineOrPageDeltaY > 0) ||
         (lineOrPageDeltaX > 0 && lineOrPageDeltaY < 0)) {
       return 0; // We cannot guess the answer in this case.
     }
-    return (std::abs(lineOrPageDeltaX) > std::abs(lineOrPageDeltaY)) ?
+    return (Abs(lineOrPageDeltaX) > Abs(lineOrPageDeltaY)) ?
              lineOrPageDeltaX : lineOrPageDeltaY;
   }
 
   // Scroll type
   // The default value is SCROLL_DEFAULT, which means nsEventStateManager will
   // select preferred scroll type automatically.
   enum ScrollType {
     SCROLL_DEFAULT,
--- a/widget/windows/nsWindow.cpp
+++ b/widget/windows/nsWindow.cpp
@@ -49,22 +49,22 @@
  **
  ** BLOCK: Includes
  **
  ** Include headers.
  **
  **************************************************************
  **************************************************************/
 
+#include "mozilla/MathAlgorithms.h"
+#include "mozilla/Util.h"
+
 #include "mozilla/ipc/RPCChannel.h"
 #include <algorithm>
 
-/* This must occur *after* ipc/RPCChannel.h to avoid typedefs conflicts. */
-#include "mozilla/Util.h"
-
 #include "nsWindow.h"
 
 #include <shellapi.h>
 #include <windows.h>
 #include <process.h>
 #include <commctrl.h>
 #include <unknwn.h>
 #include <psapi.h>
@@ -114,18 +114,16 @@
 #include "nsPrintfCString.h"
 #include "mozilla/Preferences.h"
 #include "nsISound.h"
 #include "WinTaskbar.h"
 #include "WinUtils.h"
 #include "WidgetUtils.h"
 #include "nsIWidgetListener.h"
 #include "nsDOMTouchEvent.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 #ifdef MOZ_ENABLE_D3D9_LAYER
 #include "LayerManagerD3D9.h"
 #endif
 
 #ifdef MOZ_ENABLE_D3D10_LAYER
 #include "LayerManagerD3D10.h"
 #endif
@@ -3431,17 +3429,17 @@ NS_IMETHODIMP
 nsWindow::OverrideSystemMouseScrollSpeed(int32_t aOriginalDelta,
                                          bool aIsHorizontal,
                                          int32_t &aOverriddenDelta)
 {
   // The default vertical and horizontal scrolling speed is 3, this is defined
   // on the document of SystemParametersInfo in MSDN.
   const uint32_t kSystemDefaultScrollingSpeed = 3;
 
-  int32_t absOriginDelta = std::abs(aOriginalDelta);
+  int32_t absOriginDelta = Abs(aOriginalDelta);
 
   // Compute the simple overridden speed.
   int32_t absComputedOverriddenDelta;
   nsresult rv =
     nsBaseWidget::OverrideSystemMouseScrollSpeed(absOriginDelta, aIsHorizontal,
                                                  absComputedOverriddenDelta);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -3859,18 +3857,18 @@ bool nsWindow::DispatchMouseEvent(uint32
   if (aEventType == NS_MOUSE_MOVE) 
   {
     if ((sLastMouseMovePoint.x == mpScreen.x) && (sLastMouseMovePoint.y == mpScreen.y))
       return result;
     sLastMouseMovePoint.x = mpScreen.x;
     sLastMouseMovePoint.y = mpScreen.y;
   }
 
-  bool insideMovementThreshold = (abs(sLastMousePoint.x - eventPoint.x) < (short)::GetSystemMetrics(SM_CXDOUBLECLK)) &&
-                                   (abs(sLastMousePoint.y - eventPoint.y) < (short)::GetSystemMetrics(SM_CYDOUBLECLK));
+  bool insideMovementThreshold = (Abs(sLastMousePoint.x - eventPoint.x) < (short)::GetSystemMetrics(SM_CXDOUBLECLK)) &&
+                                   (Abs(sLastMousePoint.y - eventPoint.y) < (short)::GetSystemMetrics(SM_CYDOUBLECLK));
 
   BYTE eventButton;
   switch (aButton) {
     case nsMouseEvent::eLeftButton:
       eventButton = VK_LBUTTON;
       break;
     case nsMouseEvent::eMiddleButton:
       eventButton = VK_MBUTTON;
@@ -6390,20 +6388,20 @@ bool nsWindow::OnGesture(WPARAM wParam, 
     bool endFeedback = true;
 
     if (mGesture.PanDeltaToPixelScroll(wheelEvent)) {
       DispatchEvent(&wheelEvent, status);
     }
 
     if (mDisplayPanFeedback) {
       mGesture.UpdatePanFeedbackX(mWnd,
-                                  std::abs(RoundDown(wheelEvent.overflowDeltaX)),
+                                  Abs(RoundDown(wheelEvent.overflowDeltaX)),
                                   endFeedback);
       mGesture.UpdatePanFeedbackY(mWnd,
-                                  std::abs(RoundDown(wheelEvent.overflowDeltaY)),
+                                  Abs(RoundDown(wheelEvent.overflowDeltaY)),
                                   endFeedback);
       mGesture.PanFeedbackFinalize(mWnd, endFeedback);
     }
 
     mGesture.CloseGestureInfoHandle((HGESTUREINFO)lParam);
 
     return true;
   }
--- a/xpcom/ds/TimeStamp_windows.cpp
+++ b/xpcom/ds/TimeStamp_windows.cpp
@@ -6,23 +6,23 @@
 
 // Implement TimeStamp::Now() with QueryPerformanceCounter() controlled with
 // values of GetTickCount().
 
 // XXX Forcing log to be able to catch issues in the field.  Should be removed
 // before this reaches the Release or even Beta channel.
 #define FORCE_PR_LOG
 
+#include "mozilla/MathAlgorithms.h"
+#include "mozilla/Mutex.h"
 #include "mozilla/TimeStamp.h"
-#include "mozilla/Mutex.h"
 #include <windows.h>
 
 #include "prlog.h"
 #include <stdio.h>
-#include <cstdlib> // for std::abs(int/long)
 
 #include <intrin.h>
 
 #if defined(PR_LOGGING)
 // Log module for mozilla::TimeStamp for Windows logging...
 //
 // To enable logging (see prlog.h for full details):
 //
@@ -351,17 +351,17 @@ TimeStampValue::CheckQPC(int64_t aDurati
 
   if (sHasStableTSC) // For stable TSC there is no need to check
     return true;
 
   if (!sUseQPC) // QPC globally disabled
     return false;
 
   // Treat absolutely for calibration purposes
-  aDuration = std::abs(aDuration);
+  aDuration = Abs(aDuration);
 
   // Check QPC is sane before using it.
 
   LONGLONG skew1 = mGTC - mQPC;
   LONGLONG skew2 = aOther.mGTC - aOther.mQPC;
 
   LONGLONG diff = skew1 - skew2;
   LONGLONG overflow;
--- a/xpcom/io/nsMultiplexInputStream.cpp
+++ b/xpcom/io/nsMultiplexInputStream.cpp
@@ -3,32 +3,34 @@
  * 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/. */
 
 /**
  * The multiplex stream concatenates a list of input streams into a single
  * stream.
  */
 
+#include "mozilla/Attributes.h"
+#include "mozilla/MathAlgorithms.h"
+
 #include "base/basictypes.h"
 
 #include "nsMultiplexInputStream.h"
-#include "mozilla/Attributes.h"
 #include "nsIMultiplexInputStream.h"
 #include "nsISeekableStream.h"
 #include "nsCOMPtr.h"
 #include "nsCOMArray.h"
 #include "nsIClassInfoImpl.h"
 #include "nsIIPCSerializableInputStream.h"
 #include "mozilla/ipc/InputStreamUtils.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 using namespace mozilla::ipc;
 
+using mozilla::Abs;
+
 class nsMultiplexInputStream MOZ_FINAL : public nsIMultiplexInputStream,
                                          public nsISeekableStream,
                                          public nsIIPCSerializableInputStream
 {
 public:
     nsMultiplexInputStream();
 
     NS_DECL_ISUPPORTS
@@ -508,35 +510,35 @@ nsMultiplexInputStream::Seek(int32_t aWh
                 uint64_t avail;
                 rv = mStreams[i]->Available(&avail);
                 NS_ENSURE_SUCCESS(rv, rv);
 
                 streamPos = avail;
             }
 
             // See if we have enough data in the current stream.
-            if (std::abs(remaining) < streamPos) {
+            if (Abs(remaining) < streamPos) {
                 rv = stream->Seek(NS_SEEK_END, remaining);
                 NS_ENSURE_SUCCESS(rv, rv);
 
                 mCurrentStream = i;
                 mStartedReadingCurrent = true;
 
                 remaining = 0;
-            } else if (std::abs(remaining) > streamPos) {
+            } else if (Abs(remaining) > streamPos) {
                 if (i > oldCurrentStream ||
                     (i == oldCurrentStream && !oldStartedReadingCurrent)) {
                     // We're already at start so no need to seek this stream
                     remaining += streamPos;
                 } else {
                     int64_t avail;
                     rv = stream->Tell(&avail);
                     NS_ENSURE_SUCCESS(rv, rv);
 
-                    int64_t newPos = streamPos + XPCOM_MIN(avail, std::abs(remaining));
+                    int64_t newPos = streamPos + XPCOM_MIN(avail, Abs(remaining));
 
                     rv = stream->Seek(NS_SEEK_END, -newPos);
                     NS_ENSURE_SUCCESS(rv, rv);
 
                     mCurrentStream = i;
                     mStartedReadingCurrent = true;
 
                     remaining += newPos;
--- a/xpfe/appshell/src/nsXULWindow.cpp
+++ b/xpfe/appshell/src/nsXULWindow.cpp
@@ -1,14 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 ci et: */
 /* 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/MathAlgorithms.h"
+
 // Local includes
 #include "nsXULWindow.h"
 #include <algorithm>
 
 // Helper classes
 #include "nsPrintfCString.h"
 #include "nsString.h"
 #include "nsWidgetsCID.h"
@@ -51,18 +53,16 @@
 #include "nsStyleConsts.h"
 #include "nsPresContext.h"
 #include "nsContentUtils.h"
 #include "nsWebShellWindow.h" // get rid of this one, too...
 
 #include "prenv.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/Element.h"
-#include <cstdlib> // for std::abs(int/long)
-#include <cmath> // for std::abs(float/double)
 
 using namespace mozilla;
 
 #define SIZEMODE_NORMAL     NS_LITERAL_STRING("normal")
 #define SIZEMODE_MAXIMIZED  NS_LITERAL_STRING("maximized")
 #define SIZEMODE_MINIMIZED  NS_LITERAL_STRING("minimized")
 #define SIZEMODE_FULLSCREEN NS_LITERAL_STRING("fullscreen")
 
@@ -1344,18 +1344,17 @@ void nsXULWindow::StaggerPosition(int32_
         nsCOMPtr<nsIBaseWindow> listBaseWindow(do_QueryInterface(supportsWindow));
         listBaseWindow->GetPosition(&listX, &listY);
         double scale;
         if (NS_SUCCEEDED(listBaseWindow->GetUnscaledDevicePixelsPerCSSPixel(&scale))) {
           listX = NSToIntRound(listX / scale);
           listY = NSToIntRound(listY / scale);
         }
 
-        if (std::abs(listX - aRequestedX) <= kSlop &&
-            std::abs(listY - aRequestedY) <= kSlop) {
+        if (Abs(listX - aRequestedX) <= kSlop && Abs(listY - aRequestedY) <= kSlop) {
           // collision! offset and start over
           if (bouncedX & 0x1)
             aRequestedX -= kOffset;
           else
             aRequestedX += kOffset;
           aRequestedY += kOffset;
 
           if (gotScreen) {