Bug 786533 - Replace NS_MIN/NS_MAX with std::min/std::max and #include <algorithm> where needed. r=ehsan
authorMats Palmgren <matspal@gmail.com>
Tue, 15 Jan 2013 13:22:03 +0100
changeset 124970 037363fa02583ef1f37c80373e46c0a19cf73e64
parent 124969 81a519d21a1e1590ce7dba3fbab26844935337fd
child 124971 b9d9fc98561becefc49f769a5587e659e87b5d88
push idunknown
push userunknown
push dateunknown
reviewersehsan
bugs786533
milestone21.0a1
Bug 786533 - Replace NS_MIN/NS_MAX with std::min/std::max and #include <algorithm> where needed. r=ehsan
accessible/src/base/TextUpdater.cpp
accessible/src/generic/HyperTextAccessible.cpp
browser/components/feeds/src/nsFeedSniffer.cpp
content/base/src/nsAttrValue.cpp
content/base/src/nsContentList.cpp
content/base/src/nsContentUtils.cpp
content/base/src/nsCrossSiteListenerProxy.cpp
content/base/src/nsDOMBlobBuilder.cpp
content/base/src/nsDOMBlobBuilder.h
content/base/src/nsDocument.cpp
content/base/src/nsFrameMessageManager.cpp
content/base/src/nsINode.cpp
content/base/src/nsSyncLoadService.cpp
content/base/src/nsTextFragment.cpp
content/base/src/nsTextFragmentSSE2.cpp
content/base/src/nsViewportInfo.cpp
content/canvas/src/CanvasRenderingContext2D.cpp
content/canvas/src/WebGLContextGL.cpp
content/canvas/src/WebGLContextValidate.cpp
content/canvas/src/WebGLElementArrayCache.cpp
content/canvas/src/WebGLTexture.cpp
content/canvas/src/WebGLTexture.h
content/events/src/nsContentEventHandler.cpp
content/events/src/nsEventStateManager.cpp
content/html/content/src/nsHTMLAudioElement.cpp
content/html/content/src/nsHTMLInputElement.cpp
content/html/content/src/nsHTMLMediaElement.cpp
content/html/content/src/nsHTMLMeterElement.cpp
content/html/content/src/nsHTMLProgressElement.cpp
content/html/document/src/ImageDocument.cpp
content/media/AudioSampleFormat.h
content/media/AudioStream.cpp
content/media/FileBlockCache.cpp
content/media/MediaCache.cpp
content/media/MediaDecoder.cpp
content/media/MediaDecoderReader.cpp
content/media/MediaDecoderStateMachine.cpp
content/media/MediaResource.cpp
content/media/MediaSegment.h
content/media/MediaStreamGraph.cpp
content/media/StreamBuffer.cpp
content/media/StreamBuffer.h
content/media/TrackUnionStream.h
content/media/dash/DASHDecoder.cpp
content/media/dash/DASHReader.cpp
content/media/dash/DASHRepDecoder.cpp
content/media/ogg/OggCodecState.cpp
content/media/ogg/OggReader.cpp
content/media/wave/WaveReader.cpp
content/media/webm/WebMBufferedParser.cpp
content/smil/nsSMILAnimationController.cpp
content/smil/nsSMILAnimationFunction.cpp
content/smil/nsSMILTimeContainer.cpp
content/smil/nsSMILTimedElement.cpp
content/svg/content/src/DOMSVGLengthList.cpp
content/svg/content/src/DOMSVGNumberList.cpp
content/svg/content/src/DOMSVGPointList.cpp
content/svg/content/src/DOMSVGStringList.cpp
content/svg/content/src/DOMSVGTransformList.cpp
content/svg/content/src/SVGLength.cpp
content/svg/content/src/SVGLengthListSMILType.cpp
content/svg/content/src/SVGPathData.cpp
content/svg/content/src/SVGPathElement.cpp
content/svg/content/src/SVGRectElement.cpp
content/svg/content/src/SVGSVGElement.cpp
content/svg/content/src/nsSVGFilters.cpp
content/xslt/src/base/txDouble.cpp
content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
content/xslt/src/xpath/txNodeSet.cpp
content/xslt/src/xslt/txMozillaXMLOutput.cpp
content/xul/content/src/nsXULElement.cpp
content/xul/templates/src/nsTreeRows.cpp
docshell/base/nsDefaultURIFixup.cpp
docshell/base/nsDocShell.cpp
docshell/shistory/src/nsSHEntry.cpp
docshell/shistory/src/nsSHistory.cpp
dom/base/nsDOMWindowUtils.cpp
dom/base/nsFocusManager.cpp
dom/base/nsGlobalWindow.cpp
dom/base/nsJSTimeoutHandler.cpp
dom/bindings/Codegen.py
dom/devicestorage/nsDeviceStorage.cpp
dom/indexedDB/FileManager.cpp
dom/indexedDB/IDBFactory.cpp
dom/indexedDB/IndexedDatabaseManager.cpp
dom/indexedDB/Key.cpp
dom/indexedDB/OpenDatabaseHelper.cpp
dom/ipc/TabChild.cpp
dom/ipc/TabParent.cpp
dom/plugins/base/nsNPAPIPluginStreamListener.cpp
dom/plugins/test/testplugin/nptest_macosx.mm
dom/src/geolocation/nsGeolocation.cpp
dom/src/json/nsJSON.cpp
dom/workers/RuntimeService.cpp
dom/workers/WorkerPrivate.cpp
editor/libeditor/base/CreateElementTxn.cpp
editor/libeditor/html/nsHTMLAbsPosition.cpp
editor/libeditor/html/nsHTMLEditRules.cpp
editor/libeditor/html/nsHTMLObjectResizer.cpp
editor/libeditor/html/nsTableEditor.cpp
embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
extensions/gio/nsGIOProtocolHandler.cpp
extensions/gnomevfs/nsGnomeVFSProtocolHandler.cpp
extensions/pref/autoconfig/src/nsAutoConfig.cpp
extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
gfx/2d/BaseRect.h
gfx/2d/convolver.cpp
gfx/2d/image_operations.cpp
gfx/gl/GLContext.cpp
gfx/gl/GLContext.h
gfx/layers/ThebesLayerBuffer.cpp
gfx/layers/d3d9/DeviceManagerD3D9.cpp
gfx/layers/ipc/AsyncPanZoomController.cpp
gfx/layers/ipc/Axis.cpp
gfx/layers/ipc/CompositorParent.cpp
gfx/layers/opengl/LayerManagerOGL.cpp
gfx/src/nsBoundingMetrics.h
gfx/src/nsCoord.h
gfx/src/nsDeviceContext.cpp
gfx/src/nsFontMetrics.cpp
gfx/src/nsRect.h
gfx/src/nsRegion.cpp
gfx/src/nsRenderingContext.cpp
gfx/thebes/gfxASurface.cpp
gfx/thebes/gfxContext.cpp
gfx/thebes/gfxCoreTextShaper.cpp
gfx/thebes/gfxDWriteFontList.h
gfx/thebes/gfxDWriteFonts.cpp
gfx/thebes/gfxFT2Utils.cpp
gfx/thebes/gfxFont.cpp
gfx/thebes/gfxFont.h
gfx/thebes/gfxFontUtils.h
gfx/thebes/gfxGDIFont.cpp
gfx/thebes/gfxGDIFontList.cpp
gfx/thebes/gfxHarfBuzzShaper.cpp
gfx/thebes/gfxImageSurface.cpp
gfx/thebes/gfxMacFont.cpp
gfx/thebes/gfxMacPlatformFontList.mm
gfx/thebes/gfxOS2Fonts.cpp
gfx/thebes/gfxQuad.h
gfx/thebes/gfxQuaternion.h
gfx/thebes/gfxSkipChars.cpp
gfx/thebes/gfxXlibSurface.cpp
hal/gonk/GonkHal.cpp
image/decoders/icon/gtk/nsIconChannel.cpp
image/decoders/nsBMPDecoder.cpp
image/decoders/nsGIFDecoder2.cpp
image/decoders/nsICODecoder.cpp
image/decoders/nsIconDecoder.cpp
image/decoders/nsPNGDecoder.cpp
image/src/ImageFactory.cpp
image/src/RasterImage.cpp
image/src/VectorImage.cpp
intl/uconv/src/nsConverterInputStream.cpp
intl/uconv/src/nsUTF8ToUnicode.cpp
intl/uconv/util/nsUCSupport.cpp
js/xpconnect/src/XPCJSRuntime.cpp
js/xpconnect/src/XPCWrappedNative.cpp
js/xpconnect/src/qsgen.py
layout/base/FrameLayerBuilder.cpp
layout/base/PositionedEventTargeting.cpp
layout/base/nsBidiPresUtils.cpp
layout/base/nsCSSFrameConstructor.cpp
layout/base/nsCSSRendering.cpp
layout/base/nsCSSRenderingBorders.cpp
layout/base/nsCaret.cpp
layout/base/nsDisplayList.cpp
layout/base/nsDisplayList.h
layout/base/nsLayoutUtils.cpp
layout/base/nsLayoutUtils.h
layout/base/nsPresContext.h
layout/base/nsPresShell.cpp
layout/forms/nsComboboxControlFrame.cpp
layout/forms/nsFieldSetFrame.cpp
layout/forms/nsGfxCheckboxControlFrame.cpp
layout/forms/nsHTMLButtonControlFrame.cpp
layout/forms/nsListControlFrame.cpp
layout/forms/nsMeterFrame.cpp
layout/forms/nsProgressFrame.cpp
layout/forms/nsTextControlFrame.cpp
layout/generic/TextOverflow.cpp
layout/generic/TextOverflow.h
layout/generic/nsBlockFrame.cpp
layout/generic/nsBlockReflowState.cpp
layout/generic/nsBulletFrame.cpp
layout/generic/nsColumnSetFrame.cpp
layout/generic/nsContainerFrame.cpp
layout/generic/nsFlexContainerFrame.cpp
layout/generic/nsFloatManager.cpp
layout/generic/nsFrame.cpp
layout/generic/nsGfxScrollFrame.cpp
layout/generic/nsHTMLCanvasFrame.cpp
layout/generic/nsHTMLReflowState.cpp
layout/generic/nsHTMLReflowState.h
layout/generic/nsIFrame.h
layout/generic/nsImageFrame.cpp
layout/generic/nsIntervalSet.cpp
layout/generic/nsLineBox.h
layout/generic/nsLineLayout.cpp
layout/generic/nsObjectFrame.cpp
layout/generic/nsSelection.cpp
layout/generic/nsSimplePageSequence.cpp
layout/generic/nsTextFrameThebes.cpp
layout/generic/nsTextFrameUtils.cpp
layout/generic/nsVideoFrame.cpp
layout/mathml/nsMathMLChar.cpp
layout/mathml/nsMathMLTokenFrame.cpp
layout/mathml/nsMathMLmencloseFrame.cpp
layout/mathml/nsMathMLmfencedFrame.cpp
layout/mathml/nsMathMLmfracFrame.cpp
layout/mathml/nsMathMLmmultiscriptsFrame.cpp
layout/mathml/nsMathMLmoFrame.cpp
layout/mathml/nsMathMLmpaddedFrame.cpp
layout/mathml/nsMathMLmrootFrame.cpp
layout/mathml/nsMathMLmspaceFrame.cpp
layout/mathml/nsMathMLmsubFrame.cpp
layout/mathml/nsMathMLmsubsupFrame.cpp
layout/mathml/nsMathMLmsupFrame.cpp
layout/mathml/nsMathMLmtableFrame.cpp
layout/mathml/nsMathMLmunderoverFrame.cpp
layout/printing/nsPrintEngine.cpp
layout/style/nsCSSRuleProcessor.cpp
layout/style/nsCSSScanner.cpp
layout/style/nsComputedDOMStyle.cpp
layout/style/nsRuleNode.cpp
layout/style/nsStyleStruct.cpp
layout/style/nsStyleStruct.h
layout/svg/nsSVGGlyphFrame.cpp
layout/svg/nsSVGGradientFrame.cpp
layout/svg/nsSVGTextContainerFrame.cpp
layout/svg/nsSVGUtils.cpp
layout/svg/nsSVGUtils.h
layout/tables/BasicTableLayoutStrategy.cpp
layout/tables/FixedTableLayoutStrategy.cpp
layout/tables/nsCellMap.cpp
layout/tables/nsCellMap.h
layout/tables/nsTableCellFrame.cpp
layout/tables/nsTableFrame.cpp
layout/tables/nsTableOuterFrame.cpp
layout/tables/nsTableRowFrame.cpp
layout/tables/nsTableRowGroupFrame.cpp
layout/xul/base/src/grid/nsGridRowLeafLayout.cpp
layout/xul/base/src/nsBox.cpp
layout/xul/base/src/nsBoxFrame.cpp
layout/xul/base/src/nsLeafBoxFrame.cpp
layout/xul/base/src/nsListBoxBodyFrame.cpp
layout/xul/base/src/nsListItemFrame.cpp
layout/xul/base/src/nsMenuFrame.cpp
layout/xul/base/src/nsMenuPopupFrame.cpp
layout/xul/base/src/nsResizerFrame.cpp
layout/xul/base/src/nsSliderFrame.cpp
layout/xul/base/src/nsSprocketLayout.cpp
layout/xul/base/src/tree/src/nsTreeBodyFrame.cpp
modules/libjar/nsJARInputStream.cpp
netwerk/base/src/nsBufferedStreams.cpp
netwerk/base/src/nsFileStreams.h
netwerk/base/src/nsIncrementalDownload.cpp
netwerk/base/src/nsInputStreamPump.cpp
netwerk/base/src/nsPreloadedStream.cpp
netwerk/base/src/nsSocketTransport2.cpp
netwerk/base/src/nsStandardURL.cpp
netwerk/base/src/nsSyncStreamListener.cpp
netwerk/base/src/nsUnicharStreamLoader.cpp
netwerk/cache/nsCacheEntryDescriptor.cpp
netwerk/cache/nsCacheService.cpp
netwerk/cache/nsDiskCacheBlockFile.cpp
netwerk/cache/nsDiskCacheMap.cpp
netwerk/cache/nsDiskCacheStreams.cpp
netwerk/cache/nsMemoryCacheDevice.cpp
netwerk/protocol/about/nsAboutCacheEntry.cpp
netwerk/protocol/file/nsFileChannel.cpp
netwerk/protocol/ftp/nsFtpControlConnection.cpp
netwerk/protocol/http/HttpBaseChannel.cpp
netwerk/protocol/http/SpdySession2.cpp
netwerk/protocol/http/SpdySession3.cpp
netwerk/protocol/http/SpdyStream2.cpp
netwerk/protocol/http/SpdyStream3.cpp
netwerk/protocol/http/nsHttpChunkedDecoder.cpp
netwerk/protocol/http/nsHttpConnectionMgr.cpp
netwerk/protocol/http/nsHttpPipeline.cpp
netwerk/protocol/http/nsHttpResponseHead.cpp
netwerk/protocol/http/nsHttpTransaction.cpp
netwerk/protocol/websocket/WebSocketChannel.cpp
netwerk/streamconv/converters/nsBinHexDecoder.cpp
netwerk/streamconv/converters/nsFTPDirListingConv.cpp
netwerk/streamconv/converters/nsIndexedToHTML.cpp
netwerk/streamconv/converters/nsMultiMixedConv.cpp
netwerk/streamconv/converters/nsTXTToHTMLConv.cpp
netwerk/streamconv/test/Converters.cpp
netwerk/streamconv/test/TestStreamConv.cpp
netwerk/test/TestHttp.cpp
netwerk/test/TestMCTransport.cpp
netwerk/test/TestOverlappedIO.cpp
netwerk/test/TestPageLoad.cpp
netwerk/test/TestPerf.cpp
netwerk/test/TestProtocols.cpp
netwerk/test/TestStreamChannel.cpp
netwerk/test/TestStreamPump.cpp
netwerk/test/TestThreadedIO.cpp
netwerk/test/TestUpload.cpp
parser/htmlparser/public/nsScannerString.h
parser/htmlparser/src/CNavDTD.cpp
parser/htmlparser/src/nsHTMLTags.cpp
security/manager/boot/src/nsEntropyCollector.cpp
security/manager/ssl/src/nsCrypto.cpp
security/manager/ssl/src/nsNSSCertHelper.cpp
security/manager/ssl/src/nsNSSComponent.cpp
storage/src/mozStorageConnection.cpp
storage/src/mozStorageSQLFunctions.cpp
toolkit/components/mediasniffer/nsMediaSniffer.cpp
toolkit/components/places/AsyncFaviconHelpers.cpp
toolkit/components/places/nsNavHistory.cpp
tools/profiler/sps_sampler.h
widget/android/nsWindow.cpp
widget/cocoa/GfxInfo.mm
widget/cocoa/nsCocoaWindow.mm
widget/cocoa/nsNativeThemeCocoa.mm
widget/gtk2/nsGtkKeyUtils.cpp
widget/gtk2/nsNativeThemeGTK.cpp
widget/gtk2/nsPrintSettingsGTK.cpp
widget/gtk2/nsWindow.cpp
widget/os2/nsDragService.cpp
widget/os2/nsIdleServiceOS2.cpp
widget/qt/nsWindow.cpp
widget/tests/TestWinTSF.cpp
widget/windows/IEnumFE.cpp
widget/windows/KeyboardLayout.cpp
widget/windows/nsDataObj.cpp
widget/windows/nsIMM32Handler.cpp
widget/windows/nsNativeThemeWin.cpp
widget/windows/nsTextStore.cpp
widget/windows/nsWindow.cpp
widget/xpwidgets/nsBaseDragService.cpp
widget/xpwidgets/nsBaseWidget.h
widget/xpwidgets/nsIdleService.cpp
widget/xpwidgets/nsNativeTheme.cpp
xpfe/appshell/src/nsXULWindow.cpp
--- a/accessible/src/base/TextUpdater.cpp
+++ b/accessible/src/base/TextUpdater.cpp
@@ -3,28 +3,29 @@
  * 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 "TextUpdater.h"
 
 #include "Accessible-inl.h"
 #include "DocAccessible-inl.h"
 #include "TextLeafAccessible.h"
+#include <algorithm>
 
 using namespace mozilla::a11y;
 
 void
 TextUpdater::Run(DocAccessible* aDocument, TextLeafAccessible* aTextLeaf,
                  const nsAString& aNewText)
 {
   NS_ASSERTION(aTextLeaf, "No text leaf accessible?");
 
   const nsString& oldText = aTextLeaf->Text();
   uint32_t oldLen = oldText.Length(), newLen = aNewText.Length();
-  uint32_t minLen = NS_MIN(oldLen, newLen);
+  uint32_t minLen = std::min(oldLen, newLen);
 
   // Skip coinciding begin substrings.
   uint32_t skipStart = 0;
   for (; skipStart < minLen; skipStart++) {
     if (aNewText[skipStart] != oldText[skipStart])
       break;
   }
 
@@ -50,17 +51,17 @@ TextUpdater::DoUpdate(const nsAString& a
   }
 
   // Get the text leaf accessible offset and invalidate cached offsets after it.
   mTextOffset = mHyperText->GetChildOffset(mTextLeaf, true);
   NS_ASSERTION(mTextOffset != -1,
                "Text leaf hasn't offset within hyper text!");
 
   uint32_t oldLen = aOldText.Length(), newLen = aNewText.Length();
-  uint32_t minLen = NS_MIN(oldLen, newLen);
+  uint32_t minLen = std::min(oldLen, newLen);
 
   // Trim coinciding substrings from the end.
   uint32_t skipEnd = 0;
   while (minLen - skipEnd > aSkipStart &&
          aNewText[newLen - skipEnd - 1] == aOldText[oldLen - skipEnd - 1]) {
     skipEnd++;
   }
 
@@ -115,17 +116,17 @@ TextUpdater::DoUpdate(const nsAString& a
     uint32_t* prevRow = row;
     row += len1;
     row[0] = rowIdx;
     for (uint32_t colIdx = 1; colIdx < len1; colIdx++) {
       if (str1[colIdx - 1] != str2[rowIdx - 1]) {
         uint32_t left = row[colIdx - 1];
         uint32_t up = prevRow[colIdx];
         uint32_t upleft = prevRow[colIdx - 1];
-        row[colIdx] = NS_MIN(upleft, NS_MIN(left, up)) + 1;
+        row[colIdx] = std::min(upleft, std::min(left, up)) + 1;
       } else {
         row[colIdx] = prevRow[colIdx - 1];
       }
     }
   }
 
   // Compute events based on the difference.
   nsTArray<nsRefPtr<AccEvent> > events;
--- a/accessible/src/generic/HyperTextAccessible.cpp
+++ b/accessible/src/generic/HyperTextAccessible.cpp
@@ -24,16 +24,17 @@
 #include "nsILineIterator.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIPlaintextEditor.h"
 #include "nsIScrollableFrame.h"
 #include "nsIServiceManager.h"
 #include "nsTextFragment.h"
 #include "mozilla/Selection.h"
 #include "gfxSkipChars.h"
+#include <algorithm>
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // HyperTextAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
@@ -173,17 +174,17 @@ HyperTextAccessible::GetBoundsForString(
     // are returning.
     nsRect frameScreenRect = frame->GetScreenRectInAppUnits();
 
     // Get the length of the substring in this frame that we want the bounds for
     int32_t startFrameTextOffset, endFrameTextOffset;
     frame->GetOffsets(startFrameTextOffset, endFrameTextOffset);
     int32_t frameTotalTextLength = endFrameTextOffset - startFrameTextOffset;
     int32_t seekLength = endContentOffset - startContentOffset;
-    int32_t frameSubStringLength = NS_MIN(frameTotalTextLength - startContentOffsetInFrame, seekLength);
+    int32_t frameSubStringLength = std::min(frameTotalTextLength - startContentOffsetInFrame, seekLength);
 
     // Add the point where the string starts to the frameScreenRect
     nsPoint frameTextStartPoint;
     rv = frame->GetPointFromOffset(startContentOffset, &frameTextStartPoint);
     NS_ENSURE_SUCCESS(rv, nsIntRect());
     frameScreenRect.x += frameTextStartPoint.x;
 
     // Use the point for the end offset to calculate the width
--- a/browser/components/feeds/src/nsFeedSniffer.cpp
+++ b/browser/components/feeds/src/nsFeedSniffer.cpp
@@ -22,16 +22,17 @@
 #include "nsIStreamConverter.h"
 
 #include "nsIStreamListener.h"
 
 #include "nsIHttpChannel.h"
 #include "nsIMIMEHeaderParam.h"
 
 #include "nsMimeTypes.h"
+#include <algorithm>
 
 #define TYPE_ATOM "application/atom+xml"
 #define TYPE_RSS "application/rss+xml"
 #define TYPE_MAYBE_FEED "application/vnd.mozilla.maybe.feed"
 
 #define NS_RDF "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 #define NS_RSS "http://purl.org/rss/1.0/"
 
@@ -281,20 +282,20 @@ nsFeedSniffer::GetMIMETypeFromContent(ns
     return rv;
 
   // We cap the number of bytes to scan at MAX_BYTES to prevent picking up 
   // false positives by accidentally reading document content, e.g. a "how to
   // make a feed" page.
   const char* testData;
   if (mDecodedData.IsEmpty()) {
     testData = (const char*)data;
-    length = NS_MIN(length, MAX_BYTES);
+    length = std::min(length, MAX_BYTES);
   } else {
     testData = mDecodedData.get();
-    length = NS_MIN(mDecodedData.Length(), MAX_BYTES);
+    length = std::min(mDecodedData.Length(), MAX_BYTES);
   }
 
   // The strategy here is based on that described in:
   // http://blogs.msdn.com/rssteam/articles/PublishersGuide.aspx
   // for interoperarbility purposes.
 
   // Thus begins the actual sniffing.
   nsDependentCSubstring dataString((const char*)testData, length);
--- a/content/base/src/nsAttrValue.cpp
+++ b/content/base/src/nsAttrValue.cpp
@@ -18,16 +18,17 @@
 #include "mozilla/css/StyleRule.h"
 #include "mozilla/css/Declaration.h"
 #include "nsContentUtils.h"
 #include "nsReadableUtils.h"
 #include "prprf.h"
 #include "nsHTMLCSSStyleSheet.h"
 #include "nsCSSParser.h"
 #include "nsStyledElement.h"
+#include <algorithm>
 
 using namespace mozilla;
 
 #define MISC_STR_PTR(_cont) \
   reinterpret_cast<void*>((_cont)->mStringBits & NS_ATTRVALUE_POINTERVALUE_MASK)
 
 bool
 MiscContainer::GetString(nsAString& aString) const
@@ -1446,17 +1447,17 @@ nsAttrValue::ParseSpecialIntValue(const 
   bool isPercent = false;
   nsAutoString tmp(aString);
   int32_t originalVal = StringToInteger(aString, &strict, &ec, true, &isPercent);
 
   if (NS_FAILED(ec)) {
     return false;
   }
 
-  int32_t val = NS_MAX(originalVal, 0);
+  int32_t val = std::max(originalVal, 0);
 
   // % (percent)
   if (isPercent || tmp.RFindChar('%') >= 0) {
     isPercent = true;
   }
 
   strict = strict && (originalVal == val);
 
@@ -1476,18 +1477,18 @@ nsAttrValue::ParseIntWithBounds(const ns
 
   nsresult ec;
   bool strict;
   int32_t originalVal = StringToInteger(aString, &strict, &ec);
   if (NS_FAILED(ec)) {
     return false;
   }
 
-  int32_t val = NS_MAX(originalVal, aMin);
-  val = NS_MIN(val, aMax);
+  int32_t val = std::max(originalVal, aMin);
+  val = std::min(val, aMax);
   strict = strict && (originalVal == val);
   SetIntValueAndType(val, eInteger, strict ? nullptr : &aString);
 
   return true;
 }
 
 bool
 nsAttrValue::ParseNonNegativeIntValue(const nsAString& aString)
--- a/content/base/src/nsContentList.cpp
+++ b/content/base/src/nsContentList.cpp
@@ -19,16 +19,17 @@
 #include "nsContentUtils.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsGkAtoms.h"
 #include "mozilla/dom/HTMLCollectionBinding.h"
 #include "mozilla/dom/NodeListBinding.h"
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/Likely.h"
 #include "nsGenericHTMLElement.h"
+#include <algorithm>
 
 // Form related includes
 #include "nsIDOMHTMLFormElement.h"
 
 #include "pldhash.h"
 
 #ifdef DEBUG_CONTENT_LIST
 #include "nsIContentIterator.h"
@@ -562,17 +563,17 @@ nsContentList::Item(uint32_t aIndex, boo
     nsIDocument* doc = mRootNode->GetCurrentDoc();
     if (doc) {
       // Flush pending content changes Bug 4891.
       doc->FlushPendingNotifications(Flush_ContentAndNotify);
     }
   }
 
   if (mState != LIST_UP_TO_DATE)
-    PopulateSelf(NS_MIN(aIndex, UINT32_MAX - 1) + 1);
+    PopulateSelf(std::min(aIndex, UINT32_MAX - 1) + 1);
 
   ASSERT_IN_SYNC;
   NS_ASSERTION(!mRootNode || mState != LIST_DIRTY,
                "PopulateSelf left the list in a dirty (useless) state!");
 
   return mElements.SafeElementAt(aIndex);
 }
 
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -118,16 +118,17 @@
 #include "nsViewManager.h"
 #include "nsEventStateManager.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsParserConstants.h"
 #include "nsIWebNavigation.h"
 #include "nsILoadContext.h"
 #include "nsTextFragment.h"
 #include "mozilla/Selection.h"
+#include <algorithm>
 
 #ifdef IBMBIDI
 #include "nsIBidiKeyboard.h"
 #endif
 #include "nsCycleCollectionParticipant.h"
 
 // for ReportToConsole
 #include "nsIStringBundle.h"
@@ -1923,17 +1924,17 @@ nsContentUtils::GetCommonAncestor(nsINod
     aNode2 = aNode2->GetParentNode();
   } while (aNode2);
 
   // Find where the parent chain differs
   uint32_t pos1 = parents1.Length();
   uint32_t pos2 = parents2.Length();
   nsINode* parent = nullptr;
   uint32_t len;
-  for (len = NS_MIN(pos1, pos2); len > 0; --len) {
+  for (len = std::min(pos1, pos2); len > 0; --len) {
     nsINode* child1 = parents1.ElementAt(--pos1);
     nsINode* child2 = parents2.ElementAt(--pos2);
     if (child1 != child2) {
       break;
     }
     parent = child1;
   }
 
@@ -1974,17 +1975,17 @@ nsContentUtils::ComparePoints(nsINode* a
   if (disconnected) {
     NS_ASSERTION(aDisconnected, "unexpected disconnected nodes");
     return 1;
   }
 
   // Find where the parent chains differ
   nsINode* parent = parents1.ElementAt(pos1);
   uint32_t len;
-  for (len = NS_MIN(pos1, pos2); len > 0; --len) {
+  for (len = std::min(pos1, pos2); len > 0; --len) {
     nsINode* child1 = parents1.ElementAt(--pos1);
     nsINode* child2 = parents2.ElementAt(--pos2);
     if (child1 != child2) {
       return parent->IndexOf(child1) < parent->IndexOf(child2) ? -1 : 1;
     }
     parent = child1;
   }
 
@@ -4709,17 +4710,17 @@ nsContentUtils::GetTopLevelWidget(nsIWid
 
 /* static */
 const nsDependentString
 nsContentUtils::GetLocalizedEllipsis()
 {
   static PRUnichar sBuf[4] = { 0, 0, 0, 0 };
   if (!sBuf[0]) {
     nsAdoptingString tmp = Preferences::GetLocalizedString("intl.ellipsis");
-    uint32_t len = NS_MIN(uint32_t(tmp.Length()),
+    uint32_t len = std::min(uint32_t(tmp.Length()),
                           uint32_t(ArrayLength(sBuf) - 1));
     CopyUnicodeTo(tmp, 0, sBuf, len);
     if (!sBuf[0])
       sBuf[0] = PRUnichar(0x2026);
   }
   return nsDependentString(sBuf);
 }
 
@@ -6728,18 +6729,18 @@ nsContentUtils::GetSelectionInTextContro
     }
     if ((focusNode == aRoot && focusOffset != 0) ||
         (focusNode != aRoot && focusNode != firstChild)) {
       focusOffset = firstChild->Length();
     }
   }
 
   // Make sure aOutStartOffset <= aOutEndOffset.
-  aOutStartOffset = NS_MIN(anchorOffset, focusOffset);
-  aOutEndOffset = NS_MAX(anchorOffset, focusOffset);
+  aOutStartOffset = std::min(anchorOffset, focusOffset);
+  aOutEndOffset = std::max(anchorOffset, focusOffset);
 }
 
 nsIEditor*
 nsContentUtils::GetHTMLEditor(nsPresContext* aPresContext)
 {
   nsCOMPtr<nsISupports> container = aPresContext->GetContainer();
   nsCOMPtr<nsIEditorDocShell> editorDocShell(do_QueryInterface(container));
   bool isEditable;
--- a/content/base/src/nsCrossSiteListenerProxy.cpp
+++ b/content/base/src/nsCrossSiteListenerProxy.cpp
@@ -22,16 +22,17 @@
 #include "nsIAsyncVerifyRedirectCallback.h"
 #include "nsCharSeparatedTokenizer.h"
 #include "nsAsyncRedirectVerifyHelper.h"
 #include "prtime.h"
 #include "nsClassHashtable.h"
 #include "nsHashKeys.h"
 #include "nsStreamUtils.h"
 #include "mozilla/Preferences.h"
+#include <algorithm>
 
 using namespace mozilla;
 
 #define PREFLIGHT_CACHE_SIZE 100
 
 static bool gDisableCORS = false;
 static bool gDisableCORSPrivateData = false;
 
@@ -878,17 +879,17 @@ nsCORSPreflightListener::AddResultToCach
   headerVal.BeginReading(iter);
   headerVal.EndReading(end);
   while (iter != end) {
     if (*iter < '0' || *iter > '9') {
       return;
     }
     age = age * 10 + (*iter - '0');
     // Cap at 24 hours. This also avoids overflow
-    age = NS_MIN(age, 86400U);
+    age = std::min(age, 86400U);
     ++iter;
   }
 
   if (!age || !EnsurePreflightCache()) {
     return;
   }
 
 
--- a/content/base/src/nsDOMBlobBuilder.cpp
+++ b/content/base/src/nsDOMBlobBuilder.cpp
@@ -10,16 +10,17 @@
 #include "nsAutoPtr.h"
 #include "nsDOMClassInfoID.h"
 #include "nsIMultiplexInputStream.h"
 #include "nsStringStream.h"
 #include "nsTArray.h"
 #include "nsJSUtils.h"
 #include "nsContentUtils.h"
 #include "nsIScriptError.h"
+#include <algorithm>
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_IMPL_ISUPPORTS_INHERITED1(nsDOMMultipartFile, nsDOMFile,
                              nsIJSNativeInitializer)
 
 NS_IMETHODIMP
@@ -89,17 +90,17 @@ nsDOMMultipartFile::CreateSlice(uint64_t
   for (i = 0; length && skipStart && i < mBlobs.Length(); i++) {
     nsIDOMBlob* blob = mBlobs[i].get();
 
     uint64_t l;
     nsresult rv = blob->GetSize(&l);
     NS_ENSURE_SUCCESS(rv, nullptr);
 
     if (skipStart < l) {
-      uint64_t upperBound = NS_MIN<uint64_t>(l - skipStart, length);
+      uint64_t upperBound = std::min<uint64_t>(l - skipStart, length);
 
       nsCOMPtr<nsIDOMBlob> firstBlob;
       rv = blob->Slice(skipStart, skipStart + upperBound,
                        aContentType, 3,
                        getter_AddRefs(firstBlob));
       NS_ENSURE_SUCCESS(rv, nullptr);
 
       // Avoid wrapping a single blob inside an nsDOMMultipartFile
@@ -128,17 +129,17 @@ nsDOMMultipartFile::CreateSlice(uint64_t
       rv = blob->Slice(0, length, aContentType, 3,
                        getter_AddRefs(lastBlob));
       NS_ENSURE_SUCCESS(rv, nullptr);
 
       blobs.AppendElement(lastBlob);
     } else {
       blobs.AppendElement(blob);
     }
-    length -= NS_MIN<uint64_t>(l, length);
+    length -= std::min<uint64_t>(l, length);
   }
 
   // we can create our blob now
   nsCOMPtr<nsIDOMBlob> blob = new nsDOMMultipartFile(blobs, aContentType);
   return blob.forget();
 }
 
 /* static */ nsresult
--- a/content/base/src/nsDOMBlobBuilder.h
+++ b/content/base/src/nsDOMBlobBuilder.h
@@ -5,16 +5,17 @@
 
 #ifndef nsDOMBlobBuilder_h
 #define nsDOMBlobBuilder_h
 
 #include "nsDOMFile.h"
 
 #include "mozilla/CheckedInt.h"
 #include "mozilla/Attributes.h"
+#include <algorithm>
 
 class nsDOMMultipartFile : public nsDOMFile,
                            public nsIJSNativeInitializer
 {
 public:
   // Create as a file
   nsDOMMultipartFile(nsTArray<nsCOMPtr<nsIDOMBlob> >& aBlobs,
                      const nsAString& aName,
@@ -128,17 +129,17 @@ protected:
 
     if (mDataBufferLen >= mDataLen + aSize) {
       mDataLen += aSize;
       return true;
     }
 
     // Start at 1 or we'll loop forever.
     CheckedUint32 bufferLen =
-      NS_MAX<uint32_t>(static_cast<uint32_t>(mDataBufferLen), 1);
+      std::max<uint32_t>(static_cast<uint32_t>(mDataBufferLen), 1);
     while (bufferLen.isValid() && bufferLen.value() < mDataLen + aSize)
       bufferLen *= 2;
 
     if (!bufferLen.isValid())
       return false;
 
     void* data = moz_realloc(mData, bufferLen.value());
     if (!data)
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -6,16 +6,17 @@
 
 /*
  * Base class for all our document implementations.
  */
 
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Util.h"
 #include "mozilla/Likely.h"
+#include <algorithm>
 
 #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"
@@ -6518,33 +6519,33 @@ nsDocument::GetViewportInfo(uint32_t aDi
 
     nsresult errorCode;
     mScaleMinFloat = minScaleStr.ToFloat(&errorCode);
 
     if (NS_FAILED(errorCode)) {
       mScaleMinFloat = kViewportMinScale;
     }
 
-    mScaleMinFloat = NS_MIN((double)mScaleMinFloat, kViewportMaxScale);
-    mScaleMinFloat = NS_MAX((double)mScaleMinFloat, kViewportMinScale);
+    mScaleMinFloat = std::min((double)mScaleMinFloat, kViewportMaxScale);
+    mScaleMinFloat = std::max((double)mScaleMinFloat, kViewportMinScale);
 
     nsAutoString maxScaleStr;
     GetHeaderData(nsGkAtoms::viewport_maximum_scale, maxScaleStr);
 
     // We define a special error code variable for the scale and max scale,
     // because they are used later (see the width calculations).
     nsresult scaleMaxErrorCode;
     mScaleMaxFloat = maxScaleStr.ToFloat(&scaleMaxErrorCode);
 
     if (NS_FAILED(scaleMaxErrorCode)) {
       mScaleMaxFloat = kViewportMaxScale;
     }
 
-    mScaleMaxFloat = NS_MIN((double)mScaleMaxFloat, kViewportMaxScale);
-    mScaleMaxFloat = NS_MAX((double)mScaleMaxFloat, kViewportMinScale);
+    mScaleMaxFloat = std::min((double)mScaleMaxFloat, kViewportMaxScale);
+    mScaleMaxFloat = std::max((double)mScaleMaxFloat, kViewportMinScale);
 
     nsAutoString scaleStr;
     GetHeaderData(nsGkAtoms::viewport_initial_scale, scaleStr);
 
     nsresult scaleErrorCode;
     mScaleFloat = scaleStr.ToFloat(&scaleErrorCode);
 
     nsAutoString widthStr, heightStr;
@@ -6621,36 +6622,36 @@ nsDocument::GetViewportInfo(uint32_t aDi
 
     if (mAutoSize) {
       // aDisplayWidth and aDisplayHeight are in device pixels; convert them to
       // CSS pixels for the viewport size.
       width = aDisplayWidth / pixelRatio;
       height = aDisplayHeight / pixelRatio;
     }
 
-    width = NS_MIN(width, kViewportMaxWidth);
-    width = NS_MAX(width, kViewportMinWidth);
+    width = std::min(width, kViewportMaxWidth);
+    width = std::max(width, kViewportMinWidth);
 
     // Also recalculate the default zoom, if it wasn't specified in the metadata,
     // and the width is specified.
     if (mScaleStrEmpty && !mWidthStrEmpty) {
-      scaleFloat = NS_MAX(scaleFloat, float(aDisplayWidth) / float(width));
-    }
-
-    height = NS_MIN(height, kViewportMaxHeight);
-    height = NS_MAX(height, kViewportMinHeight);
+      scaleFloat = std::max(scaleFloat, float(aDisplayWidth) / float(width));
+    }
+
+    height = std::min(height, kViewportMaxHeight);
+    height = std::max(height, kViewportMinHeight);
 
     // We need to perform a conversion, but only if the initial or maximum
     // scale were set explicitly by the user.
     if (mValidScaleFloat) {
-      width = NS_MAX(width, (uint32_t)(aDisplayWidth / scaleFloat));
-      height = NS_MAX(height, (uint32_t)(aDisplayHeight / scaleFloat));
+      width = std::max(width, (uint32_t)(aDisplayWidth / scaleFloat));
+      height = std::max(height, (uint32_t)(aDisplayHeight / scaleFloat));
     } else if (mValidMaxScale) {
-      width = NS_MAX(width, (uint32_t)(aDisplayWidth / scaleMaxFloat));
-      height = NS_MAX(height, (uint32_t)(aDisplayHeight / scaleMaxFloat));
+      width = std::max(width, (uint32_t)(aDisplayWidth / scaleMaxFloat));
+      height = std::max(height, (uint32_t)(aDisplayHeight / scaleMaxFloat));
     }
 
     nsViewportInfo ret(scaleFloat, scaleMinFloat, scaleMaxFloat, width, height,
                        mAutoSize, mAllowZoom);
     return ret;
   }
 }
 
@@ -6754,17 +6755,17 @@ nsDocument::FlushPendingNotifications(mo
   // is unsafe.
   // Since media queries mean that a size change of our container can
   // affect style, we need to promote a style flush on ourself to a
   // layout flush on our parent, since we need our container to be the
   // correct size to determine the correct style.
   if (mParentDocument && IsSafeToFlush()) {
     mozFlushType parentType = aType;
     if (aType >= Flush_Style)
-      parentType = NS_MAX(Flush_Layout, aType);
+      parentType = std::max(Flush_Layout, aType);
     mParentDocument->FlushPendingNotifications(parentType);
   }
 
   // We can optimize away getting our presshell and calling
   // FlushPendingNotifications on it if we don't need a flush of the sort we're
   // looking at.  The one exception is if mInFlush is true, because in that
   // case we might have set mNeedStyleFlush and mNeedLayoutFlush to false
   // already but the presshell hasn't actually done the corresponding work yet.
--- a/content/base/src/nsFrameMessageManager.cpp
+++ b/content/base/src/nsFrameMessageManager.cpp
@@ -26,16 +26,17 @@
 #include "nsIProtocolHandler.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIJSRuntimeService.h"
 #include "nsIDOMClassInfo.h"
 #include "nsIDOMFile.h"
 #include "xpcpublic.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/StructuredCloneUtils.h"
+#include <algorithm>
 
 #ifdef ANDROID
 #include <android/log.h>
 #endif
 #ifdef XP_WIN
 #include <windows.h>
 #endif
 
@@ -944,17 +945,17 @@ nsFrameScriptExecutor::TryCacheLoadAndCo
   channel->Open(getter_AddRefs(input));
   nsString dataString;
   uint64_t avail64 = 0;
   if (input && NS_SUCCEEDED(input->Available(&avail64)) && avail64) {
     if (avail64 > UINT32_MAX) {
       return;
     }
     nsCString buffer;
-    uint32_t avail = (uint32_t)NS_MIN(avail64, (uint64_t)UINT32_MAX);
+    uint32_t avail = (uint32_t)std::min(avail64, (uint64_t)UINT32_MAX);
     if (NS_FAILED(NS_ReadInputStreamToString(input, buffer, avail))) {
       return;
     }
     nsScriptLoader::ConvertToUTF16(channel, (uint8_t*)buffer.get(), avail,
                                    EmptyString(), nullptr, dataString);
   }
 
   if (!dataString.IsEmpty()) {
--- a/content/base/src/nsINode.cpp
+++ b/content/base/src/nsINode.cpp
@@ -99,16 +99,17 @@
 #include "prprf.h"
 #include "xpcpublic.h"
 #include "nsCSSRuleProcessor.h"
 #include "nsCSSParser.h"
 #include "nsHTMLLegendElement.h"
 #include "nsWrapperCacheInlines.h"
 #include "WrapperFactory.h"
 #include "DocumentType.h"
+#include <algorithm>
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 nsINode::nsSlots::~nsSlots()
 {
   if (mChildNodes) {
     mChildNodes->DropReference();
@@ -801,17 +802,17 @@ nsINode::CompareDocumentPosition(nsINode
       (nsIDOMNode::DOCUMENT_POSITION_FOLLOWING |
        nsIDOMNode::DOCUMENT_POSITION_DISCONNECTED |
        nsIDOMNode::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC);
   }
 
   // Find where the parent chain differs and check indices in the parent.
   const nsINode* parent = top1;
   uint32_t len;
-  for (len = NS_MIN(pos1, pos2); len > 0; --len) {
+  for (len = std::min(pos1, pos2); len > 0; --len) {
     const nsINode* child1 = parents1.ElementAt(--pos1);
     const nsINode* child2 = parents2.ElementAt(--pos2);
     if (child1 != child2) {
       // child1 or child2 can be an attribute here. This will work fine since
       // IndexOf will return -1 for the attribute making the attribute be
       // considered before any child.
       return parent->IndexOf(child1) < parent->IndexOf(child2) ?
         static_cast<uint16_t>(nsIDOMNode::DOCUMENT_POSITION_PRECEDING) :
--- a/content/base/src/nsSyncLoadService.cpp
+++ b/content/base/src/nsSyncLoadService.cpp
@@ -19,16 +19,17 @@
 #include "nsIDOMDocument.h"
 #include "nsIPrincipal.h"
 #include "nsContentUtils.h"
 #include "nsThreadUtils.h"
 #include "nsNetUtil.h"
 #include "nsAutoPtr.h"
 #include "nsStreamUtils.h"
 #include "nsCrossSiteListenerProxy.h"
+#include <algorithm>
 
 /**
  * This class manages loading a single XML document
  */
 
 class nsSyncLoader : public nsIStreamListener,
                      public nsIChannelEventSink,
                      public nsIInterfaceRequestor,
@@ -337,17 +338,17 @@ nsSyncLoadService::PushSyncStreamToListe
     nsresult rv;
     nsCOMPtr<nsIInputStream> bufferedStream;
     if (!NS_InputStreamIsBuffered(aIn)) {
         int64_t chunkSize;
         rv = aChannel->GetContentLength(&chunkSize);
         if (NS_FAILED(rv)) {
             chunkSize = 4096;
         }
-        chunkSize = NS_MIN(int64_t(UINT16_MAX), chunkSize);
+        chunkSize = std::min(int64_t(UINT16_MAX), chunkSize);
 
         rv = NS_NewBufferedInputStream(getter_AddRefs(bufferedStream), aIn,
                                        chunkSize);
         NS_ENSURE_SUCCESS(rv, rv);
 
         aIn = bufferedStream;
     }
 
@@ -365,17 +366,17 @@ nsSyncLoadService::PushSyncStreamToListe
                 }
                 break;
             }
 
             if (readCount > UINT32_MAX)
                 readCount = UINT32_MAX;
 
             rv = aListener->OnDataAvailable(aChannel, nullptr, aIn,
-                                            (uint32_t)NS_MIN(sourceOffset, (uint64_t)UINT32_MAX),
+                                            (uint32_t)std::min(sourceOffset, (uint64_t)UINT32_MAX),
                                             (uint32_t)readCount);
             if (NS_FAILED(rv)) {
                 break;
             }
             sourceOffset += readCount;
         }
     }
     if (NS_FAILED(rv)) {
--- a/content/base/src/nsTextFragment.cpp
+++ b/content/base/src/nsTextFragment.cpp
@@ -13,16 +13,17 @@
 #include "nsCRT.h"
 #include "nsReadableUtils.h"
 #include "nsMemory.h"
 #include "nsBidiUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsUTF8Utils.h"
 #include "mozilla/SSE.h"
 #include "nsTextFragmentImpl.h"
+#include <algorithm>
 
 #define TEXTFRAG_WHITE_AFTER_NEWLINE 50
 #define TEXTFRAG_MAX_NEWLINES 7
 
 // Static buffer used for common fragments
 static char* sSpaceSharedString[TEXTFRAG_MAX_NEWLINES + 1];
 static char* sTabSharedString[TEXTFRAG_MAX_NEWLINES + 1];
 static char sSingleCharSharedString[256];
@@ -122,17 +123,17 @@ FirstNon8BitUnvectorized(const PRUnichar
   const size_t mask = p::mask();
   const uint32_t alignMask = p::alignMask();
   const uint32_t numUnicharsPerWord = p::numUnicharsPerWord();
   const int32_t len = end - str;
   int32_t i = 0;
 
   // Align ourselves to a word boundary.
   int32_t alignLen =
-    NS_MIN(len, int32_t(((-NS_PTR_TO_INT32(str)) & alignMask) / sizeof(PRUnichar)));
+    std::min(len, int32_t(((-NS_PTR_TO_INT32(str)) & alignMask) / sizeof(PRUnichar)));
   for (; i < alignLen; i++) {
     if (str[i] > 255)
       return i;
   }
 
   // Check one word at a time.
   const int32_t wordWalkEnd = ((len - i) / numUnicharsPerWord) * numUnicharsPerWord;
   for (; i < wordWalkEnd; i += numUnicharsPerWord) {
--- a/content/base/src/nsTextFragmentSSE2.cpp
+++ b/content/base/src/nsTextFragmentSSE2.cpp
@@ -4,16 +4,17 @@
 
 // This file should only be compiled if you're on x86 or x86_64.  Additionally,
 // you'll need to compile this file with -msse2 if you're using gcc.
 
 #include <emmintrin.h>
 #include "nscore.h"
 #include "nsAlgorithm.h"
 #include "nsTextFragmentImpl.h"
+#include <algorithm>
 
 namespace mozilla {
 namespace SSE2 {
 
 static inline bool
 is_zero (__m128i x)
 {
   return
@@ -28,17 +29,17 @@ FirstNon8Bit(const PRUnichar *str, const
   const size_t mask = p::mask();
   const uint32_t numUnicharsPerWord = p::numUnicharsPerWord();
   const int32_t len = end - str;
   int32_t i = 0;
 
   // Align ourselves to a 16-byte boundary, as required by _mm_load_si128
   // (i.e. MOVDQA).
   int32_t alignLen =
-    NS_MIN(len, int32_t(((-NS_PTR_TO_INT32(str)) & 0xf) / sizeof(PRUnichar)));
+    std::min(len, int32_t(((-NS_PTR_TO_INT32(str)) & 0xf) / sizeof(PRUnichar)));
   for (; i < alignLen; i++) {
     if (str[i] > 255)
       return i;
   }
 
   // Check one XMM register (16 bytes) at a time.
   const int32_t vectWalkEnd = ((len - i) / numUnicharsPerVector) * numUnicharsPerVector;
   __m128i vectmask = _mm_set1_epi16(0xff00);
--- a/content/base/src/nsViewportInfo.cpp
+++ b/content/base/src/nsViewportInfo.cpp
@@ -1,23 +1,24 @@
 /* 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 "nsViewportInfo.h"
+#include <algorithm>
 
 void
 nsViewportInfo::SetDefaultZoom(const double aDefaultZoom)
 {
   MOZ_ASSERT(aDefaultZoom >= 0.0f);
   mDefaultZoom = aDefaultZoom;
 }
 
 void
 nsViewportInfo::ConstrainViewportValues()
 {
   // Constrain the min/max zoom as specified at:
   // dev.w3.org/csswg/css-device-adapt section 6.2
-  mMaxZoom = NS_MAX(mMinZoom, mMaxZoom);
+  mMaxZoom = std::max(mMinZoom, mMaxZoom);
 
-  mDefaultZoom = NS_MIN(mDefaultZoom, mMaxZoom);
-  mDefaultZoom = NS_MAX(mDefaultZoom, mMinZoom);
+  mDefaultZoom = std::min(mDefaultZoom, mMaxZoom);
+  mDefaultZoom = std::max(mDefaultZoom, mMinZoom);
 }
--- a/content/canvas/src/CanvasRenderingContext2D.cpp
+++ b/content/canvas/src/CanvasRenderingContext2D.cpp
@@ -297,20 +297,20 @@ public:
 
     mTempRect = mgfx::Rect(0, 0, ctx->mWidth, ctx->mHeight);
 
     static const gfxFloat GAUSSIAN_SCALE_FACTOR = (3 * sqrt(2 * M_PI) / 4) * 1.5;
     int32_t blurRadius = (int32_t) floor(mSigma * GAUSSIAN_SCALE_FACTOR + 0.5);
 
     // We need to enlarge and possibly offset our temporary surface
     // so that things outside of the canvas may cast shadows.
-    mTempRect.Inflate(Margin(blurRadius + NS_MAX<Float>(state.shadowOffset.x, 0),
-                             blurRadius + NS_MAX<Float>(state.shadowOffset.y, 0),
-                             blurRadius + NS_MAX<Float>(-state.shadowOffset.x, 0),
-                             blurRadius + NS_MAX<Float>(-state.shadowOffset.y, 0)));
+    mTempRect.Inflate(Margin(blurRadius + std::max<Float>(state.shadowOffset.x, 0),
+                             blurRadius + std::max<Float>(state.shadowOffset.y, 0),
+                             blurRadius + std::max<Float>(-state.shadowOffset.x, 0),
+                             blurRadius + std::max<Float>(-state.shadowOffset.y, 0)));
 
     if (aBounds) {
       // We actually include the bounds of the shadow blur, this makes it
       // easier to execute the actual blur on hardware, and shouldn't affect
       // the amount of pixels that need to be touched.
       aBounds->Inflate(Margin(blurRadius, blurRadius,
                               blurRadius, blurRadius));
       mTempRect = mTempRect.Intersect(*aBounds);
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -18,16 +18,17 @@
 #include "nsLayoutUtils.h"
 
 #include "CanvasUtils.h"
 
 #include "jsfriendapi.h"
 
 #include "WebGLTexelConversions.h"
 #include "WebGLValidateStrings.h"
+#include <algorithm>
 
 // needed to check if current OS is lower than 10.7
 #if defined(MOZ_WIDGET_COCOA)
 #include "nsCocoaFeatures.h"
 #endif
 
 #include "mozilla/dom/BindingUtils.h"
 
@@ -3278,22 +3279,22 @@ WebGLContext::ReadPixels(WebGLint x, Web
             || y >= framebufferHeight
             || y+height <= 0)
         {
             // we are completely outside of range, can exit now with buffer filled with zeros
             return DummyFramebufferOperation("readPixels");
         }
 
         // compute the parameters of the subrect we're actually going to call glReadPixels on
-        GLint   subrect_x      = NS_MAX(x, 0);
-        GLint   subrect_end_x  = NS_MIN(x+width, framebufferWidth);
+        GLint   subrect_x      = std::max(x, 0);
+        GLint   subrect_end_x  = std::min(x+width, framebufferWidth);
         GLsizei subrect_width  = subrect_end_x - subrect_x;
 
-        GLint   subrect_y      = NS_MAX(y, 0);
-        GLint   subrect_end_y  = NS_MIN(y+height, framebufferHeight);
+        GLint   subrect_y      = std::max(y, 0);
+        GLint   subrect_end_y  = std::min(y+height, framebufferHeight);
         GLsizei subrect_height = subrect_end_y - subrect_y;
 
         if (subrect_width < 0 || subrect_height < 0 ||
             subrect_width > width || subrect_height > height)
             return ErrorInvalidOperation("readPixels: integer overflow computing clipped rect size");
 
         // now we know that subrect_width is in the [0..width] interval, and same for heights.
 
--- a/content/canvas/src/WebGLContextValidate.cpp
+++ b/content/canvas/src/WebGLContextValidate.cpp
@@ -28,17 +28,17 @@ WebGLProgram::UpdateInfo()
 {
     mIdentifierMap = nullptr;
     mIdentifierReverseMap = nullptr;
     mUniformInfoMap = nullptr;
 
     mAttribMaxNameLength = 0;
 
     for (size_t i = 0; i < mAttachedShaders.Length(); i++)
-        mAttribMaxNameLength = NS_MAX(mAttribMaxNameLength, mAttachedShaders[i]->mAttribMaxNameLength);
+        mAttribMaxNameLength = std::max(mAttribMaxNameLength, mAttachedShaders[i]->mAttribMaxNameLength);
 
     GLint attribCount;
     mContext->gl->fGetProgramiv(mGLName, LOCAL_GL_ACTIVE_ATTRIBUTES, &attribCount);
 
     if (!mAttribsInUse.SetLength(mContext->mGLMaxVertexAttribs)) {
         mContext->ErrorOutOfMemory("updateInfo: out of memory to allocate %d attribs", mContext->mGLMaxVertexAttribs);
         return false;
     }
@@ -406,23 +406,23 @@ bool WebGLContext::ValidateCompressedTex
         case LOCAL_GL_ATC_RGBA_INTERPOLATED_ALPHA:
         {
             required_byteLength = ((CheckedUint32(width) + 3) / 4) * ((CheckedUint32(height) + 3) / 4) * 16;
             break;
         }
         case LOCAL_GL_COMPRESSED_RGB_PVRTC_4BPPV1:
         case LOCAL_GL_COMPRESSED_RGBA_PVRTC_4BPPV1:
         {
-            required_byteLength = CheckedUint32(NS_MAX(width, 8)) * CheckedUint32(NS_MAX(height, 8)) / 2;
+            required_byteLength = CheckedUint32(std::max(width, 8)) * CheckedUint32(std::max(height, 8)) / 2;
             break;
         }
         case LOCAL_GL_COMPRESSED_RGB_PVRTC_2BPPV1:
         case LOCAL_GL_COMPRESSED_RGBA_PVRTC_2BPPV1:
         {
-            required_byteLength = CheckedUint32(NS_MAX(width, 16)) * CheckedUint32(NS_MAX(height, 8)) / 4;
+            required_byteLength = CheckedUint32(std::max(width, 16)) * CheckedUint32(std::max(height, 8)) / 4;
             break;
         }
     }
 
     if (!required_byteLength.isValid() || required_byteLength.value() != byteLength) {
         ErrorInvalidValue("%s: data size does not match dimensions", info);
         return false;
     }
@@ -736,17 +736,17 @@ WebGLContext::ValidateUniformArraySetter
         ErrorInvalidOperation("%s: expected an array of length exactly"
                               " %d (since this uniform is not an array"
                               " uniform), got an array of length %d", name,
                               expectedElemSize,
                               arrayLength);
         return false;
     }
     numElementsToUpload =
-        NS_MIN(info.arraySize, arrayLength / expectedElemSize);
+        std::min(info.arraySize, arrayLength / expectedElemSize);
     return true;
 }
 
 bool
 WebGLContext::ValidateUniformMatrixArraySetter(const char* name, int dim, WebGLUniformLocation *location_object,
                                               GLint& location, uint32_t& numElementsToUpload, uint32_t arrayLength,
                                               WebGLboolean aTranspose)
 {
@@ -787,17 +787,17 @@ WebGLContext::ValidateUniformMatrixArray
         return false;
     }
     if (aTranspose) {
         ErrorInvalidValue("%s: transpose must be FALSE as per the "
                           "OpenGL ES 2.0 spec", name);
         return false;
     }
     numElementsToUpload =
-        NS_MIN(info.arraySize, arrayLength / (expectedElemSize));
+        std::min(info.arraySize, arrayLength / (expectedElemSize));
     return true;
 }
 
 bool
 WebGLContext::ValidateUniformSetter(const char* name, WebGLUniformLocation *location_object, GLint& location)
 {
     if (!IsContextStable())
         return false;
@@ -955,17 +955,17 @@ WebGLContext::InitAndValidateGL()
             GLint maxVertexOutputComponents,
                   minFragmentInputComponents;
             gl->fGetIntegerv(LOCAL_GL_MAX_VERTEX_OUTPUT_COMPONENTS, &maxVertexOutputComponents);
             gl->fGetIntegerv(LOCAL_GL_MAX_FRAGMENT_INPUT_COMPONENTS, &minFragmentInputComponents);
 
             error = gl->GetAndClearError();
             switch (error) {
                 case LOCAL_GL_NO_ERROR:
-                    mGLMaxVaryingVectors = NS_MIN(maxVertexOutputComponents, minFragmentInputComponents) / 4;
+                    mGLMaxVaryingVectors = std::min(maxVertexOutputComponents, minFragmentInputComponents) / 4;
                     break;
                 case LOCAL_GL_INVALID_ENUM:
                     mGLMaxVaryingVectors = 16; // = 64/4, 64 is the min value for maxVertexOutputComponents in OpenGL 3.2 spec
                     break;
                 default:
                     GenerateWarning("GL error 0x%x occurred during WebGL context initialization!", error);
                     return false;
             }   
--- a/content/canvas/src/WebGLElementArrayCache.cpp
+++ b/content/canvas/src/WebGLElementArrayCache.cpp
@@ -6,16 +6,17 @@
 #include "WebGLElementArrayCache.h"
 
 #include "nsTArray.h"
 #include "mozilla/Assertions.h"
 
 #include <cstdlib>
 #include <cstring>
 #include <limits>
+#include <algorithm>
 
 namespace mozilla {
 
 /*
  * WebGLElementArrayCacheTree contains most of the implementation of WebGLElementArrayCache,
  * which performs WebGL element array buffer validation for drawElements.
  *
  * Attention: Here lie nontrivial data structures, bug-prone algorithms, and non-canonical tweaks!
@@ -328,27 +329,27 @@ struct TreeForType<uint16_t>
   static WebGLElementArrayCacheTree<uint16_t>*& Run(WebGLElementArrayCache *b) { return b->mUint16Tree; }
 };
 
 // When the buffer gets updated from firstByte to lastByte,
 // calling this method will notify the tree accordingly
 template<typename T>
 void WebGLElementArrayCacheTree<T>::Invalidate(size_t firstByte, size_t lastByte)
 {
-  lastByte = NS_MIN(lastByte, mNumLeaves * sElementsPerLeaf * sizeof(T) - 1);
+  lastByte = std::min(lastByte, mNumLeaves * sElementsPerLeaf * sizeof(T) - 1);
   if (firstByte > lastByte) {
     return;
   }
 
   size_t firstLeaf = LeafForByte(firstByte);
   size_t lastLeaf = LeafForByte(lastByte);
 
   if (mInvalidated) {
-    mFirstInvalidatedLeaf = NS_MIN(firstLeaf, mFirstInvalidatedLeaf);
-    mLastInvalidatedLeaf = NS_MAX(lastLeaf, mLastInvalidatedLeaf);
+    mFirstInvalidatedLeaf = std::min(firstLeaf, mFirstInvalidatedLeaf);
+    mLastInvalidatedLeaf = std::max(lastLeaf, mLastInvalidatedLeaf);
   } else {
     mInvalidated = true;
     mFirstInvalidatedLeaf = firstLeaf;
     mLastInvalidatedLeaf = lastLeaf;
   }
 }
 
 
@@ -375,36 +376,36 @@ void WebGLElementArrayCacheTree<T>::Upda
     // treeIndex is the index of the tree leaf we're writing, i.e. the destination index
     size_t treeIndex = firstTreeIndex;
     // srcIndex is the index in the source buffer
     size_t srcIndex = mFirstInvalidatedLeaf * sElementsPerLeaf;
     size_t numberOfElements = mParent.ByteSize() / sizeof(T);
     while (treeIndex <= lastTreeIndex) {
       T m = 0;
       size_t a = srcIndex;
-      size_t srcIndexNextLeaf = NS_MIN(a + sElementsPerLeaf, numberOfElements);
+      size_t srcIndexNextLeaf = std::min(a + sElementsPerLeaf, numberOfElements);
       for (; srcIndex < srcIndexNextLeaf; srcIndex++) {
-        m = NS_MAX(m, mParent.Element<T>(srcIndex));
+        m = std::max(m, mParent.Element<T>(srcIndex));
       }
       mTreeData[treeIndex] = m;
       treeIndex++;
     }
   }
 
   // Step #2: propagate the values up the tree. This is simply a matter of walking up
   // the tree and setting each node to the max of its two children.
   while (firstTreeIndex > 1) {
 
     // move up 1 level
     firstTreeIndex = ParentNode(firstTreeIndex);
     lastTreeIndex = ParentNode(lastTreeIndex);
 
     // fast-exit case where only one node is invalidated at the current level
     if (firstTreeIndex == lastTreeIndex) {
-      mTreeData[firstTreeIndex] = NS_MAX(mTreeData[LeftChildNode(firstTreeIndex)], mTreeData[RightChildNode(firstTreeIndex)]);
+      mTreeData[firstTreeIndex] = std::max(mTreeData[LeftChildNode(firstTreeIndex)], mTreeData[RightChildNode(firstTreeIndex)]);
       continue;
     }
 
     // initialize local iteration variables: child and parent.
     size_t child = LeftChildNode(firstTreeIndex);
     size_t parent = firstTreeIndex;
 
     // the unrolling makes this look more complicated than it is; the plain non-unrolled
@@ -413,28 +414,28 @@ void WebGLElementArrayCacheTree<T>::Upda
     while (RightNeighborNode(parent, unrollSize - 1) <= lastTreeIndex)
     {
       for (int unroll = 0; unroll < unrollSize; unroll++)
       {
         T a = mTreeData[child];
         child = RightNeighborNode(child);
         T b = mTreeData[child];
         child = RightNeighborNode(child);
-        mTreeData[parent] = NS_MAX(a, b);
+        mTreeData[parent] = std::max(a, b);
         parent = RightNeighborNode(parent);
       }
     }
     // plain non-unrolled version, used to terminate the job after the last unrolled iteration
     while (parent <= lastTreeIndex)
     {
       T a = mTreeData[child];
       child = RightNeighborNode(child);
       T b = mTreeData[child];
       child = RightNeighborNode(child);
-      mTreeData[parent] = NS_MAX(a, b);
+      mTreeData[parent] = std::max(a, b);
       parent = RightNeighborNode(parent);
     }
   }
 
   mInvalidated = false;
 }
 
 WebGLElementArrayCache::~WebGLElementArrayCache() {
@@ -505,24 +506,24 @@ bool WebGLElementArrayCache::Validate(ui
   {
     return true;
   }
 
   const T* elements = Elements<T>();
 
   // before calling tree->Validate, we have to validate ourselves the boundaries of the elements span,
   // to round them to the nearest multiple of sElementsPerLeaf.
-  size_t firstElementAdjustmentEnd = NS_MIN(lastElement,
+  size_t firstElementAdjustmentEnd = std::min(lastElement,
                                             tree->LastElementUnderSameLeaf(firstElement));
   while (firstElement <= firstElementAdjustmentEnd) {
     if (elements[firstElement] > maxAllowedT)
       return false;
     firstElement++;
   }
-  size_t lastElementAdjustmentEnd = NS_MAX(firstElement,
+  size_t lastElementAdjustmentEnd = std::max(firstElement,
                                            tree->FirstElementUnderSameLeaf(lastElement));
   while (lastElement >= lastElementAdjustmentEnd) {
     if (elements[lastElement] > maxAllowedT)
       return false;
     lastElement--;
   }
 
   // at this point, for many tiny validations, we're already done.
--- a/content/canvas/src/WebGLTexture.cpp
+++ b/content/canvas/src/WebGLTexture.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 "WebGLContext.h"
 #include "WebGLTexture.h"
 #include "mozilla/dom/WebGLRenderingContextBinding.h"
+#include <algorithm>
 
 using namespace mozilla;
 
 JSObject*
 WebGLTexture::WrapObject(JSContext *cx, JSObject *scope, bool *triedToWrap) {
     return dom::WebGLTextureBinding::Wrap(cx, scope, this, triedToWrap);
 }
 
@@ -76,18 +77,18 @@ WebGLTexture::DoesTexture2DMipmapHaveAll
     ImageInfo expected = ImageInfoAt(0, face);
 
     // checks if custom level>0 images are all defined up to the highest level defined
     // and have the expected dimensions
     for (size_t level = 0; level <= mMaxLevelWithCustomImages; ++level) {
         const ImageInfo& actual = ImageInfoAt(level, face);
         if (actual != expected)
             return false;
-        expected.mWidth = NS_MAX(1, expected.mWidth >> 1);
-        expected.mHeight = NS_MAX(1, expected.mHeight >> 1);
+        expected.mWidth = std::max(1, expected.mWidth >> 1);
+        expected.mHeight = std::max(1, expected.mHeight >> 1);
 
         // if the current level has size 1x1, we can stop here: the spec doesn't seem to forbid the existence
         // of extra useless levels.
         if (actual.mWidth == 1 && actual.mHeight == 1)
             return true;
     }
 
     // if we're here, we've exhausted all levels without finding a 1x1 image
@@ -167,17 +168,17 @@ WebGLTexture::SetCustomMipmap() {
         // if we were in GeneratedMipmap mode and are now switching to CustomMipmap mode,
         // we need to compute now all the mipmap image info.
 
         // since we were in GeneratedMipmap mode, we know that the level 0 images all have the same info,
         // and are power-of-two.
         ImageInfo imageInfo = ImageInfoAt(0, 0);
         NS_ASSERTION(imageInfo.IsPowerOfTwo(), "this texture is NPOT, so how could GenerateMipmap() ever accept it?");
 
-        WebGLsizei size = NS_MAX(imageInfo.mWidth, imageInfo.mHeight);
+        WebGLsizei size = std::max(imageInfo.mWidth, imageInfo.mHeight);
 
         // so, the size is a power of two, let's find its log in base 2.
         size_t maxLevel = 0;
         for (WebGLsizei n = size; n > 1; n >>= 1)
             ++maxLevel;
 
         EnsureMaxLevelWithCustomImagesAtLeast(maxLevel);
 
--- a/content/canvas/src/WebGLTexture.h
+++ b/content/canvas/src/WebGLTexture.h
@@ -8,16 +8,17 @@
 
 #include "WebGLObjectModel.h"
 #include "WebGLRenderbuffer.h"
 
 #include "nsWrapperCache.h"
 
 #include "mozilla/LinkedList.h"
 #include "mozilla/CheckedInt.h"
+#include <algorithm>
 
 namespace mozilla {
 
 enum FakeBlackStatus { DoNotNeedFakeBlack, DoNeedFakeBlack, DontKnowIfNeedFakeBlack };
 
 // Zero is not an integer power of two.
 inline bool is_pot_assuming_nonnegative(WebGLsizei x)
 {
@@ -148,17 +149,17 @@ protected:
 
     size_t mFacesCount, mMaxLevelWithCustomImages;
     nsTArray<ImageInfo> mImageInfos;
 
     bool mHaveGeneratedMipmap;
     FakeBlackStatus mFakeBlackStatus;
 
     void EnsureMaxLevelWithCustomImagesAtLeast(size_t aMaxLevelWithCustomImages) {
-        mMaxLevelWithCustomImages = NS_MAX(mMaxLevelWithCustomImages, aMaxLevelWithCustomImages);
+        mMaxLevelWithCustomImages = std::max(mMaxLevelWithCustomImages, aMaxLevelWithCustomImages);
         mImageInfos.EnsureLengthAtLeast((mMaxLevelWithCustomImages + 1) * mFacesCount);
     }
 
     bool CheckFloatTextureFilterParams() const {
         // Without OES_texture_float_linear, only NEAREST and NEAREST_MIMPAMP_NEAREST are supported
         return (mMagFilter == LOCAL_GL_NEAREST) &&
             (mMinFilter == LOCAL_GL_NEAREST || mMinFilter == LOCAL_GL_NEAREST_MIPMAP_NEAREST);
     }
--- a/content/events/src/nsContentEventHandler.cpp
+++ b/content/events/src/nsContentEventHandler.cpp
@@ -22,16 +22,17 @@
 #include "nsTextFrame.h"
 #include "nsISelectionController.h"
 #include "nsISelectionPrivate.h"
 #include "nsContentUtils.h"
 #include "nsLayoutUtils.h"
 #include "nsIMEStateManager.h"
 #include "nsIObjectFrame.h"
 #include "mozilla/dom/Element.h"
+#include <algorithm>
 
 using namespace mozilla::dom;
 
 /******************************************************************/
 /* nsContentEventHandler                                          */
 /******************************************************************/
 
 nsContentEventHandler::nsContentEventHandler(
@@ -181,17 +182,17 @@ static uint32_t CountNewlinesInXPLength(
                "aContent is not a text node!");
   const nsTextFragment* text = aContent->GetText();
   if (!text)
     return 0;
   // For automated tests, we should abort on debug build.
   NS_ABORT_IF_FALSE(
     (aXPLength == UINT32_MAX || aXPLength <= text->GetLength()),
     "aXPLength is out-of-bounds");
-  const uint32_t length = NS_MIN(aXPLength, text->GetLength());
+  const uint32_t length = std::min(aXPLength, text->GetLength());
   uint32_t newlines = 0;
   for (uint32_t i = 0; i < length; ++i) {
     if (text->CharAt(i) == '\n') {
       ++newlines;
     }
   }
   return newlines;
 }
@@ -242,17 +243,17 @@ nsContentEventHandler::GetNativeTextLeng
 #else
       // On other platforms, the native and XP newlines are the same.
       0;
 #endif
 
     const nsTextFragment* text = aContent->GetText();
     if (!text)
       return 0;
-    uint32_t length = NS_MIN(text->GetLength(), aMaxLength);
+    uint32_t length = std::min(text->GetLength(), aMaxLength);
     return length + textLengthDifference;
   } else if (IsContentBR(aContent)) {
 #if defined(XP_WIN)
     // Length of \r\n
     return 2;
 #else
     return 1;
 #endif
@@ -1005,17 +1006,17 @@ static void AdjustRangeForSelection(nsIC
   
   nsIContent* brContent = node->GetChildAt(offset - 1);
   while (brContent && brContent->IsHTML()) {
     if (brContent->Tag() != nsGkAtoms::br || IsContentBR(brContent))
       break;
     brContent = node->GetChildAt(--offset - 1);
   }
   *aNode = node;
-  *aOffset = NS_MAX(offset, 0);
+  *aOffset = std::max(offset, 0);
 }
 
 nsresult
 nsContentEventHandler::OnSelectionEvent(nsSelectionEvent* aEvent)
 {
   aEvent->mSucceeded = false;
 
   // Get selection to manipulate
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -32,16 +32,17 @@
 #include "nsFrameSelection.h"
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
 #include "nsIEnumerator.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocShellTreeNode.h"
 #include "nsIWebNavigation.h"
 #include "nsIContentViewer.h"
+#include <algorithm>
 #ifdef MOZ_XUL
 #include "nsXULPopupManager.h"
 #endif
 #include "nsFrameManager.h"
 
 #include "nsIServiceManager.h"
 #include "nsIScriptSecurityManager.h"
 
@@ -3842,17 +3843,17 @@ nsEventStateManager::SetCursor(int32_t a
     // css3-ui says to use the CSS-specified hotspot if present,
     // otherwise use the intrinsic hotspot, otherwise use the top left
     // corner.
     if (aHaveHotspot) {
       int32_t imgWidth, imgHeight;
       aContainer->GetWidth(&imgWidth);
       aContainer->GetHeight(&imgHeight);
 
-      // XXX NS_MAX(NS_lround(x), 0)?
+      // XXX std::max(NS_lround(x), 0)?
       hotspotX = aHotspotX > 0.0f
                    ? uint32_t(aHotspotX + 0.5f) : uint32_t(0);
       if (hotspotX >= uint32_t(imgWidth))
         hotspotX = imgWidth - 1;
       hotspotY = aHotspotY > 0.0f
                    ? uint32_t(aHotspotY + 0.5f) : uint32_t(0);
       if (hotspotY >= uint32_t(imgHeight))
         hotspotY = imgHeight - 1;
--- a/content/html/content/src/nsHTMLAudioElement.cpp
+++ b/content/html/content/src/nsHTMLAudioElement.cpp
@@ -9,16 +9,17 @@
 #include "nsGenericHTMLElement.h"
 #include "nsGkAtoms.h"
 #include "nsIDocument.h"
 #include "jsfriendapi.h"
 #include "nsContentUtils.h"
 #include "nsJSUtils.h"
 #include "AudioSampleFormat.h"
 #include "AudioChannelCommon.h"
+#include <algorithm>
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 nsGenericHTMLElement*
 NS_NewHTMLAudioElement(already_AddRefed<nsINodeInfo> aNodeInfo,
                        FromParser aFromParser)
 {
@@ -161,17 +162,17 @@ nsHTMLAudioElement::MozWriteAudio(const 
 
   // Make sure that we are going to write the correct amount of data based
   // on number of channels.
   if (dataLength % mChannels != 0) {
     return NS_ERROR_DOM_INDEX_SIZE_ERR;
   }
 
   // Don't write more than can be written without blocking.
-  uint32_t writeLen = NS_MIN(mAudioStream->Available(), dataLength / mChannels);
+  uint32_t writeLen = std::min(mAudioStream->Available(), dataLength / mChannels);
 
   float* frames = JS_GetFloat32ArrayData(tsrc);
   // Convert the samples back to integers as we are using fixed point audio in
   // the AudioStream.
   // This could be optimized to avoid allocation and memcpy when
   // AudioDataValue is 'float', but it's not worth it for this deprecated API.
   nsAutoArrayPtr<AudioDataValue> audioData(new AudioDataValue[writeLen * mChannels]);
   ConvertAudioSamples(frames, audioData.get(), writeLen * mChannels);
--- a/content/html/content/src/nsHTMLInputElement.cpp
+++ b/content/html/content/src/nsHTMLInputElement.cpp
@@ -55,16 +55,17 @@
 #include "nsLayoutUtils.h"
 
 #include "nsIDOMMutationEvent.h"
 #include "nsIDOMEventTarget.h"
 #include "nsMutationEvent.h"
 #include "nsEventListenerManager.h"
 
 #include "nsRuleData.h"
+#include <algorithm>
 
 // input type=radio
 #include "nsIRadioGroupContainer.h"
 
 // input type=file
 #include "nsIFile.h"
 #include "nsNetUtil.h"
 #include "nsDOMFile.h"
@@ -1500,20 +1501,20 @@ nsHTMLInputElement::ApplyStep(int32_t aS
     value = min;
   // Same goes for stepDown() and max.
   } else if (GetValidityState(VALIDITY_STATE_RANGE_OVERFLOW) && aStep < 0 &&
              value >= max) {
     MOZ_ASSERT(!MOZ_DOUBLE_IS_NaN(max)); // max can't be NaN if we are here!
     value = max;
   // If we go down, we want to clamp on min.
   } else if (aStep < 0 && min == min) {
-    value = NS_MAX(value, min);
+    value = std::max(value, min);
   // If we go up, we want to clamp on max.
   } else if (aStep > 0 && max == max) {
-    value = NS_MIN(value, max);
+    value = std::min(value, max);
   }
 
   SetValue(value);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -71,16 +71,17 @@
 
 #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
 #ifdef MOZ_WEBM
@@ -1307,20 +1308,20 @@ NS_IMETHODIMP nsHTMLMediaElement::SetCur
 
   // Detect for a NaN and invalid values.
   if (aCurrentTime != aCurrentTime) {
     LOG(PR_LOG_DEBUG, ("%p SetCurrentTime(%f) failed: bad time", this, aCurrentTime));
     return NS_ERROR_FAILURE;
   }
 
   // Clamp the time to [0, duration] as required by the spec.
-  double clampedTime = NS_MAX(0.0, aCurrentTime);
+  double clampedTime = std::max(0.0, aCurrentTime);
   double duration = mDecoder->GetDuration();
   if (duration >= 0) {
-    clampedTime = NS_MIN(clampedTime, duration);
+    clampedTime = std::min(clampedTime, duration);
   }
 
   mPlayingBeforeSeek = IsPotentiallyPlaying();
   // The media backend is responsible for dispatching the timeupdate
   // event if it changes the playback position as a result of the seek.
   LOG(PR_LOG_DEBUG, ("%p SetCurrentTime(%f) starting seek", this, aCurrentTime));
   nsresult rv = mDecoder->Seek(clampedTime);
   // Start a new range at position we seeked to.
--- a/content/html/content/src/nsHTMLMeterElement.cpp
+++ b/content/html/content/src/nsHTMLMeterElement.cpp
@@ -4,16 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsIDOMHTMLMeterElement.h"
 #include "nsGenericHTMLElement.h"
 #include "nsAttrValue.h"
 #include "nsAttrValueInlines.h"
 #include "nsEventStateManager.h"
 #include "nsAlgorithm.h"
+#include <algorithm>
 
 using namespace mozilla::dom;
 
 class nsHTMLMeterElement : public nsGenericHTMLElement,
                            public nsIDOMHTMLMeterElement
 {
 public:
   nsHTMLMeterElement(already_AddRefed<nsINodeInfo> aNodeInfo);
@@ -169,17 +170,17 @@ nsHTMLMeterElement::GetMax() const
 
   const nsAttrValue* attrMax = mAttrsAndChildren.GetAttr(nsGkAtoms::max);
   if (attrMax && attrMax->Type() == nsAttrValue::eDoubleValue) {
     max = attrMax->GetDoubleValue();
   } else {
     max = kDefaultMax;
   }
 
-  return NS_MAX(max, GetMin());
+  return std::max(max, GetMin());
 }
 
 double
 nsHTMLMeterElement::GetValue() const
 {
   /**
    * If the attribute value is defined, the actual value is this value.
    * Otherwise, the actual value is the default value.
@@ -198,17 +199,17 @@ nsHTMLMeterElement::GetValue() const
   }
 
   double min = GetMin();
 
   if (value <= min) {
     return min;
   }
 
-  return NS_MIN(value, GetMax());
+  return std::min(value, GetMax());
 }
 
 double
 nsHTMLMeterElement::GetLow() const
 {
   /**
    * If the low value is defined, the low value is this value.
    * Otherwise, the low value is the minimum value.
@@ -226,17 +227,17 @@ nsHTMLMeterElement::GetLow() const
   }
 
   double low = attrLow->GetDoubleValue();
 
   if (low <= min) {
     return min;
   }
 
-  return NS_MIN(low, GetMax());
+  return std::min(low, GetMax());
 }
 
 double
 nsHTMLMeterElement::GetHigh() const
 {
   /**
    * If the high value is defined, the high value is this value.
    * Otherwise, the high value is the maximum value.
@@ -254,17 +255,17 @@ nsHTMLMeterElement::GetHigh() const
   }
 
   double high = attrHigh->GetDoubleValue();
 
   if (high >= max) {
     return max;
   }
 
-  return NS_MAX(high, GetLow());
+  return std::max(high, GetLow());
 }
 
 double
 nsHTMLMeterElement::GetOptimum() const
 {
   /**
    * If the optimum value is defined, the optimum value is this value.
    * Otherwise, the optimum value is the midpoint between
@@ -287,17 +288,17 @@ nsHTMLMeterElement::GetOptimum() const
   }
 
   double optimum = attrOptimum->GetDoubleValue();
 
   if (optimum <= min) {
     return min;
   }
 
-  return NS_MIN(optimum, max);
+  return std::min(optimum, max);
 }
 
 /*
  * XPCOM methods
  */
 
 NS_IMETHODIMP
 nsHTMLMeterElement::GetMin(double* aValue)
--- a/content/html/content/src/nsHTMLProgressElement.cpp
+++ b/content/html/content/src/nsHTMLProgressElement.cpp
@@ -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/. */
 
 #include "nsIDOMHTMLProgressElement.h"
 #include "nsGenericHTMLElement.h"
 #include "nsAttrValue.h"
 #include "nsAttrValueInlines.h"
 #include "nsEventStateManager.h"
+#include <algorithm>
 
 using namespace mozilla::dom;
 
 class nsHTMLProgressElement : public nsGenericHTMLElement,
                               public nsIDOMHTMLProgressElement
 {
 public:
   nsHTMLProgressElement(already_AddRefed<nsINodeInfo> aNodeInfo);
@@ -128,17 +129,17 @@ nsHTMLProgressElement::GetValue(double* 
     return NS_OK;
   }
 
   *aValue = attrValue->GetDoubleValue();
 
   double max;
   GetMax(&max);
 
-  *aValue = NS_MIN(*aValue, max);
+  *aValue = std::min(*aValue, max);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLProgressElement::SetValue(double aValue)
 {
   return SetDoubleAttr(nsGkAtoms::value, aValue);
--- a/content/html/document/src/ImageDocument.cpp
+++ b/content/html/document/src/ImageDocument.cpp
@@ -37,16 +37,17 @@
 #include "nsIContentViewer.h"
 #include "nsIMarkupDocumentViewer.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsThreadUtils.h"
 #include "nsIScrollableFrame.h"
 #include "nsContentUtils.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/Preferences.h"
+#include <algorithm>
 
 #define AUTOMATIC_IMAGE_RESIZING_PREF "browser.enable_automatic_image_resizing"
 #define CLICK_IMAGE_RESIZING_PREF "browser.enable_click_image_resizing"
 //XXX A hack needed for Firefox's site specific zoom.
 #define SITE_SPECIFIC_ZOOM "browser.zoom.siteSpecific"
 
 namespace mozilla {
 namespace dom {
@@ -107,17 +108,17 @@ protected:
 
   nsresult CheckOverflowing(bool changeState);
 
   void UpdateTitleAndCharset();
 
   nsresult ScrollImageTo(int32_t aX, int32_t aY, bool restoreImage);
 
   float GetRatio() {
-    return NS_MIN((float)mVisibleWidth / mImageWidth,
+    return std::min((float)mVisibleWidth / mImageWidth,
                   (float)mVisibleHeight / mImageHeight);
   }
 
   void ResetZoomLevel();
   float GetZoomLevel();
 
   nsresult OnStartContainer(imgIRequest* aRequest, imgIContainer* aImage);
   nsresult OnStopRequest(imgIRequest *aRequest, nsresult aStatus);
@@ -410,18 +411,18 @@ ImageDocument::ShrinkToFit()
   if (GetZoomLevel() != mOriginalZoomLevel && mImageIsResized &&
       !nsContentUtils::IsChildOfSameType(this)) {
     return NS_OK;
   }
 
   // Keep image content alive while changing the attributes.
   nsCOMPtr<nsIContent> imageContent = mImageContent;
   nsCOMPtr<nsIDOMHTMLImageElement> image = do_QueryInterface(mImageContent);
-  image->SetWidth(NS_MAX(1, NSToCoordFloor(GetRatio() * mImageWidth)));
-  image->SetHeight(NS_MAX(1, NSToCoordFloor(GetRatio() * mImageHeight)));
+  image->SetWidth(std::max(1, NSToCoordFloor(GetRatio() * mImageWidth)));
+  image->SetHeight(std::max(1, NSToCoordFloor(GetRatio() * mImageHeight)));
   
   // The view might have been scrolled when zooming in, scroll back to the
   // origin now that we're showing a shrunk-to-window version.
   (void) ScrollImageTo(0, 0, false);
 
   imageContent->SetAttr(kNameSpaceID_None, nsGkAtoms::style,
                         NS_LITERAL_STRING("cursor: -moz-zoom-in"), true);
   
--- a/content/media/AudioSampleFormat.h
+++ b/content/media/AudioSampleFormat.h
@@ -2,16 +2,17 @@
 /* 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/. */
 #ifndef MOZILLA_AUDIOSAMPLEFORMAT_H_
 #define MOZILLA_AUDIOSAMPLEFORMAT_H_
 
 #include "nsAlgorithm.h"
+#include <algorithm>
 
 namespace mozilla {
 
 /**
  * Audio formats supported in MediaStreams and media elements.
  *
  * Only one of these is supported by AudioStream, and that is determined
  * at compile time (roughly, FLOAT32 on desktops, S16 on mobile). Media decoders
@@ -69,17 +70,17 @@ template <> inline float
 FloatToAudioSample<float>(float aValue)
 {
   return aValue;
 }
 template <> inline int16_t
 FloatToAudioSample<int16_t>(float aValue)
 {
   float v = aValue*32768.0f;
-  float clamped = NS_MAX(-32768.0f, NS_MIN(32767.0f, v));
+  float clamped = std::max(-32768.0f, std::min(32767.0f, v));
   return int16_t(clamped);
 }
 
 // Sample buffer conversion
 
 template <typename From, typename To> inline void
 ConvertAudioSamples(const From* aFrom, To* aTo, int aCount)
 {
--- a/content/media/AudioStream.cpp
+++ b/content/media/AudioStream.cpp
@@ -7,16 +7,17 @@
 #include <math.h>
 #include "prlog.h"
 #include "prdtoa.h"
 #include "AudioStream.h"
 #include "nsAlgorithm.h"
 #include "VideoUtils.h"
 #include "mozilla/Monitor.h"
 #include "mozilla/Mutex.h"
+#include <algorithm>
 extern "C" {
 #include "sydneyaudio/sydney_audio.h"
 }
 #include "mozilla/Preferences.h"
 
 #if defined(MOZ_CUBEB)
 #include "nsAutoRef.h"
 #include "cubeb/cubeb.h"
@@ -94,33 +95,33 @@ static int PrefChanged(const char* aPref
 {
   if (strcmp(aPref, PREF_VOLUME_SCALE) == 0) {
     nsAdoptingString value = Preferences::GetString(aPref);
     MutexAutoLock lock(*gAudioPrefsLock);
     if (value.IsEmpty()) {
       gVolumeScale = 1.0;
     } else {
       NS_ConvertUTF16toUTF8 utf8(value);
-      gVolumeScale = NS_MAX<double>(0, PR_strtod(utf8.get(), nullptr));
+      gVolumeScale = std::max<double>(0, PR_strtod(utf8.get(), nullptr));
     }
   } else if (strcmp(aPref, PREF_USE_CUBEB) == 0) {
 #ifdef MOZ_WIDGET_GONK
     bool value = Preferences::GetBool(aPref, false);
 #else
     bool value = Preferences::GetBool(aPref, true);
 #endif
     MutexAutoLock lock(*gAudioPrefsLock);
     gUseCubeb = value;
   } else if (strcmp(aPref, PREF_CUBEB_LATENCY) == 0) {
     // Arbitrary default stream latency of 100ms.  The higher this
     // value, the longer stream volume changes will take to become
     // audible.
     uint32_t value = Preferences::GetUint(aPref, 100);
     MutexAutoLock lock(*gAudioPrefsLock);
-    gCubebLatency = NS_MIN<uint32_t>(NS_MAX<uint32_t>(value, 20), 1000);
+    gCubebLatency = std::min<uint32_t>(std::max<uint32_t>(value, 20), 1000);
   }
   return 0;
 }
 
 static double GetVolumeScale()
 {
   MutexAutoLock lock(*gAudioPrefsLock);
   return gVolumeScale;
@@ -548,32 +549,32 @@ public:
   // Append aLength bytes from aSrc to the buffer.  Caller must check that
   // sufficient space is available.
   void AppendElements(const uint8_t* aSrc, uint32_t aLength) {
     NS_ABORT_IF_FALSE(mBuffer && mCapacity, "Buffer not initialized.");
     NS_ABORT_IF_FALSE(aLength <= Available(), "Buffer full.");
 
     uint32_t end = (mStart + mCount) % mCapacity;
 
-    uint32_t toCopy = NS_MIN(mCapacity - end, aLength);
+    uint32_t toCopy = std::min(mCapacity - end, aLength);
     memcpy(&mBuffer[end], aSrc, toCopy);
     memcpy(&mBuffer[0], aSrc + toCopy, aLength - toCopy);
     mCount += aLength;
   }
 
   // Remove aSize bytes from the buffer.  Caller must check returned size in
   // aSize{1,2} before using the pointer returned in aData{1,2}.  Caller
   // must not specify an aSize larger than Length().
   void PopElements(uint32_t aSize, void** aData1, uint32_t* aSize1,
                    void** aData2, uint32_t* aSize2) {
     NS_ABORT_IF_FALSE(mBuffer && mCapacity, "Buffer not initialized.");
     NS_ABORT_IF_FALSE(aSize <= Length(), "Request too large.");
 
     *aData1 = &mBuffer[mStart];
-    *aSize1 = NS_MIN(mCapacity - mStart, aSize);
+    *aSize1 = std::min(mCapacity - mStart, aSize);
     *aData2 = &mBuffer[0];
     *aSize2 = aSize - *aSize1;
     mCount -= *aSize1 + *aSize2;
     mStart += *aSize1 + *aSize2;
     mStart %= mCapacity;
   }
 
 private:
@@ -768,17 +769,17 @@ BufferedAudioStream::Write(const AudioDa
   }
   NS_ASSERTION(mState == INITIALIZED || mState == STARTED,
     "Stream write in unexpected state.");
 
   const uint8_t* src = reinterpret_cast<const uint8_t*>(aBuf);
   uint32_t bytesToCopy = FramesToBytes(aFrames);
 
   while (bytesToCopy > 0) {
-    uint32_t available = NS_MIN(bytesToCopy, mBuffer.Available());
+    uint32_t available = std::min(bytesToCopy, mBuffer.Available());
     NS_ABORT_IF_FALSE(available % mBytesPerFrame == 0,
         "Must copy complete frames.");
 
     mBuffer.AppendElements(src, available);
     src += available;
     bytesToCopy -= available;
 
     if (mState != STARTED) {
@@ -917,17 +918,17 @@ BufferedAudioStream::GetPositionInFrames
   }
 
   // Adjust the reported position by the number of silent frames written
   // during stream underruns.
   uint64_t adjustedPosition = 0;
   if (position >= mLostFrames) {
     adjustedPosition = position - mLostFrames;
   }
-  return NS_MIN<uint64_t>(adjustedPosition, INT64_MAX);
+  return std::min<uint64_t>(adjustedPosition, INT64_MAX);
 }
 
 bool
 BufferedAudioStream::IsPaused()
 {
   MonitorAutoLock mon(mMonitor);
   return mState == STOPPED;
 }
@@ -940,17 +941,17 @@ BufferedAudioStream::GetUnprocessed(void
   // Flush the timestretcher pipeline, if we were playing using a playback rate
   // other than 1.0.
   uint32_t flushedFrames = 0;
   if (mTimeStretcher && mTimeStretcher->numSamples()) {
     flushedFrames = mTimeStretcher->receiveSamples(reinterpret_cast<AudioDataValue*>(wpos), aFrames);
     wpos += FramesToBytes(flushedFrames);
   }
   uint32_t toPopBytes = FramesToBytes(aFrames - flushedFrames);
-  uint32_t available = NS_MIN(toPopBytes, mBuffer.Length());
+  uint32_t available = std::min(toPopBytes, mBuffer.Length());
 
   void* input[2];
   uint32_t input_size[2];
   mBuffer.PopElements(available, &input[0], &input_size[0], &input[1], &input_size[1]);
   memcpy(wpos, input[0], input_size[0]);
   wpos += input_size[0];
   memcpy(wpos, input[1], input_size[1]);
   return BytesToFrames(available) + flushedFrames;
@@ -968,17 +969,17 @@ BufferedAudioStream::GetTimeStretched(vo
   uint32_t toPopBytes = FramesToBytes(ceil(aFrames / playbackRate));
   uint32_t available = 0;
   bool lowOnBufferedData = false;
   do {
     // Check if we already have enough data in the time stretcher pipeline.
     if (mTimeStretcher->numSamples() <= static_cast<uint32_t>(aFrames)) {
       void* input[2];
       uint32_t input_size[2];
-      available = NS_MIN(mBuffer.Length(), toPopBytes);
+      available = std::min(mBuffer.Length(), toPopBytes);
       if (available != toPopBytes) {
         lowOnBufferedData = true;
       }
       mBuffer.PopElements(available, &input[0], &input_size[0],
                                      &input[1], &input_size[1]);
       for(uint32_t i = 0; i < 2; i++) {
         mTimeStretcher->putSamples(reinterpret_cast<AudioDataValue*>(input[i]), BytesToFrames(input_size[i]));
       }
@@ -990,17 +991,17 @@ BufferedAudioStream::GetTimeStretched(vo
 
   return processedFrames;
 }
 
 long
 BufferedAudioStream::DataCallback(void* aBuffer, long aFrames)
 {
   MonitorAutoLock mon(mMonitor);
-  uint32_t available = NS_MIN(static_cast<uint32_t>(FramesToBytes(aFrames)), mBuffer.Length());
+  uint32_t available = std::min(static_cast<uint32_t>(FramesToBytes(aFrames)), mBuffer.Length());
   NS_ABORT_IF_FALSE(available % mBytesPerFrame == 0, "Must copy complete frames");
   uint32_t underrunFrames = 0;
   uint32_t servicedFrames = 0;
 
   if (available) {
     AudioDataValue* output = reinterpret_cast<AudioDataValue*>(aBuffer);
     if (mInRate == mOutRate) {
       servicedFrames = GetUnprocessed(output, aFrames);
--- a/content/media/FileBlockCache.cpp
+++ b/content/media/FileBlockCache.cpp
@@ -2,16 +2,17 @@
 /* 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 "mozilla/XPCOM.h"
 #include "FileBlockCache.h"
 #include "VideoUtils.h"
+#include <algorithm>
 
 namespace mozilla {
 
 nsresult FileBlockCache::Open(PRFileDesc* aFD)
 {
   NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
   NS_ENSURE_TRUE(aFD != nullptr, NS_ERROR_FAILURE);
   {
@@ -242,17 +243,17 @@ nsresult FileBlockCache::Read(int64_t aO
     return NS_ERROR_FAILURE;
 
   int32_t bytesToRead = aLength;
   int64_t offset = aOffset;
   uint8_t* dst = aData;
   while (bytesToRead > 0) {
     int32_t blockIndex = static_cast<int32_t>(offset / BLOCK_SIZE);
     int32_t start = offset % BLOCK_SIZE;
-    int32_t amount = NS_MIN(BLOCK_SIZE - start, bytesToRead);
+    int32_t amount = std::min(BLOCK_SIZE - start, bytesToRead);
 
     // If the block is not yet written to file, we can just read from
     // the memory buffer, otherwise we need to read from file.
     int32_t bytesRead = 0;
     nsRefPtr<BlockChange> change = mBlockChanges[blockIndex];
     if (change && change->IsWrite()) {
       // Block isn't yet written to file. Read from memory buffer.
       const uint8_t* blockData = change->mData.get();
@@ -293,17 +294,17 @@ nsresult FileBlockCache::Read(int64_t aO
 nsresult FileBlockCache::MoveBlock(int32_t aSourceBlockIndex, int32_t aDestBlockIndex)
 {
   NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
   MonitorAutoLock mon(mDataMonitor);
 
   if (!mIsOpen)
     return NS_ERROR_FAILURE;
 
-  mBlockChanges.EnsureLengthAtLeast(NS_MAX(aSourceBlockIndex, aDestBlockIndex) + 1);
+  mBlockChanges.EnsureLengthAtLeast(std::max(aSourceBlockIndex, aDestBlockIndex) + 1);
 
   // The source block's contents may be the destination of another pending
   // move, which in turn can be the destination of another pending move,
   // etc. Resolve the final source block, so that if one of the blocks in
   // the chain of moves is overwritten, we don't lose the reference to the
   // contents of the destination block.
   int32_t sourceIndex = aSourceBlockIndex;
   BlockChange* sourceBlock = nullptr;
--- a/content/media/MediaCache.cpp
+++ b/content/media/MediaCache.cpp
@@ -14,16 +14,17 @@
 #include "nsThreadUtils.h"
 #include "MediaResource.h"
 #include "nsMathUtils.h"
 #include "prlog.h"
 #include "mozilla/Preferences.h"
 #include "FileBlockCache.h"
 #include "mozilla/Attributes.h"
 #include "nsAnonymousTemporaryFile.h"
+#include <algorithm>
 
 namespace mozilla {
 
 #ifdef PR_LOGGING
 PRLogModuleInfo* gMediaCacheLog;
 #define LOG(type, msg) PR_LOG(gMediaCacheLog, type, msg)
 #else
 #define LOG(type, msg)
@@ -638,18 +639,18 @@ MediaCache::ReadCacheFileAllBytes(int64_
 
 static int32_t GetMaxBlocks()
 {
   // We look up the cache size every time. This means dynamic changes
   // to the pref are applied.
   // Cache size is in KB
   int32_t cacheSize = Preferences::GetInt("media.cache_size", 500*1024);
   int64_t maxBlocks = static_cast<int64_t>(cacheSize)*1024/MediaCache::BLOCK_SIZE;
-  maxBlocks = NS_MAX<int64_t>(maxBlocks, 1);
-  return int32_t(NS_MIN<int64_t>(maxBlocks, INT32_MAX));
+  maxBlocks = std::max<int64_t>(maxBlocks, 1);
+  return int32_t(std::min<int64_t>(maxBlocks, INT32_MAX));
 }
 
 int32_t
 MediaCache::FindBlockForIncomingData(TimeStamp aNow,
                                        MediaCacheStream* aStream)
 {
   mReentrantMonitor.AssertCurrentThreadIn();
 
@@ -715,24 +716,24 @@ MediaCache::AppendMostReusableBlock(Bloc
 int32_t
 MediaCache::FindReusableBlock(TimeStamp aNow,
                                 MediaCacheStream* aForStream,
                                 int32_t aForStreamBlock,
                                 int32_t aMaxSearchBlockIndex)
 {
   mReentrantMonitor.AssertCurrentThreadIn();
 
-  uint32_t length = NS_MIN(uint32_t(aMaxSearchBlockIndex), mIndex.Length());
+  uint32_t length = std::min(uint32_t(aMaxSearchBlockIndex), mIndex.Length());
 
   if (aForStream && aForStreamBlock > 0 &&
       uint32_t(aForStreamBlock) <= aForStream->mBlocks.Length()) {
     int32_t prevCacheBlock = aForStream->mBlocks[aForStreamBlock - 1];
     if (prevCacheBlock >= 0) {
       uint32_t freeBlockScanEnd =
-        NS_MIN(length, prevCacheBlock + FREE_BLOCK_SCAN_LIMIT);
+        std::min(length, prevCacheBlock + FREE_BLOCK_SCAN_LIMIT);
       for (uint32_t i = prevCacheBlock; i < freeBlockScanEnd; ++i) {
         if (IsBlockFree(i))
           return i;
       }
     }
   }
 
   if (!mFreeBlocks.IsEmpty()) {
@@ -943,17 +944,17 @@ MediaCache::PredictNextUse(TimeStamp aNo
     case READAHEAD_BLOCK: {
       int64_t bytesAhead =
         static_cast<int64_t>(bo->mStreamBlock)*BLOCK_SIZE - bo->mStream->mStreamOffset;
       NS_ASSERTION(bytesAhead >= 0,
                    "Readahead block before the current stream position?");
       int64_t millisecondsAhead =
         bytesAhead*1000/bo->mStream->mPlaybackBytesPerSecond;
       prediction = TimeDuration::FromMilliseconds(
-          NS_MIN<int64_t>(millisecondsAhead, INT32_MAX));
+          std::min<int64_t>(millisecondsAhead, INT32_MAX));
       break;
     }
     default:
       NS_ERROR("Invalid class for predicting next use");
       return TimeDuration(0);
     }
     if (i == 0 || prediction < result) {
       result = prediction;
@@ -971,17 +972,17 @@ MediaCache::PredictNextUseForIncomingDat
   if (bytesAhead <= -BLOCK_SIZE) {
     // Hmm, no idea when data behind us will be used. Guess 24 hours.
     return TimeDuration::FromSeconds(24*60*60);
   }
   if (bytesAhead <= 0)
     return TimeDuration(0);
   int64_t millisecondsAhead = bytesAhead*1000/aStream->mPlaybackBytesPerSecond;
   return TimeDuration::FromMilliseconds(
-      NS_MIN<int64_t>(millisecondsAhead, INT32_MAX));
+      std::min<int64_t>(millisecondsAhead, INT32_MAX));
 }
 
 enum StreamAction { NONE, SEEK, SEEK_AND_RESUME, RESUME, SUSPEND };
 
 void
 MediaCache::Update()
 {
   NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
@@ -1021,17 +1022,17 @@ MediaCache::Update()
     for (int32_t blockIndex = mIndex.Length() - 1; blockIndex >= maxBlocks;
          --blockIndex) {
       if (IsBlockFree(blockIndex)) {
         // Don't count overflowing free blocks in our free block count
         --freeBlockCount;
         continue;
       }
       TimeDuration predictedUse = PredictNextUse(now, blockIndex);
-      latestPredictedUseForOverflow = NS_MAX(latestPredictedUseForOverflow, predictedUse);
+      latestPredictedUseForOverflow = std::max(latestPredictedUseForOverflow, predictedUse);
     }
 
     // Now try to move overflowing blocks to the main part of the cache.
     for (int32_t blockIndex = mIndex.Length() - 1; blockIndex >= maxBlocks;
          --blockIndex) {
       if (IsBlockFree(blockIndex))
         continue;
 
@@ -1557,17 +1558,17 @@ MediaCache::NoteSeek(MediaCacheStream* a
   mReentrantMonitor.AssertCurrentThreadIn();
 
   if (aOldOffset < aStream->mStreamOffset) {
     // We seeked forward. Convert blocks from readahead to played.
     // Any readahead block that intersects the seeked-over range must
     // be converted.
     int32_t blockIndex = aOldOffset/BLOCK_SIZE;
     int32_t endIndex =
-      NS_MIN<int64_t>((aStream->mStreamOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
+      std::min<int64_t>((aStream->mStreamOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
              aStream->mBlocks.Length());
     TimeStamp now = TimeStamp::Now();
     while (blockIndex < endIndex) {
       int32_t cacheBlockIndex = aStream->mBlocks[blockIndex];
       if (cacheBlockIndex >= 0) {
         // Marking the block used may not be exactly what we want but
         // it's simple
         NoteBlockUsage(aStream, cacheBlockIndex, MediaCacheStream::MODE_PLAYBACK,
@@ -1577,17 +1578,17 @@ MediaCache::NoteSeek(MediaCacheStream* a
     }
   } else {
     // We seeked backward. Convert from played to readahead.
     // Any played block that is entirely after the start of the seeked-over
     // range must be converted.
     int32_t blockIndex =
       (aStream->mStreamOffset + BLOCK_SIZE - 1)/BLOCK_SIZE;
     int32_t endIndex =
-      NS_MIN<int64_t>((aOldOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
+      std::min<int64_t>((aOldOffset + BLOCK_SIZE - 1)/BLOCK_SIZE,
              aStream->mBlocks.Length());
     while (blockIndex < endIndex) {
       int32_t cacheBlockIndex = aStream->mBlocks[endIndex - 1];
       if (cacheBlockIndex >= 0) {
         BlockOwner* bo = GetBlockOwner(cacheBlockIndex, aStream);
         NS_ASSERTION(bo, "Stream doesn't own its blocks?");
         if (bo->mClass == PLAYED_BLOCK) {
           aStream->mPlayedBlocks.RemoveBlock(cacheBlockIndex);
@@ -1621,17 +1622,17 @@ MediaCacheStream::NotifyDataStarted(int6
 
   ReentrantMonitorAutoEnter mon(gMediaCache->GetReentrantMonitor());
   NS_WARN_IF_FALSE(aOffset == mChannelOffset,
                    "Server is giving us unexpected offset");
   mChannelOffset = aOffset;
   if (mStreamLength >= 0) {
     // If we started reading at a certain offset, then for sure
     // the stream is at least that long.
-    mStreamLength = NS_MAX(mStreamLength, mChannelOffset);
+    mStreamLength = std::max(mStreamLength, mChannelOffset);
   }
   // Ensure that |mDownloadCancelled| is set to false since we have new data.
   if (mDownloadCancelled) {
     mDownloadCancelled = false;
   }
 }
 
 bool
@@ -1666,17 +1667,17 @@ MediaCacheStream::NotifyDataReceived(int
 
   LOG(PR_LOG_DEBUG, ("Stream %p DataReceived at %lld count=%lld",
       this, (long long)mChannelOffset, (long long)aSize));
 
   // We process the data one block (or part of a block) at a time
   while (size > 0) {
     uint32_t blockIndex = mChannelOffset/BLOCK_SIZE;
     int32_t blockOffset = int32_t(mChannelOffset - blockIndex*BLOCK_SIZE);
-    int32_t chunkSize = NS_MIN<int64_t>(BLOCK_SIZE - blockOffset, size);
+    int32_t chunkSize = std::min<int64_t>(BLOCK_SIZE - blockOffset, size);
 
     // This gets set to something non-null if we have a whole block
     // of data to write to the cache
     const char* blockDataToStore = nullptr;
     ReadMode mode = MODE_PLAYBACK;
     if (blockOffset == 0 && chunkSize == BLOCK_SIZE) {
       // We received a whole block, so avoid a useless copy through
       // mPartialBlockBuffer
@@ -1707,17 +1708,17 @@ MediaCacheStream::NotifyDataReceived(int
     size -= chunkSize;
     data += chunkSize;
   }
 
   MediaCache::ResourceStreamIterator iter(mResourceID);
   while (MediaCacheStream* stream = iter.Next()) {
     if (stream->mStreamLength >= 0) {
       // The stream is at least as long as what we've read
-      stream->mStreamLength = NS_MAX(stream->mStreamLength, mChannelOffset);
+      stream->mStreamLength = std::max(stream->mStreamLength, mChannelOffset);
     }
     stream->mClient->CacheClientNotifyDataReceived();
   }
 
   // Notify in case there's a waiting reader
   // XXX it would be fairly easy to optimize things a lot more to
   // avoid waking up reader threads unnecessarily
   mon.NotifyAll();
@@ -1967,19 +1968,19 @@ MediaCacheStream::GetCachedDataEndIntern
   if (blockIndex == mChannelOffset/BLOCK_SIZE) {
     // The block containing mChannelOffset may be partially read but not
     // yet committed to the main cache
     result = mChannelOffset;
   }
   if (mStreamLength >= 0) {
     // The last block in the cache may only be partially valid, so limit
     // the cached range to the stream length
-    result = NS_MIN(result, mStreamLength);
+    result = std::min(result, mStreamLength);
   }
-  return NS_MAX(result, aOffset);
+  return std::max(result, aOffset);
 }
 
 int64_t
 MediaCacheStream::GetNextCachedDataInternal(int64_t aOffset)
 {
   gMediaCache->GetReentrantMonitor().AssertCurrentThreadIn();
   if (aOffset == mStreamLength)
     return -1;
@@ -2098,28 +2099,28 @@ MediaCacheStream::Read(char* aBuffer, ui
     return NS_ERROR_FAILURE;
 
   uint32_t count = 0;
   // Read one block (or part of a block) at a time
   while (count < aCount) {
     uint32_t streamBlock = uint32_t(mStreamOffset/BLOCK_SIZE);
     uint32_t offsetInStreamBlock =
       uint32_t(mStreamOffset - streamBlock*BLOCK_SIZE);
-    int64_t size = NS_MIN(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
+    int64_t size = std::min(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
 
     if (mStreamLength >= 0) {
       // Don't try to read beyond the end of the stream
       int64_t bytesRemaining = mStreamLength - mStreamOffset;
       if (bytesRemaining <= 0) {
         // Get out of here and return NS_OK
         break;
       }
-      size = NS_MIN(size, bytesRemaining);
+      size = std::min(size, bytesRemaining);
       // Clamp size until 64-bit file size issues (bug 500784) are fixed.
-      size = NS_MIN(size, int64_t(INT32_MAX));
+      size = std::min(size, int64_t(INT32_MAX));
     }
 
     int32_t bytes;
     int32_t cacheBlock = streamBlock < mBlocks.Length() ? mBlocks[streamBlock] : -1;
     if (cacheBlock < 0) {
       // We don't have a complete cached block here.
 
       if (count > 0) {
@@ -2140,17 +2141,17 @@ MediaCacheStream::Read(char* aBuffer, ui
           streamWithPartialBlock = stream;
           break;
         }
       }
       if (streamWithPartialBlock) {
         // We can just use the data in mPartialBlockBuffer. In fact we should
         // use it rather than waiting for the block to fill and land in
         // the cache.
-        bytes = NS_MIN<int64_t>(size, streamWithPartialBlock->mChannelOffset - mStreamOffset);
+        bytes = std::min<int64_t>(size, streamWithPartialBlock->mChannelOffset - mStreamOffset);
         memcpy(aBuffer,
           reinterpret_cast<char*>(streamWithPartialBlock->mPartialBlockBuffer) + offsetInStreamBlock, bytes);
         if (mCurrentMode == MODE_METADATA) {
           streamWithPartialBlock->mMetadataInPartialBlockBuffer = true;
         }
         mStreamOffset += bytes;
         count = bytes;
         break;
@@ -2208,37 +2209,37 @@ MediaCacheStream::ReadFromCache(char* aB
 
   // Read one block (or part of a block) at a time
   uint32_t count = 0;
   int64_t streamOffset = aOffset;
   while (count < aCount) {
     uint32_t streamBlock = uint32_t(streamOffset/BLOCK_SIZE);
     uint32_t offsetInStreamBlock =
       uint32_t(streamOffset - streamBlock*BLOCK_SIZE);
-    int64_t size = NS_MIN<int64_t>(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
+    int64_t size = std::min<int64_t>(aCount - count, BLOCK_SIZE - offsetInStreamBlock);
 
     if (mStreamLength >= 0) {
       // Don't try to read beyond the end of the stream
       int64_t bytesRemaining = mStreamLength - streamOffset;
       if (bytesRemaining <= 0) {
         return NS_ERROR_FAILURE;
       }
-      size = NS_MIN(size, bytesRemaining);
+      size = std::min(size, bytesRemaining);
       // Clamp size until 64-bit file size issues (bug 500784) are fixed.
-      size = NS_MIN(size, int64_t(INT32_MAX));
+      size = std::min(size, int64_t(INT32_MAX));
     }
 
     int32_t bytes;
     uint32_t channelBlock = uint32_t(mChannelOffset/BLOCK_SIZE);
     int32_t cacheBlock = streamBlock < mBlocks.Length() ? mBlocks[streamBlock] : -1;
     if (channelBlock == streamBlock && streamOffset < mChannelOffset) {
       // We can just use the data in mPartialBlockBuffer. In fact we should
       // use it rather than waiting for the block to fill and land in
       // the cache.
-      bytes = NS_MIN<int64_t>(size, mChannelOffset - streamOffset);
+      bytes = std::min<int64_t>(size, mChannelOffset - streamOffset);
       memcpy(aBuffer + count,
         reinterpret_cast<char*>(mPartialBlockBuffer) + offsetInStreamBlock, bytes);
     } else {
       if (cacheBlock < 0) {
         // We expect all blocks to be cached! Fail!
         return NS_ERROR_FAILURE;
       }
       int64_t offset = cacheBlock*BLOCK_SIZE + offsetInStreamBlock;
--- a/content/media/MediaDecoder.cpp
+++ b/content/media/MediaDecoder.cpp
@@ -17,16 +17,17 @@
 #include "nsTimeRanges.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>
 
 #ifdef MOZ_WMF
 #include "WMFDecoder.h"
 #endif
 
 using namespace mozilla::layers;
 using namespace mozilla::dom;
 
@@ -894,22 +895,22 @@ void MediaDecoder::UpdatePlaybackRate()
   MOZ_ASSERT(NS_IsMainThread() || OnStateMachineThread());
   GetReentrantMonitor().AssertCurrentThreadIn();
   if (!mResource)
     return;
   bool reliable;
   uint32_t rate = uint32_t(ComputePlaybackRate(&reliable));
   if (reliable) {
     // Avoid passing a zero rate
-    rate = NS_MAX(rate, 1u);
+    rate = std::max(rate, 1u);
   }
   else {
     // Set a minimum rate of 10,000 bytes per second ... sometimes we just
     // don't have good data
-    rate = NS_MAX(rate, 10000u);
+    rate = std::max(rate, 10000u);
   }
   mResource->SetPlaybackRate(rate);
 }
 
 void MediaDecoder::NotifySuspendedStatusChanged()
 {
   MOZ_ASSERT(NS_IsMainThread());
   if (!mResource)
@@ -1327,17 +1328,17 @@ void MediaDecoder::MoveLoadsToBackground
   if (mResource) {
     mResource->MoveLoadsToBackground();
   }
 }
 
 void MediaDecoder::UpdatePlaybackOffset(int64_t aOffset)
 {
   ReentrantMonitorAutoEnter mon(GetReentrantMonitor());
-  mPlaybackPosition = NS_MAX(aOffset, mPlaybackPosition);
+  mPlaybackPosition = std::max(aOffset, mPlaybackPosition);
 }
 
 bool MediaDecoder::OnStateMachineThread() const
 {
   return IsCurrentThread(MediaDecoderStateMachine::GetStateMachineThread());
 }
 
 void MediaDecoder::NotifyAudioAvailableListener()
--- a/content/media/MediaDecoderReader.cpp
+++ b/content/media/MediaDecoderReader.cpp
@@ -8,16 +8,17 @@
 #include "MediaDecoderReader.h"
 #include "AbstractMediaDecoder.h"
 #include "MediaDecoderStateMachine.h"
 #include "VideoUtils.h"
 #include "ImageContainer.h"
 
 #include "mozilla/mozalloc.h"
 #include "mozilla/StandardInteger.h"
+#include <algorithm>
 
 namespace mozilla {
 
 using layers::ImageContainer;
 using layers::PlanarYCbCrImage;
 
 // Verify these values are sane. Once we've checked the frame sizes, we then
 // can do less integer overflow checking.
@@ -415,17 +416,17 @@ VideoData* MediaDecoderReader::FindStart
   }
   if (HasAudio()) {
     AudioData* audioData = DecodeToFirstAudioData();
     if (audioData) {
       audioStartTime = audioData->mTime;
     }
   }
 
-  int64_t startTime = NS_MIN(videoStartTime, audioStartTime);
+  int64_t startTime = std::min(videoStartTime, audioStartTime);
   if (startTime != INT64_MAX) {
     aOutStartTime = startTime;
   }
 
   return videoData;
 }
 
 nsresult MediaDecoderReader::DecodeToTarget(int64_t aTarget)
--- a/content/media/MediaDecoderStateMachine.cpp
+++ b/content/media/MediaDecoderStateMachine.cpp
@@ -18,16 +18,17 @@
 #include "nsTimeRanges.h"
 #include "nsDeque.h"
 #include "AudioSegment.h"
 #include "VideoSegment.h"
 #include "ImageContainer.h"
 
 #include "prenv.h"
 #include "mozilla/Preferences.h"
+#include <algorithm>
 
 namespace mozilla {
 
 using namespace mozilla::layers;
 using namespace mozilla::dom;
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gMediaDecoderLog;
@@ -621,18 +622,18 @@ void MediaDecoderStateMachine::SendStrea
     }
     if (output.GetDuration() > 0) {
       mediaStream->AppendToTrack(TRACK_AUDIO, &output);
     }
     if (mReader->AudioQueue().IsFinished() && !stream->mHaveSentFinishAudio) {
       mediaStream->EndTrack(TRACK_AUDIO);
       stream->mHaveSentFinishAudio = true;
     }
-    minLastAudioPacketTime = NS_MIN(minLastAudioPacketTime, stream->mLastAudioPacketTime);
-    endPosition = NS_MAX(endPosition,
+    minLastAudioPacketTime = std::min(minLastAudioPacketTime, stream->mLastAudioPacketTime);
+    endPosition = std::max(endPosition,
         TicksToTimeRoundDown(mInfo.mAudioRate, stream->mAudioFramesWritten));
   }
 
   if (mInfo.mHasVideo) {
     nsAutoTArray<VideoData*,10> video;
     // It's OK to hold references to the VideoData only the decoder thread
     // pops from the queue.
     mReader->VideoQueue().GetElementsAfter(stream->mNextVideoTime + mStartTime, &video);
@@ -667,17 +668,17 @@ void MediaDecoderStateMachine::SendStrea
     }
     if (output.GetDuration() > 0) {
       mediaStream->AppendToTrack(TRACK_VIDEO, &output);
     }
     if (mReader->VideoQueue().IsFinished() && !stream->mHaveSentFinishVideo) {
       mediaStream->EndTrack(TRACK_VIDEO);
       stream->mHaveSentFinishVideo = true;
     }
-    endPosition = NS_MAX(endPosition,
+    endPosition = std::max(endPosition,
         TicksToTimeRoundDown(RATE_VIDEO, stream->mNextVideoTime - stream->mInitialTime));
   }
 
   if (!stream->mHaveSentFinish) {
     stream->mStream->AdvanceKnownTracksTime(endPosition);
   }
 
   bool finished =
@@ -686,17 +687,17 @@ void MediaDecoderStateMachine::SendStrea
   if (finished && !stream->mHaveSentFinish) {
     stream->mHaveSentFinish = true;
     stream->mStream->Finish();
   }
 
   if (mAudioCaptured) {
     // Discard audio packets that are no longer needed.
     int64_t audioPacketTimeToDiscard =
-        NS_MIN(minLastAudioPacketTime, mStartTime + mCurrentFrameTime);
+        std::min(minLastAudioPacketTime, mStartTime + mCurrentFrameTime);
     while (true) {
       nsAutoPtr<AudioData> a(mReader->AudioQueue().PopFront());
       if (!a)
         break;
       // Packet times are not 100% reliable so this may discard packets that
       // actually contain data for mCurrentFrameTime. This means if someone might
       // create a new output stream and we actually don't have the audio for the
       // very start. That's OK, we'll play silence instead for a brief moment.
@@ -870,18 +871,18 @@ void MediaDecoderStateMachine::DecodeLoo
         TimeStamp start = TimeStamp::Now();
         videoPlaying = mReader->DecodeVideoFrame(skipToNextKeyframe, currentTime);
         decodeTime = TimeStamp::Now() - start;
       }
       if (THRESHOLD_FACTOR * DurationToUsecs(decodeTime) > lowAudioThreshold &&
           !HasLowUndecodedData())
       {
         lowAudioThreshold =
-          NS_MIN(THRESHOLD_FACTOR * DurationToUsecs(decodeTime), AMPLE_AUDIO_USECS);
-        ampleAudioThreshold = NS_MAX(THRESHOLD_FACTOR * lowAudioThreshold,
+          std::min(THRESHOLD_FACTOR * DurationToUsecs(decodeTime), AMPLE_AUDIO_USECS);
+        ampleAudioThreshold = std::max(THRESHOLD_FACTOR * lowAudioThreshold,
                                      ampleAudioThreshold);
         LOG(PR_LOG_DEBUG,
             ("Slow video decode, set lowAudioThreshold=%lld ampleAudioThreshold=%lld",
              lowAudioThreshold, ampleAudioThreshold));
       }
     }
 
     // Audio decode.
@@ -1078,17 +1079,17 @@ void MediaDecoderStateMachine::AudioLoop
     }
 
     int64_t framesWritten = 0;
     if (missingFrames.value() > 0) {
       // The next audio chunk begins some time after the end of the last chunk
       // we pushed to the audio hardware. We must push silence into the audio
       // hardware so that the next audio chunk begins playback at the correct
       // time.
-      missingFrames = NS_MIN<int64_t>(UINT32_MAX, missingFrames.value());
+      missingFrames = std::min<int64_t>(UINT32_MAX, missingFrames.value());
       LOG(PR_LOG_DEBUG, ("%p Decoder playing %d frames of silence",
                          mDecoder.get(), int32_t(missingFrames.value())));
       framesWritten = PlaySilence(static_cast<uint32_t>(missingFrames.value()),
                                   channels, playedFrames.value());
     } else {
       framesWritten = PlayFromAudioQueue(sampleTime.value(), channels);
     }
     audioDuration += framesWritten;
@@ -1132,17 +1133,17 @@ void MediaDecoderStateMachine::AudioLoop
         int64_t oldPosition = -1;
         int64_t position = GetMediaTime();
         while (oldPosition != position &&
                mAudioEndTime - position > 0 &&
                mState != DECODER_STATE_SEEKING &&
                mState != DECODER_STATE_SHUTDOWN)
         {
           const int64_t DRAIN_BLOCK_USECS = 100000;
-          Wait(NS_MIN(mAudioEndTime - position, DRAIN_BLOCK_USECS));
+          Wait(std::min(mAudioEndTime - position, DRAIN_BLOCK_USECS));
           oldPosition = position;
           position = GetMediaTime();
         }
         seeking = mState == DECODER_STATE_SEEKING;
       }
 
       if (!seeking && !mAudioStream->IsPaused()) {
         {
@@ -1176,17 +1177,17 @@ void MediaDecoderStateMachine::AudioLoop
 uint32_t MediaDecoderStateMachine::PlaySilence(uint32_t aFrames,
                                                    uint32_t aChannels,
                                                    uint64_t aFrameOffset)
 
 {
   NS_ASSERTION(OnAudioThread(), "Only call on audio thread.");
   NS_ASSERTION(!mAudioStream->IsPaused(), "Don't play when paused");
   uint32_t maxFrames = SILENCE_BYTES_CHUNK / aChannels / sizeof(AudioDataValue);
-  uint32_t frames = NS_MIN(aFrames, maxFrames);
+  uint32_t frames = std::min(aFrames, maxFrames);
   WriteSilence(mAudioStream, frames);
   // Dispatch events to the DOM for the audio just written.
   mEventManager.QueueWrittenAudioData(nullptr, frames * aChannels,
                                       (aFrameOffset + frames) * aChannels);
   return frames;
 }
 
 uint32_t MediaDecoderStateMachine::PlayFromAudioQueue(uint64_t aFrameOffset,
@@ -1489,17 +1490,17 @@ void MediaDecoderStateMachine::NotifyDat
       NS_SUCCEEDED(mDecoder->GetBuffered(&buffered)))
   {
     uint32_t length = 0;
     buffered.GetLength(&length);
     if (length) {
       double end = 0;
       buffered.End(length - 1, &end);
       ReentrantMonitorAutoEnter mon(mDecoder->GetReentrantMonitor());
-      mEndTime = NS_MAX<int64_t>(mEndTime, end * USECS_PER_S);
+      mEndTime = std::max<int64_t>(mEndTime, end * USECS_PER_S);
     }
   }
 }
 
 void MediaDecoderStateMachine::Seek(double aTime)
 {
   NS_ASSERTION(NS_IsMainThread(), "Should be on main thread.");
   ReentrantMonitorAutoEnter mon(mDecoder->GetReentrantMonitor());
@@ -1523,18 +1524,18 @@ void MediaDecoderStateMachine::Seek(doub
 
   mSeekTime = static_cast<int64_t>(t) + mStartTime;
   NS_ASSERTION(mSeekTime >= mStartTime && mSeekTime <= mEndTime,
                "Can only seek in range [0,duration]");
 
   // Bound the seek time to be inside the media range.
   NS_ASSERTION(mStartTime != -1, "Should know start time by now");
   NS_ASSERTION(mEndTime != -1, "Should know end time by now");
-  mSeekTime = NS_MIN(mSeekTime, mEndTime);
-  mSeekTime = NS_MAX(mStartTime, mSeekTime);
+  mSeekTime = std::min(mSeekTime, mEndTime);
+  mSeekTime = std::max(mStartTime, mSeekTime);
   mBasePosition = mSeekTime;
   LOG(PR_LOG_DEBUG, ("%p Changed state to SEEKING (to %f)", mDecoder.get(), aTime));
   mState = DECODER_STATE_SEEKING;
   if (mDecoder->GetDecodedStream()) {
     mDecoder->RecreateDecodedStream(mSeekTime - mStartTime);
   }
   ScheduleStateMachine();
 }
@@ -2185,17 +2186,17 @@ nsresult MediaDecoderStateMachine::RunSt
         // our state should have scheduled another state machine run.
         NS_ASSERTION(IsStateMachineScheduled(), "Must have timer scheduled");
         return NS_OK;
       }
  
       StopAudioThread();
       if (mDecoder->GetState() == MediaDecoder::PLAY_STATE_PLAYING) {
         int64_t videoTime = HasVideo() ? mVideoFrameEndTime : 0;
-        int64_t clockTime = NS_MAX(mEndTime, NS_MAX(videoTime, GetAudioClock()));
+        int64_t clockTime = std::max(mEndTime, std::max(videoTime, GetAudioClock()));
         UpdatePlaybackPosition(clockTime);
         nsCOMPtr<nsIRunnable> event =
           NS_NewRunnableMethod(mDecoder, &MediaDecoder::PlaybackEnded);
         NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
       }
       return NS_OK;
     }
   }
@@ -2398,17 +2399,17 @@ void MediaDecoderStateMachine::AdvanceFr
     currentFrame = nullptr;
   }
 
   // Cap the current time to the larger of the audio and video end time.
   // This ensures that if we're running off the system clock, we don't
   // advance the clock to after the media end time.
   if (mVideoFrameEndTime != -1 || mAudioEndTime != -1) {
     // These will be non -1 if we've displayed a video frame, or played an audio frame.
-    clock_time = NS_MIN(clock_time, NS_MAX(mVideoFrameEndTime, mAudioEndTime));
+    clock_time = std::min(clock_time, std::max(mVideoFrameEndTime, mAudioEndTime));
     if (clock_time > GetMediaTime()) {
       // Only update the playback position if the clock time is greater
       // than the previous playback position. The audio clock can
       // sometimes report a time less than its previously reported in
       // some situations, and we need to gracefully handle that.
       UpdatePlaybackPosition(clock_time);
     }
   }
@@ -2420,17 +2421,17 @@ void MediaDecoderStateMachine::AdvanceFr
   UpdateReadyState();
 
   ScheduleStateMachine(remainingTime);
 }
 
 void MediaDecoderStateMachine::Wait(int64_t aUsecs) {
   NS_ASSERTION(OnAudioThread(), "Only call on the audio thread");
   mDecoder->GetReentrantMonitor().AssertCurrentThreadIn();
-  TimeStamp end = TimeStamp::Now() + UsecsToDuration(NS_MAX<int64_t>(USECS_PER_MS, aUsecs));
+  TimeStamp end = TimeStamp::Now() + UsecsToDuration(std::max<int64_t>(USECS_PER_MS, aUsecs));
   TimeStamp now;
   while ((now = TimeStamp::Now()) < end &&
          mState != DECODER_STATE_SHUTDOWN &&
          mState != DECODER_STATE_SEEKING &&
          !mStopAudioThread &&
          IsPlaying())
   {
     int64_t ms = static_cast<int64_t>(NS_round((end - now).ToSeconds() * 1000));
@@ -2634,17 +2635,17 @@ void MediaDecoderStateMachine::ScheduleS
 nsresult MediaDecoderStateMachine::ScheduleStateMachine(int64_t aUsecs) {
   mDecoder->GetReentrantMonitor().AssertCurrentThreadIn();
   NS_ABORT_IF_FALSE(GetStateMachineThread(),
     "Must have a state machine thread to schedule");
 
   if (mState == DECODER_STATE_SHUTDOWN) {
     return NS_ERROR_FAILURE;
   }
-  aUsecs = NS_MAX<int64_t>(aUsecs, 0);
+  aUsecs = std::max<int64_t>(aUsecs, 0);
 
   TimeStamp timeout = TimeStamp::Now() + UsecsToDuration(aUsecs);
   if (!mTimeout.IsNull()) {
     if (timeout >= mTimeout) {
       // We've already scheduled a timer set to expire at or before this time,
       // or have an event dispatched to run the state machine.
       return NS_OK;
     }
--- a/content/media/MediaResource.cpp
+++ b/content/media/MediaResource.cpp
@@ -25,16 +25,17 @@
 #include "nsCrossSiteListenerProxy.h"
 #include "nsHTMLMediaElement.h"
 #include "nsError.h"
 #include "nsICachingChannel.h"
 #include "nsURILoader.h"
 #include "nsIAsyncVerifyRedirectCallback.h"
 #include "nsContentUtils.h"
 #include "nsHostObjectProtocolHandler.h"
+#include <algorithm>
 
 #ifdef PR_LOGGING
 PRLogModuleInfo* gMediaResourceLog;
 #define LOG(msg, ...) PR_LOG(gMediaResourceLog, PR_LOG_DEBUG, \
                              (msg, ##__VA_ARGS__))
 // Debug logging macro with object pointer and class name.
 #define CMLOG(msg, ...) \
         LOG("%p [ChannelMediaResource]: " msg, this, ##__VA_ARGS__)
@@ -1303,17 +1304,17 @@ public:
 
     EnsureSizeInitialized();
     return (aOffset < mSize) ? aOffset : -1;
   }
   virtual int64_t GetCachedDataEnd(int64_t aOffset) {
     MutexAutoLock lock(mLock);
 
     EnsureSizeInitialized();
-    return NS_MAX(aOffset, mSize);
+    return std::max(aOffset, mSize);
   }
   virtual bool    IsDataCachedToEndOfResource(int64_t aOffset) { return true; }
   virtual bool    IsSuspendedByCache(MediaResource** aActiveResource)
   {
     if (aActiveResource) {
       *aActiveResource = nullptr;
     }
     return false;
--- a/content/media/MediaSegment.h
+++ b/content/media/MediaSegment.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 MOZILLA_MEDIASEGMENT_H_
 #define MOZILLA_MEDIASEGMENT_H_
 
 #include "nsTArray.h"
+#include <algorithm>
 
 namespace mozilla {
 
 /**
  * We represent media times in 64-bit fixed point. So 1 MediaTime is
  * 1/(2^MEDIA_TIME_FRAC_BITS) seconds.
  */
 typedef int64_t MediaTime;
@@ -151,17 +152,17 @@ public:
    * will not be required again.
    */
   virtual void ForgetUpTo(TrackTicks aDuration)
   {
     if (mChunks.IsEmpty() || aDuration <= 0) {
       return;
     }
     if (mChunks[0].IsNull()) {
-      TrackTicks extraToForget = NS_MIN(aDuration, mDuration) - mChunks[0].GetDuration();
+      TrackTicks extraToForget = std::min(aDuration, mDuration) - mChunks[0].GetDuration();
       if (extraToForget > 0) {
         RemoveLeading(extraToForget, 1);
         mChunks[0].mDuration += extraToForget;
         mDuration += extraToForget;
       }
       return;
     }
     RemoveLeading(aDuration, 0);
@@ -232,19 +233,19 @@ protected:
     static_cast<C*>(this)->CheckCompatible(static_cast<const C&>(aSource));
     NS_ASSERTION(aStart <= aEnd, "Endpoints inverted");
     NS_ASSERTION(aStart >= 0 && aEnd <= aSource.mDuration,
                  "Slice out of range");
     mDuration += aEnd - aStart;
     TrackTicks offset = 0;
     for (uint32_t i = 0; i < aSource.mChunks.Length() && offset < aEnd; ++i) {
       const Chunk& c = aSource.mChunks[i];
-      TrackTicks start = NS_MAX(aStart, offset);
+      TrackTicks start = std::max(aStart, offset);
       TrackTicks nextOffset = offset + c.GetDuration();
-      TrackTicks end = NS_MIN(aEnd, nextOffset);
+      TrackTicks end = std::min(aEnd, nextOffset);
       if (start < end) {
         mChunks.AppendElement(c)->SliceTo(start - offset, end - offset);
       }
       offset = nextOffset;
     }
   }
 
   Chunk* AppendChunk(TrackTicks aDuration)
--- a/content/media/MediaStreamGraph.cpp
+++ b/content/media/MediaStreamGraph.cpp
@@ -16,16 +16,17 @@
 #include "nsWidgetsCID.h"
 #include "nsXPCOMCIDInternal.h"
 #include "prlog.h"
 #include "VideoUtils.h"
 #include "mozilla/Attributes.h"
 #include "TrackUnionStream.h"
 #include "ImageContainer.h"
 #include "AudioChannelCommon.h"
+#include <algorithm>
 
 using namespace mozilla::layers;
 using namespace mozilla::dom;
 
 namespace mozilla {
 
 #ifdef PR_LOGGING
 PRLogModuleInfo* gMediaStreamGraphLog;
@@ -514,17 +515,17 @@ public:
  */
 static MediaStreamGraphImpl* gGraph;
 
 StreamTime
 MediaStreamGraphImpl::GetDesiredBufferEnd(MediaStream* aStream)
 {
   StreamTime current = mCurrentTime - aStream->mBufferStartTime;
   return current +
-      MillisecondsToMediaTime(NS_MAX(AUDIO_TARGET_MS, VIDEO_TARGET_MS));
+      MillisecondsToMediaTime(std::max(AUDIO_TARGET_MS, VIDEO_TARGET_MS));
 }
 
 void
 MediaStreamGraphImpl::FinishStream(MediaStream* aStream)
 {
   if (aStream->mFinished)
     return;
   LOG(PR_LOG_DEBUG, ("MediaStream %p will finish", aStream));
@@ -686,28 +687,28 @@ MediaStreamGraphImpl::UpdateBufferSuffic
 
 StreamTime
 MediaStreamGraphImpl::GraphTimeToStreamTime(MediaStream* aStream,
                                             GraphTime aTime)
 {
   NS_ASSERTION(aTime <= mStateComputedTime,
                "Don't ask about times where we haven't made blocking decisions yet");
   if (aTime <= mCurrentTime) {
-    return NS_MAX<StreamTime>(0, aTime - aStream->mBufferStartTime);
+    return std::max<StreamTime>(0, aTime - aStream->mBufferStartTime);
   }
   GraphTime t = mCurrentTime;
   StreamTime s = t - aStream->mBufferStartTime;
   while (t < aTime) {
     GraphTime end;
     if (!aStream->mBlocked.GetAt(t, &end)) {
-      s += NS_MIN(aTime, end) - t;
+      s += std::min(aTime, end) - t;
     }
     t = end;
   }
-  return NS_MAX<StreamTime>(0, s);
+  return std::max<StreamTime>(0, s);
 }  
 
 GraphTime
 MediaStreamGraphImpl::StreamTimeToGraphTime(MediaStream* aStream,
                                             StreamTime aTime, uint32_t aFlags)
 {
   if (aTime >= STREAM_TIME_MAX) {
     return GRAPH_TIME_MAX;
@@ -722,29 +723,29 @@ MediaStreamGraphImpl::StreamTimeToGraphT
   NS_ASSERTION(streamAmount >= 0, "Can't answer queries before current time");
 
   GraphTime t = mCurrentTime;
   while (t < GRAPH_TIME_MAX) {
     bool blocked;
     GraphTime end;
     if (t < mStateComputedTime) {
       blocked = aStream->mBlocked.GetAt(t, &end);
-      end = NS_MIN(end, mStateComputedTime);
+      end = std::min(end, mStateComputedTime);
     } else {
       blocked = false;
       end = GRAPH_TIME_MAX;
     }
     if (blocked) {
       t = end;
     } else {
       if (streamAmount == 0) {
         // No more stream time to consume at time t, so we're done.
         break;
       }
-      MediaTime consume = NS_MIN(end - t, streamAmount);
+      MediaTime consume = std::min(end - t, streamAmount);
       streamAmount -= consume;
       t += consume;
     }
   }
   return t;
 }
 
 GraphTime
@@ -801,17 +802,17 @@ MediaStreamGraphImpl::UpdateCurrentTime(
 
     // Calculate blocked time and fire Blocked/Unblocked events
     GraphTime blockedTime = 0;
     GraphTime t = prevCurrentTime;
     while (t < nextCurrentTime) {
       GraphTime end;
       bool blocked = stream->mBlocked.GetAt(t, &end);
       if (blocked) {
-        blockedTime += NS_MIN(end, nextCurrentTime) - t;
+        blockedTime += std::min(end, nextCurrentTime) - t;
       }
       if (blocked != stream->mNotifiedBlocked) {
         for (uint32_t j = 0; j < stream->mListeners.Length(); ++j) {
           MediaStreamListener* l = stream->mListeners[j];
           l->NotifyBlockingChanged(this,
               blocked ? MediaStreamListener::BLOCKED : MediaStreamListener::UNBLOCKED);
         }
         stream->mNotifiedBlocked = blocked;
@@ -877,17 +878,17 @@ MediaStreamGraphImpl::WillUnderrun(Media
   // we can.
   if (bufferEnd <= aEndBlockingDecisions && aStream->mBlocked.GetBefore(aTime)) {
     LOG(PR_LOG_DEBUG, ("MediaStream %p will block due to speculative data underrun, "
                        "bufferEnd %f",
                        aStream, MediaTimeToSeconds(bufferEnd)));
     return true;
   }
   // Reconsider decisions at bufferEnd
-  *aEnd = NS_MIN(*aEnd, bufferEnd);
+  *aEnd = std::min(*aEnd, bufferEnd);
   return false;
 }
 
 void
 MediaStreamGraphImpl::MarkConsumed(MediaStream* aStream)
 {
   if (aStream->mIsConsumed) {
     return;
@@ -1078,23 +1079,23 @@ MediaStreamGraphImpl::RecomputeBlockingA
         // We'll block indefinitely
         MarkStreamBlocking(stream);
         *aEnd = aEndBlockingDecisions;
         continue;
       } else {
         LOG(PR_LOG_DEBUG, ("MediaStream %p is finished, but not blocked yet (end at %f, with blocking at %f)",
                            stream, MediaTimeToSeconds(stream->GetBufferEnd()),
                            MediaTimeToSeconds(endTime)));
-        *aEnd = NS_MIN(*aEnd, endTime);
+        *aEnd = std::min(*aEnd, endTime);
       }
     }
 
     GraphTime end;
     bool explicitBlock = stream->mExplicitBlockerCount.GetAt(aTime, &end) > 0;
-    *aEnd = NS_MIN(*aEnd, end);
+    *aEnd = std::min(*aEnd, end);
     if (explicitBlock) {
       LOG(PR_LOG_DEBUG, ("MediaStream %p is blocked due to explicit blocker", stream));
       MarkStreamBlocking(stream);
       continue;
     }
 
     bool underrun = WillUnderrun(stream, aTime, aEndBlockingDecisions, aEnd);
     if (underrun) {
@@ -1202,17 +1203,17 @@ MediaStreamGraphImpl::PlayAudio(MediaStr
     // time spent blocked. Instead, we'll update it in UpdateCurrentTime after the
     // blocked period has completed. But we do need to make sure we play from the
     // right offsets in the stream buffer, even if we've already written silence for
     // some amount of blocked time after the current time.
     GraphTime t = aFrom;
     while (t < aTo) {
       GraphTime end;
       bool blocked = aStream->mBlocked.GetAt(t, &end);
-      end = NS_MIN(end, aTo);
+      end = std::min(end, aTo);
 
       AudioSegment output;
       output.InitFrom(*audio);
       if (blocked) {
         // Track total blocked time in aStream->mBlockedAudioTime so that
         // the amount of silent samples we've inserted for blocking never gets
         // more than one sample away from the ideal amount.
         TrackTicks startTicks =
@@ -1229,17 +1230,17 @@ MediaStreamGraphImpl::PlayAudio(MediaStr
             track->TimeToTicksRoundDown(GraphTimeToStreamTime(aStream, t));
         TrackTicks endTicks =
             track->TimeToTicksRoundDown(GraphTimeToStreamTime(aStream, end));
 
         // If startTicks is before the track start, then that part of 'audio'
         // will just be silence, which is fine here. But if endTicks is after
         // the track end, then 'audio' won't be long enough, so we'll need
         // to explicitly play silence.
-        TrackTicks sliceEnd = NS_MIN(endTicks, audio->GetDuration());
+        TrackTicks sliceEnd = std::min(endTicks, audio->GetDuration());
         if (sliceEnd > startTicks) {
           output.AppendSlice(*audio, startTicks, sliceEnd);
         }
         // Play silence where the track has ended
         output.AppendNullData(endTicks - sliceEnd);
         NS_ASSERTION(endTicks == sliceEnd || track->IsEnded(),
                      "Ran out of data but track not ended?");
         output.ApplyVolume(volume);
@@ -1453,17 +1454,17 @@ MediaStreamGraphImpl::RunThread()
 
       PRIntervalTime timeout = PR_INTERVAL_NO_TIMEOUT;
       TimeStamp now = TimeStamp::Now();
       if (mNeedAnotherIteration) {
         int64_t timeoutMS = MEDIA_GRAPH_TARGET_PERIOD_MS -
           int64_t((now - mCurrentTimeStamp).ToMilliseconds());
         // Make sure timeoutMS doesn't overflow 32 bits by waking up at
         // least once a minute, if we need to wake up at all
-        timeoutMS = NS_MAX<int64_t>(0, NS_MIN<int64_t>(timeoutMS, 60*1000));
+        timeoutMS = std::max<int64_t>(0, std::min<int64_t>(timeoutMS, 60*1000));
         timeout = PR_MillisecondsToInterval(uint32_t(timeoutMS));
         LOG(PR_LOG_DEBUG, ("Waiting for next iteration; at %f, timeout=%f",
                            (now - mInitialTimeStamp).ToSeconds(), timeoutMS/1000.0));
         mWaitState = WAITSTATE_WAITING_FOR_NEXT_ITERATION;
       } else {
         mWaitState = WAITSTATE_WAITING_INDEFINITELY;
       }
       if (timeout > 0) {
@@ -2170,17 +2171,17 @@ MediaInputPort::GetNextInputInterval(Gra
       break;
     if (end == GRAPH_TIME_MAX)
       return result;
     t = end;
   }
   result.mStart = t;
   GraphTime sourceEnd;
   result.mInputIsBlocked = mSource->mBlocked.GetAt(t, &sourceEnd);
-  result.mEnd = NS_MIN(end, sourceEnd);
+  result.mEnd = std::min(end, sourceEnd);
   return result;
 }
 
 void
 MediaInputPort::Destroy()
 {
   class Message : public ControlMessage {
   public:
--- a/content/media/StreamBuffer.cpp
+++ b/content/media/StreamBuffer.cpp
@@ -1,25 +1,26 @@
 /* -*- 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 "StreamBuffer.h"
+#include <algorithm>
 
 namespace mozilla {
 
 StreamTime
 StreamBuffer::GetEnd() const
 {
   StreamTime t = mTracksKnownTime;
   for (uint32_t i = 0; i < mTracks.Length(); ++i) {
     Track* track = mTracks[i];
     if (!track->IsEnded()) {
-      t = NS_MIN(t, track->GetEndTimeRoundDown());
+      t = std::min(t, track->GetEndTimeRoundDown());
     }
   }
   return t;
 }
 
 StreamBuffer::Track*
 StreamBuffer::FindTrack(TrackID aID)
 {
@@ -47,14 +48,14 @@ StreamBuffer::ForgetUpTo(StreamTime aTim
 
   for (uint32_t i = 0; i < mTracks.Length(); ++i) {
     Track* track = mTracks[i];
     if (track->IsEnded() && track->GetEndTimeRoundDown() <= forget) {
       mTracks.RemoveElementAt(i);
       --i;
       continue;
     }
-    TrackTicks forgetTo = NS_MIN(track->GetEnd() - 1, track->TimeToTicksRoundDown(forget));
+    TrackTicks forgetTo = std::min(track->GetEnd() - 1, track->TimeToTicksRoundDown(forget));
     track->ForgetUpTo(forgetTo);
   }
 }
 
 }
--- a/content/media/StreamBuffer.h
+++ b/content/media/StreamBuffer.h
@@ -5,16 +5,17 @@
 
 #ifndef MOZILLA_STREAMBUFFER_H_
 #define MOZILLA_STREAMBUFFER_H_
 
 #include "mozilla/DebugOnly.h"
 
 #include "MediaSegment.h"
 #include "nsAutoPtr.h"
+#include <algorithm>
 
 namespace mozilla {
 
 /**
  * Media time relative to the start of a StreamBuffer.
  */
 typedef MediaTime StreamTime;
 const StreamTime STREAM_TIME_MAX = MEDIA_TIME_MAX;
@@ -159,17 +160,17 @@ public:
     MediaSegment* RemoveSegment()
     {
       return mSegment.forget();
     }
     void ForgetUpTo(TrackTicks aTime)
     {
       mSegment->ForgetUpTo(aTime);
 #ifdef DEBUG
-      mForgottenUpTo = NS_MAX<TrackTicks>(mForgottenUpTo, aTime);
+      mForgottenUpTo = std::max<TrackTicks>(mForgottenUpTo, aTime);
 #endif
     }
 #ifdef DEBUG
     TrackTicks GetForgottenUpTo() { return mForgottenUpTo; }
 #endif
 
   protected:
     friend class StreamBuffer;
--- a/content/media/TrackUnionStream.h
+++ b/content/media/TrackUnionStream.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 MOZILLA_TRACKUNIONSTREAM_H_
 #define MOZILLA_TRACKUNIONSTREAM_H_
 
 #include "MediaStreamGraph.h"
+#include <algorithm>
 
 namespace mozilla {
 
 #ifdef PR_LOGGING
 #define LOG(type, msg) PR_LOG(gMediaStreamGraphLog, type, msg)
 #else
 #define LOG(type, msg)
 #endif
@@ -112,17 +113,17 @@ protected:
     nsAutoPtr<MediaSegment> mSegment;
   };
 
   uint32_t AddTrack(MediaInputPort* aPort, StreamBuffer::Track* aTrack,
                     GraphTime aFrom)
   {
     // Use the ID of the source track if we can, otherwise allocate a new
     // unique ID
-    TrackID id = NS_MAX(mMaxTrackID + 1, aTrack->GetID());
+    TrackID id = std::max(mMaxTrackID + 1, aTrack->GetID());
     mMaxTrackID = id;
 
     TrackRate rate = aTrack->GetRate();
     // Round up the track start time so the track, if anything, starts a
     // little later than the true time. This means we'll have enough
     // samples in our input stream to go just beyond the destination time.
     TrackTicks outputStart = TimeToTicksRoundUp(rate, GraphTimeToStreamTime(aFrom));
 
@@ -176,17 +177,17 @@ protected:
     TrackRate rate = outputTrack->GetRate();
     MediaSegment* segment = map->mSegment;
     MediaStream* source = map->mInputPort->GetSource();
 
     GraphTime next;
     *aOutputTrackFinished = false;
     for (GraphTime t = aFrom; t < aTo; t = next) {
       MediaInputPort::InputInterval interval = map->mInputPort->GetNextInputInterval(t);
-      interval.mEnd = NS_MIN(interval.mEnd, aTo);
+      interval.mEnd = std::min(interval.mEnd, aTo);
       if (interval.mStart >= interval.mEnd)
         break;
       next = interval.mEnd;
 
       // Ticks >= startTicks and < endTicks are in the interval
       StreamTime outputEnd = GraphTimeToStreamTime(interval.mEnd);
       TrackTicks startTicks = outputTrack->GetEnd();
 #ifdef DEBUG
@@ -219,20 +220,20 @@ protected:
         // of a tick. Assuming the input track hasn't ended, we have to ensure
         // that 'ticks' samples are gathered, even though a tick boundary may
         // occur between outputStart and outputEnd but not between inputStart
         // and inputEnd.
         // We'll take the latest samples we can.
         TrackTicks inputEndTicks = TimeToTicksRoundUp(rate, inputEnd);
         TrackTicks inputStartTicks = inputEndTicks - ticks;
         segment->AppendSlice(*aInputTrack->GetSegment(),
-                             NS_MIN(inputTrackEndPoint, inputStartTicks),
-                             NS_MIN(inputTrackEndPoint, inputEndTicks));
+                             std::min(inputTrackEndPoint, inputStartTicks),
+                             std::min(inputTrackEndPoint, inputEndTicks));
         LOG(PR_LOG_DEBUG, ("TrackUnionStream %p appending %lld ticks of input data to track %d",
-            this, (long long)(NS_MIN(inputTrackEndPoint, inputEndTicks) - NS_MIN(inputTrackEndPoint, inputStartTicks)),
+            this, (long long)(std::min(inputTrackEndPoint, inputEndTicks) - std::min(inputTrackEndPoint, inputStartTicks)),
             outputTrack->GetID()));
       }
       for (uint32_t j = 0; j < mListeners.Length(); ++j) {
         MediaStreamListener* l = mListeners[j];
         l->NotifyQueuedTrackChanges(Graph(), outputTrack->GetID(),
                                     outputTrack->GetRate(), startTicks, 0,
                                     *segment);
       }
--- a/content/media/dash/DASHDecoder.cpp
+++ b/content/media/dash/DASHDecoder.cpp
@@ -122,16 +122,17 @@
 #include "nsICachingChannel.h"
 #include "MediaDecoderStateMachine.h"
 #include "WebMDecoder.h"
 #include "WebMReader.h"
 #include "DASHReader.h"
 #include "nsDASHMPDParser.h"
 #include "DASHRepDecoder.h"
 #include "DASHDecoder.h"
+#include <algorithm>
 
 namespace mozilla {
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gMediaDecoderLog;
 #define LOG(msg, ...) PR_LOG(gMediaDecoderLog, PR_LOG_DEBUG, \
                              ("%p [DASHDecoder] " msg, this, __VA_ARGS__))
 #define LOG1(msg) PR_LOG(gMediaDecoderLog, PR_LOG_DEBUG, \
@@ -934,17 +935,17 @@ DASHDecoder::PossiblySwitchDecoder(DASHR
       downloadRate/1000.0, (reliable ? "yes" : "no"), bestRepIdx,
       (noRepAvailable ? "yes" : "no"));
 
   // If there is a higher bitrate stream that can be downloaded with the
   // current estimated bandwidth, step up to the next stream, for a graceful
   // increase in quality.
   uint32_t toDecoderIdx = mVideoRepDecoderIdx;
   if (bestRepIdx > toDecoderIdx) {
-    toDecoderIdx = NS_MIN(toDecoderIdx+1, mVideoRepDecoders.Length()-1);
+    toDecoderIdx = std::min(toDecoderIdx+1, mVideoRepDecoders.Length()-1);
   } else if (toDecoderIdx < bestRepIdx) {
     // If the bitrate is too much for the current bandwidth, just use that
     // stream directly.
     toDecoderIdx = bestRepIdx;
   }
 
   // Upgrade |toDecoderIdx| if a better subsegment was previously downloaded and
   // is still cached.
--- a/content/media/dash/DASHReader.cpp
+++ b/content/media/dash/DASHReader.cpp
@@ -12,16 +12,17 @@
  *
  * see DASHDecoder.cpp for info on DASH interaction with the media engine.*/
 
 #include "nsTimeRanges.h"
 #include "VideoFrameContainer.h"
 #include "AbstractMediaDecoder.h"
 #include "DASHReader.h"
 #include "DASHDecoder.h"
+#include <algorithm>
 
 namespace mozilla {
 
 #ifdef PR_LOGGING
 PRLogModuleInfo* gDASHReaderLog;
 #define LOG(msg, ...) PR_LOG(gDASHReaderLog, PR_LOG_DEBUG, \
                              ("%p [DASHReader] " msg, this, __VA_ARGS__))
 #define LOG1(msg) PR_LOG(gDASHReaderLog, PR_LOG_DEBUG, \
@@ -416,17 +417,17 @@ DASHReader::FindStartTime(int64_t& aOutS
   if (HasAudio()) {
     // Forward to audio reader.
     AudioData* audioData = mAudioReader->DecodeToFirstAudioData();
     if (audioData) {
       audioStartTime = audioData->mTime;
     }
   }
 
-  int64_t startTime = NS_MIN(videoStartTime, audioStartTime);
+  int64_t startTime = std::min(videoStartTime, audioStartTime);
   if (startTime != INT64_MAX) {
     aOutStartTime = startTime;
   }
 
   return videoData;
 }
 
 MediaQueue<AudioData>&
--- a/content/media/dash/DASHRepDecoder.cpp
+++ b/content/media/dash/DASHRepDecoder.cpp
@@ -15,16 +15,17 @@
 #include "prlog.h"
 #include "VideoUtils.h"
 #include "SegmentBase.h"
 #include "MediaDecoderStateMachine.h"
 #include "DASHReader.h"
 #include "MediaResource.h"
 #include "DASHRepDecoder.h"
 #include "WebMReader.h"
+#include <algorithm>
 
 namespace mozilla {
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gMediaDecoderLog;
 #define LOG(msg, ...) PR_LOG(gMediaDecoderLog, PR_LOG_DEBUG, \
                              ("%p [DASHRepDecoder] " msg, this, __VA_ARGS__))
 #define LOG1(msg) PR_LOG(gMediaDecoderLog, PR_LOG_DEBUG, \
@@ -96,22 +97,22 @@ DASHRepDecoder::Load(MediaResource* aRes
   // Determine byte range to Open.
   // For small deltas between init and index ranges, we need to bundle the byte
   // range requests together in order to deal with |MediaCache|'s control of
   // seeking (see |MediaCache|::|Update|). |MediaCache| will not initiate a
   // |ChannelMediaResource|::|CacheClientSeek| for the INDEX byte range if the
   // delta between it and the INIT byte ranges is less than
   // |SEEK_VS_READ_THRESHOLD|. To get around this, request all metadata bytes
   // now so |MediaCache| can assume the bytes are en route.
-  int64_t delta = NS_MAX(mIndexByteRange.mStart, mInitByteRange.mStart)
-                - NS_MIN(mIndexByteRange.mEnd, mInitByteRange.mEnd);
+  int64_t delta = std::max(mIndexByteRange.mStart, mInitByteRange.mStart)
+                - std::min(mIndexByteRange.mEnd, mInitByteRange.mEnd);
   MediaByteRange byteRange;
   if (delta <= SEEK_VS_READ_THRESHOLD) {
-    byteRange.mStart = NS_MIN(mIndexByteRange.mStart, mInitByteRange.mStart);
-    byteRange.mEnd = NS_MAX(mIndexByteRange.mEnd, mInitByteRange.mEnd);
+    byteRange.mStart = std::min(mIndexByteRange.mStart, mInitByteRange.mStart);
+    byteRange.mEnd = std::max(mIndexByteRange.mEnd, mInitByteRange.mEnd);
     // Loading everything in one chunk .
     mMetadataChunkCount = 1;
   } else {
     byteRange = mInitByteRange;
     // Loading in two chunks: init and index.
     mMetadataChunkCount = 2;
   }
   mCurrentByteRange = byteRange;
--- a/content/media/ogg/OggCodecState.cpp
+++ b/content/media/ogg/OggCodecState.cpp
@@ -10,16 +10,17 @@
 #include "mozilla/StandardInteger.h"
 
 #include "nsDebug.h"
 #include "OggCodecState.h"
 #include "OggDecoder.h"
 #include "nsTraceRefcnt.h"
 #include "VideoUtils.h"
 #include "MediaDecoderReader.h"
+#include <algorithm>
 
 namespace mozilla {
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gMediaDecoderLog;
 #define LOG(type, msg) PR_LOG(gMediaDecoderLog, type, msg)
 #else
 #define LOG(type, msg)
@@ -496,17 +497,17 @@ void TheoraState::ReconstructTheoraGranu
     {
       // (frame - keyframe) won't overflow the "offset" segment of the
       // granulepos, so it's safe to calculate the granulepos.
       granulepos = (keyframe << shift) + (frame - keyframe);
     } else {
       // (frame - keyframeno) will overflow the "offset" segment of the
       // granulepos, so we take "keyframe" to be the max possible offset
       // frame instead.
-      ogg_int64_t k = NS_MAX(frame - (((ogg_int64_t)1 << shift) - 1), version_3_2_1);
+      ogg_int64_t k = std::max(frame - (((ogg_int64_t)1 << shift) - 1), version_3_2_1);
       granulepos = (k << shift) + (frame - k);
     }
     // Theora 3.2.1+ granulepos store frame number [1..N], so granulepos
     // should be > 0.
     // Theora 3.2.0 granulepos store the frame index [0..(N-1)], so
     // granulepos should be >= 0. 
     NS_ASSERTION(granulepos >= version_3_2_1,
                   "Invalid granulepos for Theora version");
@@ -800,17 +801,17 @@ nsresult VorbisState::ReconstructVorbisG
       mUnstamped[i]->granulepos += pruned;
     }
 #ifdef VALIDATE_VORBIS_SAMPLE_CALCULATION
     mVorbisPacketSamples[last] -= pruned;
 #endif
   }
 
   mPrevVorbisBlockSize = vorbis_packet_blocksize(&mInfo, last);
-  mPrevVorbisBlockSize = NS_MAX(static_cast<long>(0), mPrevVorbisBlockSize);
+  mPrevVorbisBlockSize = std::max(static_cast<long>(0), mPrevVorbisBlockSize);
   mGranulepos = last->granulepos;
 
   return NS_OK;
 }
 
 #ifdef MOZ_OPUS
 OpusState::OpusState(ogg_page* aBosPage) :
   OggCodecState(aBosPage, true),
@@ -929,17 +930,17 @@ bool OpusState::DecodeHeader(ogg_packet*
         return false;
 #endif
       mPreSkip = LEUint16(aPacket->packet + 10);
       mNominalRate = LEUint32(aPacket->packet + 12);
       double gain_dB = LEInt16(aPacket->packet + 16) / 256.0;
 #ifdef MOZ_SAMPLE_TYPE_FLOAT32
       mGain = static_cast<float>(pow(10,0.05*gain_dB));
 #else
-      mGain_Q16 = static_cast<int32_t>(NS_MIN(65536*pow(10,0.05*gain_dB)+0.5,
+      mGain_Q16 = static_cast<int32_t>(std::min(65536*pow(10,0.05*gain_dB)+0.5,
                                               static_cast<double>(INT32_MAX)));
 #endif
       mChannelMapping = aPacket->packet[18];
 
       if (mChannelMapping == 0) {
         // Mapping family 0 only allows two channels
         if (mChannels>2) {
           LOG(PR_LOG_DEBUG, ("Invalid Opus file: too many channels (%d) for"
--- a/content/media/ogg/OggReader.cpp
+++ b/content/media/ogg/OggReader.cpp
@@ -7,16 +7,17 @@
 #include "mozilla/DebugOnly.h"
 
 #include "nsError.h"
 #include "MediaDecoderStateMachine.h"
 #include "MediaDecoder.h"
 #include "OggReader.h"
 #include "VideoUtils.h"
 #include "theora/theoradec.h"
+#include <algorithm>
 #ifdef MOZ_OPUS
 #include "opus/opus.h"
 extern "C" {
 #include "opus/opus_multistream.h"
 }
 #endif
 #include "nsTimeRanges.h"
 #include "mozilla/TimeStamp.h"
@@ -450,26 +451,26 @@ nsresult OggReader::DecodeOpus(ogg_packe
     return NS_ERROR_FAILURE;
   NS_ASSERTION(ret == frames, "Opus decoded too few audio samples");
 
   int64_t endFrame = aPacket->granulepos;
   int64_t startFrame;
   // If this is the last packet, perform end trimming.
   if (aPacket->e_o_s && mOpusState->mPrevPacketGranulepos != -1) {
     startFrame = mOpusState->mPrevPacketGranulepos;
-    frames = static_cast<int32_t>(NS_MAX(static_cast<int64_t>(0),
-                                         NS_MIN(endFrame - startFrame,
+    frames = static_cast<int32_t>(std::max(static_cast<int64_t>(0),
+                                         std::min(endFrame - startFrame,
                                                 static_cast<int64_t>(frames))));
   } else {
     startFrame = endFrame - frames;
   }
 
   // Trim the initial frames while the decoder is settling.
   if (mOpusState->mSkip > 0) {
-    int32_t skipFrames = NS_MIN(mOpusState->mSkip, frames);
+    int32_t skipFrames = std::min(mOpusState->mSkip, frames);
     if (skipFrames == frames) {
       // discard the whole packet
       mOpusState->mSkip -= frames;
       LOG(PR_LOG_DEBUG, ("Opus decoder skipping %d frames"
                          " (whole packet)", frames));
       return NS_OK;
     }
     int32_t keepFrames = frames - skipFrames;
@@ -984,30 +985,30 @@ int64_t OggReader::RangeEndTime(int64_t 
         if (endTime != -1 || readStartOffset == 0) {
           // We have encountered a page before, or we're at the end of file.
           break;
         }
         mustBackOff = false;
         prevChecksumAfterSeek = checksumAfterSeek;
         checksumAfterSeek = 0;
         ogg_sync_reset(&sync.mState);
-        readStartOffset = NS_MAX(static_cast<int64_t>(0), readStartOffset - step);
+        readStartOffset = std::max(static_cast<int64_t>(0), readStartOffset - step);
         // There's no point reading more than the maximum size of
         // an Ogg page into data we've previously scanned. Any data
         // between readLimitOffset and aEndOffset must be garbage
         // and we can ignore it thereafter.
-        readLimitOffset = NS_MIN(readLimitOffset,
+        readLimitOffset = std::min(readLimitOffset,
                                  readStartOffset + maxOggPageSize);
-        readHead = NS_MAX(aStartOffset, readStartOffset);
+        readHead = std::max(aStartOffset, readStartOffset);
       }
 
-      int64_t limit = NS_MIN(static_cast<int64_t>(UINT32_MAX),
+      int64_t limit = std::min(static_cast<int64_t>(UINT32_MAX),
                              aEndOffset - readHead);
-      limit = NS_MAX(static_cast<int64_t>(0), limit);
-      limit = NS_MIN(limit, static_cast<int64_t>(step));
+      limit = std::max(static_cast<int64_t>(0), limit);
+      limit = std::min(limit, static_cast<int64_t>(step));
       uint32_t bytesToRead = static_cast<uint32_t>(limit);
       uint32_t bytesRead = 0;
       char* buffer = ogg_sync_buffer(&sync.mState, bytesToRead);
       NS_ASSERTION(buffer, "Must have buffer");
       nsresult res;
       if (aCachedDataOnly) {
         res = resource->ReadFromCache(buffer, readHead, bytesToRead);
         NS_ENSURE_SUCCESS(res, -1);
@@ -1273,17 +1274,17 @@ nsresult OggReader::SeekInBufferedRange(
       // First decoded frame isn't a keyframe, seek back to previous keyframe,
       // otherwise we'll get visual artifacts.
       NS_ASSERTION(video->mTimecode != -1, "Must have a granulepos");
       int shift = mTheoraState->mInfo.keyframe_granule_shift;
       int64_t keyframeGranulepos = (video->mTimecode >> shift) << shift;
       int64_t keyframeTime = mTheoraState->StartTime(keyframeGranulepos);
       SEEK_LOG(PR_LOG_DEBUG, ("Keyframe for %lld is at %lld, seeking back to it",
                               video->mTime, keyframeTime));
-      aAdjustedTarget = NS_MIN(aAdjustedTarget, keyframeTime);
+      aAdjustedTarget = std::min(aAdjustedTarget, keyframeTime);
     }
   }
   if (aAdjustedTarget < aTarget) {
     SeekRange k = SelectSeekRange(aRanges,
                                   aAdjustedTarget,
                                   aStartTime,
                                   aEndTime,
                                   false);
@@ -1312,19 +1313,19 @@ nsresult OggReader::SeekInUnbuffered(int
   // is buffered (compared to just doing a bisection to exactly find the
   // keyframe).
   int64_t keyframeOffsetMs = 0;
   if (HasVideo() && mTheoraState) {
     keyframeOffsetMs = mTheoraState->MaxKeyframeOffset();
   }
   // Add in the Opus pre-roll if necessary, as well.
   if (HasAudio() && mOpusState) {
-    keyframeOffsetMs = NS_MAX(keyframeOffsetMs, SEEK_OPUS_PREROLL);
+    keyframeOffsetMs = std::max(keyframeOffsetMs, SEEK_OPUS_PREROLL);
   }
-  int64_t seekTarget = NS_MAX(aStartTime, aTarget - keyframeOffsetMs);
+  int64_t seekTarget = std::max(aStartTime, aTarget - keyframeOffsetMs);
   // Minimize the bisection search space using the known timestamps from the
   // buffered ranges.
   SeekRange k = SelectSeekRange(aRanges, seekTarget, aStartTime, aEndTime, false);
   return SeekBisection(seekTarget, k, SEEK_FUZZ_USECS);
 }
 
 nsresult OggReader::Seek(int64_t aTarget,
                            int64_t aStartTime,
@@ -1335,17 +1336,17 @@ nsresult OggReader::Seek(int64_t aTarget
   if (mIsChained)
     return NS_ERROR_FAILURE;
   LOG(PR_LOG_DEBUG, ("%p About to seek to %lld", mDecoder, aTarget));
   nsresult res;
   MediaResource* resource = mDecoder->GetResource();
   NS_ENSURE_TRUE(resource != nullptr, NS_ERROR_FAILURE);
   int64_t adjustedTarget = aTarget;
   if (HasAudio() && mOpusState){
-    adjustedTarget = NS_MAX(aStartTime, aTarget - SEEK_OPUS_PREROLL);
+    adjustedTarget = std::max(aStartTime, aTarget - SEEK_OPUS_PREROLL);
   }
 
   if (adjustedTarget == aStartTime) {
     // We've seeked to the media start. Just seek to the offset of the first
     // content page.
     res = resource->Seek(nsISeekableStream::NS_SEEK_SET, 0);
     NS_ENSURE_SUCCESS(res,res);
 
@@ -1413,17 +1414,17 @@ PageSync(MediaResource* aResource,
   int64_t readHead = aOffset;
   while (ret <= 0) {
     ret = ogg_sync_pageseek(aState, aPage);
     if (ret == 0) {
       char* buffer = ogg_sync_buffer(aState, PAGE_STEP);
       NS_ASSERTION(buffer, "Must have a buffer");
 
       // Read from the file into the buffer
-      int64_t bytesToRead = NS_MIN(static_cast<int64_t>(PAGE_STEP),
+      int64_t bytesToRead = std::min(static_cast<int64_t>(PAGE_STEP),
                                    aEndOffset - readHead);
       NS_ASSERTION(bytesToRead <= UINT32_MAX, "bytesToRead range check");
       if (bytesToRead <= 0) {
         return PAGE_SYNC_END_OF_RANGE;
       }
       nsresult rv = NS_OK;
       if (aCachedDataOnly) {
         rv = aResource->ReadFromCache(buffer, readHead,
@@ -1484,17 +1485,17 @@ nsresult OggReader::SeekBisection(int64_
   // the seek target.
   ogg_int64_t startOffset = aRange.mOffsetStart;
   ogg_int64_t startTime = aRange.mTimeStart;
   ogg_int64_t startLength = 0; // Length of the page at startOffset.
   ogg_int64_t endOffset = aRange.mOffsetEnd;
   ogg_int64_t endTime = aRange.mTimeEnd;
 
   ogg_int64_t seekTarget = aTarget;
-  int64_t seekLowerBound = NS_MAX(static_cast<int64_t>(0), aTarget - aFuzz);
+  int64_t seekLowerBound = std::max(static_cast<int64_t>(0), aTarget - aFuzz);
   int hops = 0;
   DebugOnly<ogg_int64_t> previousGuess = -1;
   int backsteps = 0;
   const int maxBackStep = 10;
   NS_ASSERTION(static_cast<uint64_t>(PAGE_STEP) * pow(2.0, maxBackStep) < INT32_MAX,
                "Backstep calculation must not overflow");
 
   // Seek via bisection search. Loop until we find the offset where the page
@@ -1531,17 +1532,17 @@ nsresult OggReader::SeekBisection(int64_
         break;
       }
 
       // Guess bisection point.
       duration = endTime - startTime;
       target = (double)(seekTarget - startTime) / (double)duration;
       guess = startOffset + startLength +
               static_cast<ogg_int64_t>((double)interval * target);
-      guess = NS_MIN(guess, endOffset - PAGE_STEP);
+      guess = std::min(guess, endOffset - PAGE_STEP);
       if (mustBackoff) {
         // We previously failed to determine the time at the guess offset,
         // probably because we ran out of data to decode. This usually happens
         // when we guess very close to the end offset. So reduce the guess
         // offset using an exponential backoff until we determine the time.
         SEEK_LOG(PR_LOG_DEBUG, ("Backing off %d bytes, backsteps=%d",
           static_cast<int32_t>(PAGE_STEP * pow(2.0, backsteps)), backsteps));
         guess -= PAGE_STEP * static_cast<ogg_int64_t>(pow(2.0, backsteps));
@@ -1551,24 +1552,24 @@ nsresult OggReader::SeekBisection(int64_
           // range. This means we couldn't find a seek termination position
           // near the end of the seek range, so just set the seek termination
           // condition, and break out of the bisection loop. We'll begin
           // decoding from the start of the seek range.
           interval = 0;
           break;
         }
 
-        backsteps = NS_MIN(backsteps + 1, maxBackStep);
+        backsteps = std::min(backsteps + 1, maxBackStep);
         // We reset mustBackoff. If we still need to backoff further, it will
         // be set to true again.
         mustBackoff = false;
       } else {
         backsteps = 0;
       }
-      guess = NS_MAX(guess, startOffset + startLength);
+      guess = std::max(guess, startOffset + startLength);
 
       SEEK_LOG(PR_LOG_DEBUG, ("Seek loop start[o=%lld..%lld t=%lld] "
                               "end[o=%lld t=%lld] "
                               "interval=%lld target=%lf guess=%lld",
                               startOffset, (startOffset+startLength), startTime,
                               endOffset, endTime, interval, target, guess));
 
       NS_ASSERTION(guess >= startOffset + startLength, "Guess must be after range start");
@@ -1669,17 +1670,17 @@ nsresult OggReader::SeekBisection(int64_
         // We should backoff; cause the guess to back off from the end, so
         // that we've got more room to capture.
         mustBackoff = true;
         continue;
       }
 
       // We've found appropriate time stamps here. Proceed to bisect
       // the search space.
-      granuleTime = NS_MAX(audioTime, videoTime);
+      granuleTime = std::max(audioTime, videoTime);
       NS_ASSERTION(granuleTime > 0, "Must get a granuletime");
       break;
     } // End of "until we determine time at guess offset" loop.
 
     if (interval == 0) {
       // Seek termination condition; we've found the page boundary of the
       // last page before the target, and the first page after the target.
       SEEK_LOG(PR_LOG_DEBUG, ("Terminating seek at offset=%lld", startOffset));
--- a/content/media/wave/WaveReader.cpp
+++ b/content/media/wave/WaveReader.cpp
@@ -9,16 +9,17 @@
 #include "WaveReader.h"
 #include "nsTimeRanges.h"
 #include "MediaDecoderStateMachine.h"
 #include "VideoUtils.h"
 
 #include "mozilla/StandardInteger.h"
 #include "mozilla/Util.h"
 #include "mozilla/CheckedInt.h"
+#include <algorithm>
 
 namespace mozilla {
 
 // Un-comment to enable logging of seek bisections.
 //#define SEEK_LOGGING
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gMediaDecoderLog;
@@ -193,17 +194,17 @@ bool WaveReader::DecodeAudioData()
   NS_ASSERTION(mDecoder->OnDecodeThread(), "Should be on decode thread.");
 
   int64_t pos = GetPosition() - mWavePCMOffset;
   int64_t len = GetDataLength();
   int64_t remaining = len - pos;
   NS_ASSERTION(remaining >= 0, "Current wave position is greater than wave file length");
 
   static const int64_t BLOCK_SIZE = 4096;
-  int64_t readSize = NS_MIN(BLOCK_SIZE, remaining);
+  int64_t readSize = std::min(BLOCK_SIZE, remaining);
   int64_t frames = readSize / mFrameSize;
 
   PR_STATIC_ASSERT(uint64_t(BLOCK_SIZE) < UINT_MAX / sizeof(AudioDataValue) / MAX_CHANNELS);
   const size_t bufferSize = static_cast<size_t>(frames * mChannels);
   nsAutoArrayPtr<AudioDataValue> sampleBuffer(new AudioDataValue[bufferSize]);
 
   PR_STATIC_ASSERT(uint64_t(BLOCK_SIZE) < UINT_MAX / sizeof(char));
   nsAutoArrayPtr<char> dataBuffer(new char[static_cast<size_t>(readSize)]);
@@ -257,17 +258,17 @@ nsresult WaveReader::Seek(int64_t aTarge
   NS_ASSERTION(mDecoder->OnDecodeThread(), "Should be on decode thread.");
   LOG(PR_LOG_DEBUG, ("%p About to seek to %lld", mDecoder, aTarget));
   if (NS_FAILED(ResetDecode())) {
     return NS_ERROR_FAILURE;
   }
   double d = BytesToTime(GetDataLength());
   NS_ASSERTION(d < INT64_MAX / USECS_PER_S, "Duration overflow"); 
   int64_t duration = static_cast<int64_t>(d * USECS_PER_S);
-  double seekTime = NS_MIN(aTarget, duration) / static_cast<double>(USECS_PER_S);
+  double seekTime = std::min(aTarget, duration) / static_cast<double>(USECS_PER_S);
   int64_t position = RoundDownToFrame(static_cast<int64_t>(TimeToBytes(seekTime)));
   NS_ASSERTION(INT64_MAX - mWavePCMOffset > position, "Integer overflow during wave seek");
   position += mWavePCMOffset;
   return mDecoder->GetResource()->Seek(nsISeekableStream::NS_SEEK_SET, position);
 }
 
 static double RoundToUsecs(double aSeconds) {
   return floor(aSeconds * USECS_PER_S) / USECS_PER_S;
@@ -489,18 +490,18 @@ int64_t
 WaveReader::GetDataLength()
 {
   int64_t length = mWaveLength;
   // If the decoder has a valid content length, and it's shorter than the
   // expected length of the PCM data, calculate the playback duration from
   // the content length rather than the expected PCM data length.
   int64_t streamLength = mDecoder->GetResource()->GetLength();
   if (streamLength >= 0) {
-    int64_t dataLength = NS_MAX<int64_t>(0, streamLength - mWavePCMOffset);
-    length = NS_MIN(dataLength, length);
+    int64_t dataLength = std::max<int64_t>(0, streamLength - mWavePCMOffset);
+    length = std::min(dataLength, length);
   }
   return length;
 }
 
 int64_t
 WaveReader::GetPosition()
 {
   return mDecoder->GetResource()->Tell();
@@ -659,17 +660,17 @@ WaveReader::LoadAllChunks(nsAutoPtr<nsHT
     if (!forward.isValid() || forward.value() < 0) {
       return false;
     }
 
     static const int64_t MAX_CHUNK_SIZE = 1 << 16;
     PR_STATIC_ASSERT(uint64_t(MAX_CHUNK_SIZE) < UINT_MAX / sizeof(char));
     nsAutoArrayPtr<char> chunk(new char[MAX_CHUNK_SIZE]);
     while (forward.value() > 0) {
-      int64_t size = NS_MIN(forward.value(), MAX_CHUNK_SIZE);
+      int64_t size = std::min(forward.value(), MAX_CHUNK_SIZE);
       if (!ReadAll(chunk.get(), size)) {
         return false;
       }
       forward -= size;
     }
   }
 
   return false;
--- a/content/media/webm/WebMBufferedParser.cpp
+++ b/content/media/webm/WebMBufferedParser.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 "nsAlgorithm.h"
 #include "WebMBufferedParser.h"
 #include "nsTimeRanges.h"
 #include "nsThreadUtils.h"
+#include <algorithm>
 
 namespace mozilla {
 
 static const double NS_PER_S = 1e9;
 
 static uint32_t
 VIntLength(unsigned char aFirstByte, uint32_t* aMask)
 {
@@ -153,17 +154,17 @@ void WebMBufferedParser::Append(const un
         mSkipBytes = uint32_t(mBlockSize);
         mState = SKIP_DATA;
         mNextState = ANY_BLOCK_SYNC;
       }
       break;
     case SKIP_DATA:
       if (mSkipBytes) {
         uint32_t left = aLength - (p - aBuffer);
-        left = NS_MIN(left, mSkipBytes);
+        left = std::min(left, mSkipBytes);
         p += left;
         mSkipBytes -= left;
       } else {
         mState = mNextState;
       }
       break;
     case SKIP_ELEMENT:
       mSkipBytes = uint32_t(mVInt);
--- a/content/smil/nsSMILAnimationController.cpp
+++ b/content/smil/nsSMILAnimationController.cpp
@@ -8,16 +8,17 @@
 #include "nsSMILCSSProperty.h"
 #include "nsCSSProps.h"
 #include "nsITimer.h"
 #include "mozilla/dom/Element.h"
 #include "nsIDocument.h"
 #include "nsISMILAnimationElement.h"
 #include "nsIDOMSVGAnimationElement.h"
 #include "nsSMILTimedElement.h"
+#include <algorithm>
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 //----------------------------------------------------------------------
 // nsSMILAnimationController implementation
 
 //----------------------------------------------------------------------
@@ -113,17 +114,17 @@ void
 nsSMILAnimationController::WillRefresh(mozilla::TimeStamp aTime)
 {
   // Although we never expect aTime to go backwards, when we initialise the
   // animation controller, if we can't get hold of a refresh driver we
   // initialise mCurrentSampleTime to Now(). It may be possible that after
   // doing so we get sampled by a refresh driver whose most recent refresh time
   // predates when we were initialised, so to be safe we make sure to take the
   // most recent time here.
-  aTime = NS_MAX(mCurrentSampleTime, aTime);
+  aTime = std::max(mCurrentSampleTime, aTime);
 
   // Sleep detection: If the time between samples is a whole lot greater than we
   // were expecting then we assume the computer went to sleep or someone's
   // messing with the clock. In that case, fiddle our parent offset and use our
   // average time between samples to calculate the new sample time. This
   // prevents us from hanging while trying to catch up on all the missed time.
 
   // Smoothing of coefficient for the average function. 0.2 should let us track
@@ -557,34 +558,34 @@ nsSMILAnimationController::DoMilestoneSa
     // Due to negative offsets, early ends and the like, a timed element might
     // register a milestone that is actually in the past. That's fine, but it's
     // still only going to get *sampled* with whatever time we're up to and no
     // earlier.
     //
     // Because we're only performing this clamping at the last moment, the
     // animations will still all get sampled in the correct order and
     // dependencies will be appropriately resolved.
-    sampleTime = NS_MAX(nextMilestone.mTime, sampleTime);
+    sampleTime = std::max(nextMilestone.mTime, sampleTime);
 
     for (uint32_t i = 0; i < length; ++i) {
       nsISMILAnimationElement* elem = params.mElements[i].get();
       NS_ABORT_IF_FALSE(elem, "NULL animation element in list");
       nsSMILTimeContainer* container = elem->GetTimeContainer();
       if (!container)
         // The container may be nullptr if the element has been detached from its
         // parent since registering a milestone.
         continue;
 
       nsSMILTimeValue containerTimeValue =
         container->ParentToContainerTime(sampleTime);
       if (!containerTimeValue.IsDefinite())
         continue;
 
       // Clamp the converted container time to non-negative values.
-      nsSMILTime containerTime = NS_MAX<nsSMILTime>(0, containerTimeValue.GetMillis());
+      nsSMILTime containerTime = std::max<nsSMILTime>(0, containerTimeValue.GetMillis());
 
       if (nextMilestone.mIsEnd) {
         elem->TimedElement().SampleEndAt(containerTime);
       } else {
         elem->TimedElement().SampleAt(containerTime);
       }
     }
   }
--- a/content/smil/nsSMILAnimationFunction.cpp
+++ b/content/smil/nsSMILAnimationFunction.cpp
@@ -14,16 +14,17 @@
 #include "nsCOMPtr.h"
 #include "nsCOMArray.h"
 #include "nsIContent.h"
 #include "nsAutoPtr.h"
 #include "nsContentUtils.h"
 #include "nsReadableUtils.h"
 #include "nsString.h"
 #include <math.h>
+#include <algorithm>
 
 //----------------------------------------------------------------------
 // Static members
 
 nsAttrValue::EnumTable nsSMILAnimationFunction::sAccumulateTable[] = {
       {"none", false},
       {"sum", true},
       {nullptr, 0}
@@ -549,17 +550,17 @@ nsSMILAnimationFunction::ComputePacedPos
 #endif
       aValues[i].ComputeDistance(aValues[i+1], curIntervalDist);
     NS_ABORT_IF_FALSE(NS_SUCCEEDED(rv),
                       "If we got through ComputePacedTotalDistance, we should "
                       "be able to recompute each sub-distance without errors");
 
     NS_ASSERTION(curIntervalDist >= 0, "distance values must be non-negative");
     // Clamp distance value at 0, just in case ComputeDistance is evil.
-    curIntervalDist = NS_MAX(curIntervalDist, 0.0);
+    curIntervalDist = std::max(curIntervalDist, 0.0);
 
     if (remainingDist >= curIntervalDist) {
       remainingDist -= curIntervalDist;
     } else {
       // NOTE: If we get here, then curIntervalDist necessarily is not 0. Why?
       // Because this clause is only hit when remainingDist < curIntervalDist,
       // and if curIntervalDist were 0, that would mean remainingDist would
       // have to be < 0.  But that can't happen, because remainingDist (as
@@ -600,17 +601,17 @@ nsSMILAnimationFunction::ComputePacedTot
     nsresult rv = aValues[i].ComputeDistance(aValues[i+1], tmpDist);
     if (NS_FAILED(rv)) {
       return COMPUTE_DISTANCE_ERROR;
     }
 
     // Clamp distance value to 0, just in case we have an evil ComputeDistance
     // implementation somewhere
     NS_ABORT_IF_FALSE(tmpDist >= 0.0f, "distance values must be non-negative");
-    tmpDist = NS_MAX(tmpDist, 0.0);
+    tmpDist = std::max(tmpDist, 0.0);
 
     totalDistance += tmpDist;
   }
 
   return totalDistance;
 }
 
 double
--- a/content/smil/nsSMILTimeContainer.cpp
+++ b/content/smil/nsSMILTimeContainer.cpp
@@ -1,16 +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/. */
 
 #include "nsSMILTimeContainer.h"
 #include "nsSMILTimeValue.h"
 #include "nsSMILTimedElement.h"
+#include <algorithm>
 
 nsSMILTimeContainer::nsSMILTimeContainer()
 :
   mParent(nullptr),
   mCurrentTime(0L),
   mParentOffset(0L),
   mPauseStart(0L),
   mNeedsPauseSample(false),
@@ -112,17 +113,17 @@ nsSMILTimeContainer::GetCurrentTime() co
   return mCurrentTime;
 }
 
 void
 nsSMILTimeContainer::SetCurrentTime(nsSMILTime aSeekTo)
 {
   // SVG 1.1 doesn't specify what to do for negative times so we adopt SVGT1.2's
   // behaviour of clamping negative times to 0.
-  aSeekTo = NS_MAX<nsSMILTime>(0, aSeekTo);
+  aSeekTo = std::max<nsSMILTime>(0, aSeekTo);
 
   // The following behaviour is consistent with:
   // http://www.w3.org/2003/01/REC-SVG11-20030114-errata
   //  #getCurrentTime_setCurrentTime_undefined_before_document_timeline_begin
   // which says that if SetCurrentTime is called before the document timeline
   // has begun we should still adjust the offset.
   nsSMILTime parentTime = GetParentTime();
   mParentOffset = parentTime - aSeekTo;
--- a/content/smil/nsSMILTimedElement.cpp
+++ b/content/smil/nsSMILTimedElement.cpp
@@ -21,16 +21,17 @@
 #include "nsThreadUtils.h"
 #include "nsIPresShell.h"
 #include "prdtoa.h"
 #include "plstr.h"
 #include "prtime.h"
 #include "nsString.h"
 #include "mozilla/AutoRestore.h"
 #include "nsCharSeparatedTokenizer.h"
+#include <algorithm>
 
 using namespace mozilla;
 
 //----------------------------------------------------------------------
 // Helper class: InstanceTimeComparator
 
 // Upon inserting an instance time into one of our instance time lists we assign
 // it a serial number. This allows us to sort the instance times in such a way
@@ -1817,17 +1818,17 @@ nsSMILTimedElement::CalcActiveEnd(const 
   } else {
     result = GetRepeatDuration();
   }
 
   if (aEnd.IsDefinite()) {
     nsSMILTime activeDur = aEnd.GetMillis() - aBegin.GetMillis();
 
     if (result.IsDefinite()) {
-      result.SetMillis(NS_MIN(result.GetMillis(), activeDur));
+      result.SetMillis(std::min(result.GetMillis(), activeDur));
     } else {
       result.SetMillis(activeDur);
     }
   }
 
   result = ApplyMinAndMax(result);
 
   if (result.IsDefinite()) {
@@ -1842,17 +1843,17 @@ nsSMILTimeValue
 nsSMILTimedElement::GetRepeatDuration() const
 {
   nsSMILTimeValue result;
 
   if (mRepeatCount.IsDefinite() && mRepeatDur.IsDefinite()) {
     if (mSimpleDur.IsDefinite()) {
       nsSMILTime activeDur =
         nsSMILTime(mRepeatCount * double(mSimpleDur.GetMillis()));
-      result.SetMillis(NS_MIN(activeDur, mRepeatDur.GetMillis()));
+      result.SetMillis(std::min(activeDur, mRepeatDur.GetMillis()));
     } else {
       result = mRepeatDur;
     }
   } else if (mRepeatCount.IsDefinite() && mSimpleDur.IsDefinite()) {
     nsSMILTime activeDur =
       nsSMILTime(mRepeatCount * double(mSimpleDur.GetMillis()));
     result.SetMillis(activeDur);
   } else if (mRepeatDur.IsDefinite()) {
@@ -2181,17 +2182,17 @@ nsSMILTimedElement::GetNextMilestone(nsS
     {
       // Work out what comes next: the interval end or the next repeat iteration
       nsSMILTimeValue nextRepeat;
       if (mSeekState == SEEK_NOT_SEEKING && mSimpleDur.IsDefinite()) {
         nextRepeat.SetMillis(mCurrentInterval->Begin()->Time().GetMillis() +
             (mCurrentRepeatIteration + 1) * mSimpleDur.GetMillis());
       }
       nsSMILTimeValue nextMilestone =
-        NS_MIN(mCurrentInterval->End()->Time(), nextRepeat);
+        std::min(mCurrentInterval->End()->Time(), nextRepeat);
 
       // Check for an early end before that time
       nsSMILInstanceTime* earlyEnd = CheckForEarlyEnd(nextMilestone);
       if (earlyEnd) {
         aNextMilestone.mIsEnd = true;
         aNextMilestone.mTime = earlyEnd->Time().GetMillis();
         return true;
       }
--- a/content/svg/content/src/DOMSVGLengthList.cpp
+++ b/content/svg/content/src/DOMSVGLengthList.cpp
@@ -6,16 +6,17 @@
 #include "nsSVGElement.h"
 #include "DOMSVGLengthList.h"
 #include "DOMSVGLength.h"
 #include "nsError.h"
 #include "SVGAnimatedLengthList.h"
 #include "nsCOMPtr.h"
 #include "nsContentUtils.h"
 #include "mozilla/dom/SVGLengthListBinding.h"
+#include <algorithm>
 
 // See the comment in this file's header.
 
 // local helper functions
 namespace {
 
 using mozilla::DOMSVGLength;
 
@@ -195,17 +196,17 @@ DOMSVGLengthList::InsertItemBefore(nsIDO
                                    uint32_t index,
                                    ErrorResult& error)
 {
   if (IsAnimValList()) {
     error.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR);
     return nullptr;
   }
 
-  index = NS_MIN(index, LengthNoFlush());
+  index = std::min(index, LengthNoFlush());
   if (index >= DOMSVGLength::MaxListIndex()) {
     error.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
     return nullptr;
   }
 
   nsCOMPtr<DOMSVGLength> domItem = do_QueryInterface(newItem);
   if (!domItem) {
     error.Throw(NS_ERROR_DOM_SVG_WRONG_TYPE_ERR);
--- a/content/svg/content/src/DOMSVGNumberList.cpp
+++ b/content/svg/content/src/DOMSVGNumberList.cpp
@@ -6,16 +6,17 @@
 #include "nsSVGElement.h"
 #include "DOMSVGNumberList.h"
 #include "DOMSVGNumber.h"
 #include "nsError.h"
 #include "SVGAnimatedNumberList.h"
 #include "nsCOMPtr.h"
 #include "nsContentUtils.h"
 #include "mozilla/dom/SVGNumberListBinding.h"
+#include <algorithm>
 
 // See the comment in this file's header.
 
 namespace mozilla {
 
 // local helper functions
 namespace {
 
@@ -193,17 +194,17 @@ DOMSVGNumberList::InsertItemBefore(nsIDO
                                    uint32_t index,
                                    ErrorResult& error)
 {
   if (IsAnimValList()) {
     error.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR);
     return nullptr;
   }
 
-  index = NS_MIN(index, LengthNoFlush());
+  index = std::min(index, LengthNoFlush());
   if (index >= DOMSVGNumber::MaxListIndex()) {
     error.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
     return nullptr;
   }
 
   nsCOMPtr<DOMSVGNumber> domItem = do_QueryInterface(newItem);
   if (!domItem) {
     error.Throw(NS_ERROR_DOM_SVG_WRONG_TYPE_ERR);
--- a/content/svg/content/src/DOMSVGPointList.cpp
+++ b/content/svg/content/src/DOMSVGPointList.cpp
@@ -7,16 +7,17 @@
 #include "DOMSVGPointList.h"
 #include "DOMSVGPoint.h"
 #include "nsError.h"
 #include "SVGAnimatedPointList.h"
 #include "nsCOMPtr.h"
 #include "nsSVGAttrTearoffTable.h"
 #include "nsContentUtils.h"
 #include "mozilla/dom/SVGPointListBinding.h"
+#include <algorithm>
 
 // See the comment in this file's header.
 
 // local helper functions
 namespace {
 
 using mozilla::DOMSVGPoint;
 
@@ -248,17 +249,17 @@ already_AddRefed<nsISVGPoint>
 DOMSVGPointList::InsertItemBefore(nsISVGPoint& aNewItem, uint32_t aIndex,
                                   ErrorResult& aError)
 {
   if (IsAnimValList()) {
     aError.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR);
     return nullptr;
   }
 
-  aIndex = NS_MIN(aIndex, LengthNoFlush());
+  aIndex = std::min(aIndex, LengthNoFlush());
   if (aIndex >= DOMSVGPoint::MaxListIndex()) {
     aError.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
     return nullptr;
   }
 
   nsCOMPtr<DOMSVGPoint> domItem = do_QueryInterface(&aNewItem);
   if (!domItem) {
     aError.Throw(NS_ERROR_DOM_SVG_WRONG_TYPE_ERR);
--- a/content/svg/content/src/DOMSVGStringList.cpp
+++ b/content/svg/content/src/DOMSVGStringList.cpp
@@ -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/. */
 
 #include "DOMSVGStringList.h"
 #include "DOMSVGTests.h"
 #include "nsError.h"
 #include "nsCOMPtr.h"
 #include "nsSVGAttrTearoffTable.h"
+#include <algorithm>
 
 // See the architecture comment in this file's header.
 
 namespace mozilla {
 
 static nsSVGAttrTearoffTable<SVGStringList, DOMSVGStringList>
   sSVGStringListTearoffTable;
 
@@ -109,17 +110,17 @@ DOMSVGStringList::GetItem(uint32_t index
 NS_IMETHODIMP
 DOMSVGStringList::InsertItemBefore(const nsAString & newItem,
                                    uint32_t index,
                                    nsAString & _retval)
 {
   if (newItem.IsEmpty()) { // takes care of DOMStringIsNull too
     return NS_ERROR_DOM_SYNTAX_ERR;
   }
-  index = NS_MIN(index, InternalList().Length());
+  index = std::min(index, InternalList().Length());
 
   // Ensure we have enough memory so we can avoid complex error handling below:
   if (!InternalList().SetCapacity(InternalList().Length() + 1)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   nsAttrValue emptyOrOldValue =
     mElement->WillChangeStringList(mIsConditionalProcessingAttribute,
--- a/content/svg/content/src/DOMSVGTransformList.cpp
+++ b/content/svg/content/src/DOMSVGTransformList.cpp
@@ -6,16 +6,17 @@
 #include "DOMSVGTransformList.h"
 #include "DOMSVGTransform.h"
 #include "mozilla/dom/SVGMatrix.h"
 #include "SVGAnimatedTransformList.h"
 #include "nsSVGElement.h"
 #include "nsContentUtils.h"
 #include "mozilla/dom/SVGTransformListBinding.h"
 #include "nsError.h"
+#include <algorithm>
 
 // local helper functions
 namespace {
 
 void UpdateListIndicesFromIndex(
   nsTArray<mozilla::DOMSVGTransform*>& aItemsArray,
   uint32_t aStartingIndex)
 {
@@ -192,17 +193,17 @@ already_AddRefed<DOMSVGTransform>
 DOMSVGTransformList::InsertItemBefore(DOMSVGTransform& newItem,
                                       uint32_t index, ErrorResult& error)
 {
   if (IsAnimValList()) {
     error.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR);
     return nullptr;
   }
 
-  index = NS_MIN(index, LengthNoFlush());
+  index = std::min(index, LengthNoFlush());
   if (index >= DOMSVGTransform::MaxListIndex()) {
     error.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
     return nullptr;
   }
 
   nsCOMPtr<DOMSVGTransform> domItem = &newItem;
   if (newItem.HasOwner()) {
     domItem = newItem.Clone(); // must do this before changing anything!
--- a/content/svg/content/src/SVGLength.cpp
+++ b/content/svg/content/src/SVGLength.cpp
@@ -9,16 +9,17 @@
 #include "nsSVGElement.h"
 #include "mozilla/dom/SVGSVGElement.h"
 #include "nsString.h"
 #include "nsTextFormatter.h"
 #include "prdtoa.h"
 #include "nsMathUtils.h"
 #include "SVGContentUtils.h"
 #include <limits>
+#include <algorithm>
 
 namespace mozilla {
 
 // Declare some helpers defined below:
 static void GetUnitString(nsAString& unit, uint16_t unitType);
 static uint16_t GetUnitTypeForString(const nsAString& unitStr);
 
 void
@@ -188,17 +189,17 @@ SVGLength::GetUserUnitsPerUnit(const nsS
 }
 
 /* static */ float
 SVGLength::GetUserUnitsPerPercent(const nsSVGElement *aElement, uint8_t aAxis)
 {
   if (aElement) {
     dom::SVGSVGElement *viewportElement = aElement->GetCtx();
     if (viewportElement) {
-      return NS_MAX(viewportElement->GetLength(aAxis) / 100.0f, 0.0f);
+      return std::max(viewportElement->GetLength(aAxis) / 100.0f, 0.0f);
     }
   }
   return std::numeric_limits<float>::quiet_NaN();
 }
 
 // Helpers:
 
 // These items must be at the same index as the nsIDOMSVGLength constants!
--- a/content/svg/content/src/SVGLengthListSMILType.cpp
+++ b/content/svg/content/src/SVGLengthListSMILType.cpp
@@ -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/. */
 
 #include "SVGLengthListSMILType.h"
 #include "nsSMILValue.h"
 #include "SVGLengthList.h"
 #include "nsMathUtils.h"
 #include <math.h>
+#include <algorithm>
 
 namespace mozilla {
 
 /*static*/ SVGLengthListSMILType SVGLengthListSMILType::sSingleton;
 
 //----------------------------------------------------------------------
 // nsISMILType implementation
 
@@ -262,17 +263,17 @@ SVGLengthListSMILType::Interpolate(const
                "being animated can't be zero padded");
 
   if ((start.Length() < end.Length() && !start.CanZeroPadList()) ||
       (end.Length() < start.Length() && !end.CanZeroPadList())) {
     // SVGContentUtils::ReportToConsole
     return NS_ERROR_FAILURE;
   }
 
-  if (!result.SetLength(NS_MAX(start.Length(), end.Length()))) {
+  if (!result.SetLength(std::max(start.Length(), end.Length()))) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   uint32_t i = 0;
   for (; i < start.Length() && i < end.Length(); ++i) {
     float s;
     if (start[i].GetUnit() == end[i].GetUnit()) {
       s = start[i].GetValueInCurrentUnits();
--- a/content/svg/content/src/SVGPathData.cpp
+++ b/content/svg/content/src/SVGPathData.cpp
@@ -8,16 +8,17 @@
 #include "nsError.h"
 #include "nsString.h"
 #include "nsSVGElement.h"
 #include "nsSVGPathDataParser.h"
 #include "nsSVGPathGeometryElement.h" // for nsSVGMark
 #include <stdarg.h>
 #include "SVGContentUtils.h"
 #include "SVGPathSegUtils.h"
+#include <algorithm>
 
 using namespace mozilla;
 
 static bool IsMoveto(uint16_t aSegType)
 {
   return aSegType == PATHSEG_MOVETO_ABS ||
          aSegType == PATHSEG_MOVETO_REL;
 }
@@ -194,17 +195,17 @@ SVGPathData::GetPathSegAtLength(float aD
       return segIndex;
     }
     i += 1 + SVGPathSegUtils::ArgCountForType(mData[i]);
     segIndex++;
   }
 
   NS_ABORT_IF_FALSE(i == mData.Length(), "Very, very bad - mData corrupt");
 
-  return NS_MAX(0U, segIndex - 1); // -1 because while loop takes us 1 too far
+  return std::max(0U, segIndex - 1); // -1 because while loop takes us 1 too far
 }
 
 /**
  * The SVG spec says we have to paint stroke caps for zero length subpaths:
  *
  *   http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes
  *
  * Cairo only does this for |stroke-linecap: round| and not for
--- a/content/svg/content/src/SVGPathElement.cpp
+++ b/content/svg/content/src/SVGPathElement.cpp
@@ -8,16 +8,17 @@
 #include "nsGkAtoms.h"
 #include "DOMSVGPathSeg.h"
 #include "DOMSVGPathSegList.h"
 #include "nsCOMPtr.h"
 #include "nsContentUtils.h"
 #include "mozilla/dom/SVGPathElement.h"
 #include "DOMSVGPoint.h"
 #include "gfxContext.h"
+#include <algorithm>
 
 DOMCI_NODE_DATA(SVGPathElement, mozilla::dom::SVGPathElement)
 
 NS_IMPL_NS_NEW_NAMESPACED_SVG_ELEMENT(Path)
 
 namespace mozilla {
 namespace dom {
 
@@ -89,18 +90,18 @@ SVGPathElement::GetPointAtLength(float d
   float totalLength = flat->GetLength();
   if (mPathLength.IsExplicitlySet()) {
     float pathLength = mPathLength.GetAnimValue();
     if (pathLength <= 0) {
       return NS_ERROR_FAILURE;
     }
     distance *= totalLength / pathLength;
   }
-  distance = NS_MAX(0.f,         distance);
-  distance = NS_MIN(totalLength, distance);
+  distance = std::max(0.f,         distance);
+  distance = std::min(totalLength, distance);
 
   NS_ADDREF(*_retval = new DOMSVGPoint(flat->FindPoint(gfxPoint(distance, 0))));
   return NS_OK;
 }
 
 /* unsigned long getPathSegAtLength (in float distance); */
 NS_IMETHODIMP
 SVGPathElement::GetPathSegAtLength(float distance, uint32_t *_retval)
--- a/content/svg/content/src/SVGRectElement.cpp
+++ b/content/svg/content/src/SVGRectElement.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 "mozilla/dom/SVGRectElement.h"
 #include "nsGkAtoms.h"
 #include "gfxContext.h"
 #include "mozilla/dom/SVGRectElementBinding.h"
+#include <algorithm>
 
 DOMCI_NODE_DATA(SVGRectElement, mozilla::dom::SVGRectElement)
 
 NS_IMPL_NS_NEW_NAMESPACED_SVG_ELEMENT(Rect)
 
 namespace mozilla {
 namespace dom {
 
@@ -168,18 +169,18 @@ SVGRectElement::ConstructPath(gfxContext
 
   GetAnimatedLengthValues(&x, &y, &width, &height, &rx, &ry, nullptr);
 
   /* In a perfect world, this would be handled by the DOM, and
      return a DOM exception. */
   if (width <= 0 || height <= 0)
     return;
 
-  rx = NS_MAX(rx, 0.0f);
-  ry = NS_MAX(ry, 0.0f);
+  rx = std::max(rx, 0.0f);
+  ry = std::max(ry, 0.0f);
 
   /* optimize the no rounded corners case */
   if (rx == 0 && ry == 0) {
     aCtx->Rectangle(gfxRect(x, y, width, height));
     return;
   }
 
   /* If either the 'rx' or the 'ry' attribute isn't set, then we
--- a/content/svg/content/src/SVGSVGElement.cpp
+++ b/content/svg/content/src/SVGSVGElement.cpp
@@ -34,16 +34,17 @@
 #include "SVGContentUtils.h"
 
 #include "nsEventDispatcher.h"
 #include "nsSMILTimeContainer.h"
 #include "nsSMILAnimationController.h"
 #include "nsSMILTypes.h"
 #include "nsIContentIterator.h"
 #include "SVGAngle.h"
+#include <algorithm>
 
 DOMCI_NODE_DATA(SVGSVGElement, mozilla::dom::SVGSVGElement)
 
 NS_IMPL_NS_NEW_NAMESPACED_SVG_ELEMENT_CHECK_PARSER(SVG)
 
 namespace mozilla {
 namespace dom {
 
@@ -1207,18 +1208,18 @@ SVGSVGElement::GetLength(uint8_t aCtxTyp
                                            mViewportWidth, this);
     h = ComputeSynthesizedViewBoxDimension(mLengthAttributes[ATTR_HEIGHT],
                                            mViewportHeight, this);
   } else {
     w = mViewportWidth;
     h = mViewportHeight;
   }
 
-  w = NS_MAX(w, 0.0f);
-  h = NS_MAX(h, 0.0f);
+  w = std::max(w, 0.0f);
+  h = std::max(h, 0.0f);
 
   switch (aCtxType) {
   case SVGContentUtils::X:
     return w;
   case SVGContentUtils::Y:
     return h;
   case SVGContentUtils::XY:
     return float(SVGContentUtils::ComputeNormalizedHypotenuse(w, h));
--- a/content/svg/content/src/nsSVGFilters.cpp
+++ b/content/svg/content/src/nsSVGFilters.cpp
@@ -31,16 +31,17 @@
 #include "imgIContainer.h"
 #include "nsNetUtil.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsSVGFilterElement.h"
 #include "nsSVGString.h"
 #include "nsSVGEffects.h"
 #include "gfxUtils.h"
 #include "SVGContentUtils.h"
+#include <algorithm>
 
 #if defined(XP_WIN) 
 // Prevent Windows redefining LoadImage
 #undef LoadImage
 #endif
 
 #define NUM_ENTRIES_IN_4x5_MATRIX 20
 
@@ -495,18 +496,18 @@ BoxBlur(const uint8_t *aInput, uint8_t *
         int32_t aLeftLobe, int32_t aRightLobe, bool aAlphaOnly)
 {
   int32_t boxSize = aLeftLobe + aRightLobe + 1;
   int32_t scaledDivisor = ComputeScaledDivisor(boxSize);
   int32_t sums[4] = {0, 0, 0, 0};
 
   for (int32_t i=0; i < boxSize; i++) {
     int32_t pos = aStartMinor - aLeftLobe + i;
-    pos = NS_MAX(pos, aStartMinor);
-    pos = NS_MIN(pos, aEndMinor - 1);
+    pos = std::max(pos, aStartMinor);
+    pos = std::min(pos, aEndMinor - 1);
 #define SUM(j)     sums[j] += aInput[aStrideMinor*pos + j];
     SUM(0); SUM(1); SUM(2); SUM(3);
 #undef SUM
   }
 
   aOutput += aStrideMinor*aStartMinor;
   if (aStartMinor + int32_t(boxSize) <= aEndMinor) {
     const uint8_t *lastInput = aInput + aStartMinor*aStrideMinor;
@@ -551,18 +552,18 @@ BoxBlur(const uint8_t *aInput, uint8_t *
       lastInput += aStrideMinor;
       aOutput += aStrideMinor;
 #undef SUM_PIXEL
 #undef SUM
     }
   } else {
     for (int32_t minor = aStartMinor; minor < aEndMinor; minor++) {
       int32_t tmp = minor - aLeftLobe;
-      int32_t last = NS_MAX(tmp, aStartMinor);
-      int32_t next = NS_MIN(tmp + int32_t(boxSize), aEndMinor - 1);
+      int32_t last = std::max(tmp, aStartMinor);
+      int32_t next = std::min(tmp + int32_t(boxSize), aEndMinor - 1);
 
       OUTPUT_PIXEL();
 #define SUM(j)     sums[j] += aInput[aStrideMinor*next + j] - \
                               aInput[aStrideMinor*last + j];
       if (!aAlphaOnly) { SUM(GFX_ARGB32_OFFSET_B);
                          SUM(GFX_ARGB32_OFFSET_G);
                          SUM(GFX_ARGB32_OFFSET_R); }
       SUM(GFX_ARGB32_OFFSET_A);
@@ -940,44 +941,44 @@ nsSVGFEBlendElement::Filter(nsSVGFilterI
 
   uint16_t mode = mEnumAttributes[MODE].GetAnimValue();
 
   for (int32_t x = rect.x; x < rect.XMost(); x++) {
     for (int32_t y = rect.y; y < rect.YMost(); y++) {
       uint32_t targIndex = y * stride + 4 * x;
       uint32_t qa = targetData[targIndex + GFX_ARGB32_OFFSET_A];
       uint32_t qb = sourceData[targIndex + GFX_ARGB32_OFFSET_A];
-      for (int32_t i = NS_MIN(GFX_ARGB32_OFFSET_B, GFX_ARGB32_OFFSET_R);
-           i <= NS_MAX(GFX_ARGB32_OFFSET_B, GFX_ARGB32_OFFSET_R); i++) {
+      for (int32_t i = std::min(GFX_ARGB32_OFFSET_B, GFX_ARGB32_OFFSET_R);
+           i <= std::max(GFX_ARGB32_OFFSET_B, GFX_ARGB32_OFFSET_R); i++) {
         uint32_t ca = targetData[targIndex + i];
         uint32_t cb = sourceData[targIndex + i];
         uint32_t val;
         switch (mode) {
           case nsSVGFEBlendElement::SVG_MODE_NORMAL:
             val = (255 - qa) * cb + 255 * ca;
             break;
           case nsSVGFEBlendElement::SVG_MODE_MULTIPLY:
             val = ((255 - qa) * cb + (255 - qb + cb) * ca);
             break;
           case nsSVGFEBlendElement::SVG_MODE_SCREEN:
             val = 255 * (cb + ca) - ca * cb;
             break;
           case nsSVGFEBlendElement::SVG_MODE_DARKEN:
-            val = NS_MIN((255 - qa) * cb + 255 * ca,
+            val = std::min((255 - qa) * cb + 255 * ca,
                          (255 - qb) * ca + 255 * cb);
             break;
           case nsSVGFEBlendElement::SVG_MODE_LIGHTEN:
-            val = NS_MAX((255 - qa) * cb + 255 * ca,
+            val = std::max((255 - qa) * cb + 255 * ca,
                          (255 - qb) * ca + 255 * cb);
             break;
           default:
             return NS_ERROR_FAILURE;
             break;
         }
-        val = NS_MIN(val / 255, 255U);
+        val = std::min(val / 255, 255U);
         targetData[targIndex + i] =  static_cast<uint8_t>(val);
       }
       uint32_t alpha = 255 * 255 - (255 - qa) * (255 - qb);
       FAST_DIVIDE_BY_255(targetData[targIndex + GFX_ARGB32_OFFSET_A], alpha);
     }
   }
   return NS_OK;
 }
@@ -1992,60 +1993,60 @@ nsSVGComponentTransferFunctionElement::G
   case nsIDOMSVGComponentTransferFunctionElement::SVG_FECOMPONENTTRANSFER_TYPE_TABLE:
   {
     if (tableValues.Length() <= 1)
       break;
 
     for (i = 0; i < 256; i++) {
       uint32_t k = (i * (tvLength - 1)) / 255;
       float v1 = tableValues[k];
-      float v2 = tableValues[NS_MIN(k + 1, tvLength - 1)];
+      float v2 = tableValues[std::min(k + 1, tvLength - 1)];
       int32_t val =
         int32_t(255 * (v1 + (i/255.0f - k/float(tvLength-1))*(tvLength - 1)*(v2 - v1)));
-      val = NS_MIN(255, val);
-      val = NS_MAX(0, val);
+      val = std::min(255, val);
+      val = std::max(0, val);
       aTable[i] = val;
     }
     break;
   }
 
   case nsIDOMSVGComponentTransferFunctionElement::SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE:
   {
     if (tableValues.Length() <= 1)
       break;
 
     for (i = 0; i < 256; i++) {
       uint32_t k = (i * tvLength) / 255;
-      k = NS_MIN(k, tvLength - 1);
+      k = std::min(k, tvLength - 1);
       float v = tableValues[k];
       int32_t val = int32_t(255 * v);
-      val = NS_MIN(255, val);
-      val = NS_MAX(0, val);
+      val = std::min(255, val);
+      val = std::max(0, val);
       aTable[i] = val;
     }
     break;
   }
 
   case nsIDOMSVGComponentTransferFunctionElement::SVG_FECOMPONENTTRANSFER_TYPE_LINEAR:
   {
     for (i = 0; i < 256; i++) {
       int32_t val = int32_t(slope * i + 255 * intercept);
-      val = NS_MIN(255, val);
-      val = NS_MAX(0, val);
+      val = std::min(255, val);
+      val = std::max(0, val);
       aTable[i] = val;
     }
     break;
   }
 
   case nsIDOMSVGComponentTransferFunctionElement::SVG_FECOMPONENTTRANSFER_TYPE_GAMMA:
   {
     for (i = 0; i < 256; i++) {
       int32_t val = int32_t(255 * (amplitude * pow(i / 255.0f, exponent) + offset));
-      val = NS_MIN(255, val);
-      val = NS_MAX(0, val);
+      val = std::min(255, val);
+      val = std::max(0, val);
       aTable[i] = val;
     }
     break;
   }
 
   case nsIDOMSVGComponentTransferFunctionElement::SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY:
   default:
     break;
@@ -3351,18 +3352,18 @@ nsSVGFETurbulenceElement::Filter(nsSVGFi
           col[i] = Turbulence(i, point, fX, fY, octaves, false,
                               doStitch, filterX, filterY, filterWidth, filterHeight) * 255;
       } else {
         for (int i = 0; i < 4; i++)
           col[i] = (Turbulence(i, point, fX, fY, octaves, true,
                                doStitch, filterX, filterY, filterWidth, filterHeight) * 255 + 255) / 2;
       }
       for (int i = 0; i < 4; i++) {
-        col[i] = NS_MIN(col[i], 255.f);
-        col[i] = NS_MAX(col[i], 0.f);
+        col[i] = std::min(col[i], 255.f);
+        col[i] = std::max(col[i], 0.f);
       }
 
       uint8_t r, g, b, a;
       a = uint8_t(col[3]);
       FAST_DIVIDE_BY_255(r, unsigned(col[0]) * a);
       FAST_DIVIDE_BY_255(g, unsigned(col[1]) * a);
       FAST_DIVIDE_BY_255(b, unsigned(col[2]) * a);
 
@@ -3752,17 +3753,17 @@ nsSVGFEMorphologyElement::GetSourceImage
 
 nsIntRect
 nsSVGFEMorphologyElement::InflateRect(const nsIntRect& aRect,
                                       const nsSVGFilterInstance& aInstance)
 {
   int32_t rx, ry;
   GetRXY(&rx, &ry, aInstance);
   nsIntRect result = aRect;
-  result.Inflate(NS_MAX(0, rx), NS_MAX(0, ry));
+  result.Inflate(std::max(0, rx), std::max(0, ry));
   return result;
 }
 
 nsIntRect
 nsSVGFEMorphologyElement::ComputeTargetBBox(const nsTArray<nsIntRect>& aSourceBBoxes,
         const nsSVGFilterInstance& aInstance)
 {
   return InflateRect(aSourceBBoxes[0], aInstance);
@@ -3815,35 +3816,35 @@ nsSVGFEMorphologyElement::Filter(nsSVGFi
     // XXX SVGContentUtils::ReportToConsole()
     return NS_OK;
   }
   if (rx == 0 && ry == 0) {
     return NS_OK;
   }
 
   // Clamp radii to prevent completely insane values:
-  rx = NS_MIN(rx, 100000);
-  ry = NS_MIN(ry, 100000);
+  rx = std::min(rx, 100000);
+  ry = std::min(ry, 100000);
 
   uint8_t* sourceData = aSources[0]->mImage->Data();
   uint8_t* targetData = aTarget->mImage->Data();
   int32_t stride = aTarget->mImage->Stride();
   uint8_t extrema[4];         // RGBA magnitude of extrema
   uint16_t op = mEnumAttributes[OPERATOR].GetAnimValue();
 
   // Scan the kernel for each pixel to determine max/min RGBA values.
   for (int32_t y = rect.y; y < rect.YMost(); y++) {
-    int32_t startY = NS_MAX(0, y - ry);
+    int32_t startY = std::max(0, y - ry);
     // We need to read pixels not just in 'rect', which is limited to
     // the dirty part of our filter primitive subregion, but all pixels in
     // the given radii from the source surface, so use the surface size here.
-    int32_t endY = NS_MIN(y + ry, instance->GetSurfaceHeight() - 1);
+    int32_t endY = std::min(y + ry, instance->GetSurfaceHeight() - 1);
     for (int32_t x = rect.x; x < rect.XMost(); x++) {
-      int32_t startX = NS_MAX(0, x - rx);
-      int32_t endX = NS_MIN(x + rx, instance->GetSurfaceWidth() - 1);
+      int32_t startX = std::max(0, x - rx);
+      int32_t endX = std::min(x + rx, instance->GetSurfaceWidth() - 1);
       int32_t targIndex = y * stride + 4 * x;
 
       for (int32_t i = 0; i < 4; i++) {
         extrema[i] = sourceData[targIndex + i];
       }
       for (int32_t y1 = startY; y1 <= endY; y1++) {
         for (int32_t x1 = startX; x1 <= endX; x1++) {
           for (int32_t i = 0; i < 4; i++) {
@@ -4178,18 +4179,18 @@ nsSVGFEConvolveMatrixElement::ComputeCha
 {
   // XXX Precise results are possible but we're going to skip that work
   // for now.
   return GetMaxRect();
 }
 
 static int32_t BoundInterval(int32_t aVal, int32_t aMax)
 {
-  aVal = NS_MAX(aVal, 0);
-  return NS_MIN(aVal, aMax - 1);
+  aVal = std::max(aVal, 0);
+  return std::min(aVal, aMax - 1);
 }
 
 static void
 ConvolvePixel(const uint8_t *aSourceData,
               uint8_t *aTargetData,
               int32_t aWidth, int32_t aHeight,
               int32_t aStride,
               int32_t aX, int32_t aY,
@@ -5078,17 +5079,17 @@ nsSVGFELightingElement::Filter(nsSVGFilt
                                   &specularExponent,
                                   &limitingConeAngle,
                                   nullptr);
     instance->ConvertLocation(lightPos);
     instance->ConvertLocation(pointsAt);
 
     if (spot->mNumberAttributes[nsSVGFESpotLightElement::LIMITING_CONE_ANGLE].
                                   IsExplicitlySet()) {
-      cosConeAngle = NS_MAX<double>(cos(limitingConeAngle * radPerDeg), 0.0);
+      cosConeAngle = std::max<double>(cos(limitingConeAngle * radPerDeg), 0.0);
     }
   }
 
   float surfaceScale = mNumberAttributes[SURFACE_SCALE].GetAnimValue();
 
   const nsIntRect& dataRect = info.mDataRect;
   int32_t stride = info.mSource->Stride();
   uint8_t *sourceData = info.mSource->Data();
@@ -5296,21 +5297,21 @@ nsSVGFEDiffuseLightingElement::LightPixe
                                           nscolor color, uint8_t *targetData)
 {
   float diffuseNL =
     mNumberAttributes[DIFFUSE_CONSTANT].GetAnimValue() * DOT(N, L);
 
   if (diffuseNL < 0) diffuseNL = 0;
 
   targetData[GFX_ARGB32_OFFSET_B] =
-    NS_MIN(uint32_t(diffuseNL * NS_GET_B(color)), 255U);
+    std::min(uint32_t(diffuseNL * NS_GET_B(color)), 255U);
   targetData[GFX_ARGB32_OFFSET_G] =
-    NS_MIN(uint32_t(diffuseNL * NS_GET_G(color)), 255U);
+    std::min(uint32_t(diffuseNL * NS_GET_G(color)), 255U);
   targetData[GFX_ARGB32_OFFSET_R] =
-    NS_MIN(uint32_t(diffuseNL * NS_GET_R(color)), 255U);
+    std::min(uint32_t(diffuseNL * NS_GET_R(color)), 255U);
   targetData[GFX_ARGB32_OFFSET_A] = 255;
 }
 
 //---------------------SpecularLighting------------------------
 
 typedef nsSVGFELightingElement nsSVGFESpecularLightingElementBase;
 
 class nsSVGFESpecularLightingElement : public nsSVGFESpecularLightingElementBase,
@@ -5465,25 +5466,25 @@ nsSVGFESpecularLightingElement::LightPix
   bool invalid = dotNH <= 0 || kS <= 0;
   kS *= invalid ? 0 : 1;
   uint8_t minAlpha = invalid ? 255 : 0;
 
   float specularNH =
     kS * pow(dotNH, mNumberAttributes[SPECULAR_EXPONENT].GetAnimValue());
 
   targetData[GFX_ARGB32_OFFSET_B] =
-    NS_MIN(uint32_t(specularNH * NS_GET_B(color)), 255U);
+    std::min(uint32_t(specularNH * NS_GET_B(color)), 255U);
   targetData[GFX_ARGB32_OFFSET_G] =
-    NS_MIN(uint32_t(specularNH * NS_GET_G(color)), 255U);
+    std::min(uint32_t(specularNH * NS_GET_G(color)), 255U);
   targetData[GFX_ARGB32_OFFSET_R] =
-    NS_MIN(uint32_t(specularNH * NS_GET_R(color)), 255U);
+    std::min(uint32_t(specularNH * NS_GET_R(color)), 255U);
 
   targetData[GFX_ARGB32_OFFSET_A] =
-    NS_MAX(minAlpha, NS_MAX(targetData[GFX_ARGB32_OFFSET_B],
-                            NS_MAX(targetData[GFX_ARGB32_OFFSET_G],
+    std::max(minAlpha, std::max(targetData[GFX_ARGB32_OFFSET_B],
+                            std::max(targetData[GFX_ARGB32_OFFSET_G],
                                    targetData[GFX_ARGB32_OFFSET_R])));
 }
 
 //---------------------Image------------------------
 
 nsSVGElement::StringInfo nsSVGFEImageElement::sStringInfo[2] =
 {
   { &nsGkAtoms::result, kNameSpaceID_None, true },
--- a/content/xslt/src/base/txDouble.cpp
+++ b/content/xslt/src/base/txDouble.cpp
@@ -5,16 +5,17 @@
 
 #include "mozilla/FloatingPoint.h"
 
 #include "nsString.h"
 #include "txCore.h"
 #include "txXMLUtils.h"
 #include <math.h>
 #include <stdlib.h>
+#include <algorithm>
 #ifdef WIN32
 #include <float.h>
 #endif
 #include "prdtoa.h"
 
 /*
  * Utility class for doubles
  */
@@ -190,17 +191,17 @@ void txDouble::toString(double aValue, n
     if (intDigits < 1) {
         *dest = '0'; ++dest;
         *dest = '.'; ++dest;
         for (i = 0; i > intDigits; --i) {
             *dest = '0'; ++dest;
         }
     }
     // mantissa
-    int firstlen = NS_MIN<size_t>(intDigits, endp - buf);
+    int firstlen = std::min<size_t>(intDigits, endp - buf);
     for (i = 0; i < firstlen; i++) {
         *dest = buf[i]; ++dest;
     }
     if (i < endp - buf) {
         if (i > 0) {
             *dest = '.'; ++dest;
         }
         for (; i < endp - buf; i++) {
--- a/content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
+++ b/content/xslt/src/xpath/txMozillaXPathTreeWalker.cpp
@@ -18,16 +18,17 @@
 #include "nsTextFragment.h"
 #include "txXMLUtils.h"
 #include "txLog.h"
 #include "nsUnicharUtils.h"
 #include "nsAttrName.h"
 #include "nsTArray.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/StandardInteger.h"
+#include <algorithm>
 
 const uint32_t kUnknownIndex = uint32_t(-1);
 
 txXPathTreeWalker::txXPathTreeWalker(const txXPathTreeWalker& aOther)
     : mPosition(aOther.mPosition),
       mCurrentIndex(aOther.mCurrentIndex)
 {
 }
@@ -642,17 +643,17 @@ txXPathNodeUtils::comparePosition(const 
         otherNode = otherNode->GetParentNode();
     }
 
     // Walk back down along the parent-chains until we find where they split.
     int32_t total = parents.Length() - 1;
     int32_t otherTotal = otherParents.Length() - 1;
     NS_ASSERTION(total != otherTotal, "Can't have same number of parents");
 
-    int32_t lastIndex = NS_MIN(total, otherTotal);
+    int32_t lastIndex = std::min(total, otherTotal);
     int32_t i;
     parent = nullptr;
     for (i = 0; i <= lastIndex; ++i) {
         node = parents.ElementAt(total - i);
         otherNode = otherParents.ElementAt(otherTotal - i);
         if (node != otherNode) {
             if (!parent) {
                 // The two nodes are in different orphan subtrees.
--- a/content/xslt/src/xpath/txNodeSet.cpp
+++ b/content/xslt/src/xpath/txNodeSet.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 "txNodeSet.h"
 #include "txLog.h"
 #include "nsMemory.h"
 #include "txXPathTreeWalker.h"
+#include <algorithm>
 
 /**
  * Implementation of an XPath nodeset
  */
 
 #ifdef NS_BUILD_REFCNT_LOGGING
 #define LOG_CHUNK_MOVE(_start, _new_start, _count)            \
 {                                                             \
@@ -514,17 +515,17 @@ bool txNodeSet::ensureGrowSize(int32_t a
         mStart = dest;
         mEnd = dest + oldSize;
             
         return true;
     }
 
     // This isn't 100% safe. But until someone manages to make a 1gig nodeset
     // it should be ok.
-    int32_t newLength = NS_MAX(oldLength, kTxNodeSetMinSize);
+    int32_t newLength = std::max(oldLength, kTxNodeSetMinSize);
 
     while (newLength < ensureSize) {
         newLength *= kTxNodeSetGrowFactor;
     }
 
     txXPathNode* newArr = static_cast<txXPathNode*>
                                      (nsMemory::Alloc(newLength *
                                                          sizeof(txXPathNode)));
--- a/content/xslt/src/xslt/txMozillaXMLOutput.cpp
+++ b/content/xslt/src/xslt/txMozillaXMLOutput.cpp
@@ -34,16 +34,17 @@
 #include "mozilla/dom/EncodingUtils.h"
 #include "nsContentUtils.h"
 #include "txXMLUtils.h"
 #include "nsContentSink.h"
 #include "nsINode.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsError.h"
 #include "nsIFrame.h"
+#include <algorithm>
 
 using namespace mozilla::dom;
 
 #define TX_ENSURE_CURRENTNODE                           \
     NS_ASSERTION(mCurrentNode, "mCurrentNode is NULL"); \
     if (!mCurrentNode)                                  \
         return NS_ERROR_UNEXPECTED
 
@@ -651,17 +652,17 @@ txMozillaXMLOutput::createTxWrapper()
         }
 #endif
 
         if (childContent->Tag() == nsGkAtoms::documentTypeNodeName) {
 #ifdef DEBUG
             // The new documentElement should go after the document type.
             // This is needed for cases when there is no existing
             // documentElement in the document.
-            rootLocation = NS_MAX(rootLocation, j + 1);
+            rootLocation = std::max(rootLocation, j + 1);
 #endif
             ++j;
         }
         else {
             mDocument->RemoveChildAt(j, true);
 
             rv = wrapper->AppendChildTo(childContent, true);
             NS_ENSURE_SUCCESS(rv, rv);
--- a/content/xul/content/src/nsXULElement.cpp
+++ b/content/xul/content/src/nsXULElement.cpp
@@ -84,16 +84,17 @@
 #include "nsNodeUtils.h"
 #include "nsFrameLoader.h"
 #include "prlog.h"
 #include "rdf.h"
 #include "nsIControllers.h"
 #include "nsAttrValueOrString.h"
 #include "nsAttrValueInlines.h"
 #include "mozilla/Attributes.h"
+#include <algorithm>
 
 // The XUL doc interface
 #include "nsIDOMXULDocument.h"
 
 #include "nsReadableUtils.h"
 #include "nsIFrame.h"
 #include "nsNodeInfoManager.h"
 #include "nsXBLBinding.h"
@@ -816,17 +817,17 @@ nsXULElement::RemoveChildAt(uint32_t aIn
     
     if (newCurrentIndex == -2)
         controlElement->SetCurrentItem(nullptr);
     else if (newCurrentIndex > -1) {
         // Make sure the index is still valid
         int32_t treeRows;
         listBox->GetRowCount(&treeRows);
         if (treeRows > 0) {
-            newCurrentIndex = NS_MIN((treeRows - 1), newCurrentIndex);
+            newCurrentIndex = std::min((treeRows - 1), newCurrentIndex);
             nsCOMPtr<nsIDOMElement> newCurrentItem;
             listBox->GetItemAtIndex(newCurrentIndex, getter_AddRefs(newCurrentItem));
             nsCOMPtr<nsIDOMXULSelectControlItemElement> xulCurItem = do_QueryInterface(newCurrentItem);
             if (xulCurItem)
                 controlElement->SetCurrentItem(xulCurItem);
         } else {
             controlElement->SetCurrentItem(nullptr);
         }
--- a/content/xul/templates/src/nsTreeRows.cpp
+++ b/content/xul/templates/src/nsTreeRows.cpp
@@ -1,15 +1,16 @@
 /* -*- 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/. */
 
 #include "nsString.h"
 #include "nsTreeRows.h"
+#include <algorithm>
 
 nsTreeRows::Subtree*
 nsTreeRows::EnsureSubtreeFor(Subtree* aParent,
                              int32_t aChildIndex)
 {
     Subtree* subtree = GetSubtreeFor(aParent, aChildIndex);
 
     if (! subtree) {
@@ -226,17 +227,17 @@ nsTreeRows::Subtree::Clear()
     mRows = nullptr;
     mCount = mCapacity = mSubtreeSize = 0;
 }
 
 nsTreeRows::iterator
 nsTreeRows::Subtree::InsertRowAt(nsTemplateMatch* aMatch, int32_t aIndex)
 {
     if (mCount >= mCapacity || aIndex >= mCapacity) {
-        int32_t newCapacity = NS_MAX(mCapacity * 2, aIndex + 1);
+        int32_t newCapacity = std::max(mCapacity * 2, aIndex + 1);
         Row* newRows = new Row[newCapacity];
         if (! newRows)
             return iterator();
 
         for (int32_t i = mCount - 1; i >= 0; --i)
             newRows[i] = mRows[i];
 
         delete[] mRows;
--- a/docshell/base/nsDefaultURIFixup.cpp
+++ b/docshell/base/nsDefaultURIFixup.cpp
@@ -7,16 +7,17 @@
 #include "nsString.h"
 #include "nsReadableUtils.h"
 #include "nsNetUtil.h"
 #include "nsEscape.h"
 #include "nsCRT.h"
 
 #include "nsIPlatformCharset.h"
 #include "nsIFile.h"
+#include <algorithm>
 
 #ifdef MOZ_TOOLKIT_SEARCH
 #include "nsIBrowserSearchService.h"
 #endif
 
 #include "nsIURIFixup.h"
 #include "nsDefaultURIFixup.h"
 #include "mozilla/Preferences.h"
@@ -806,17 +807,17 @@ nsresult nsDefaultURIFixup::KeywordURIFi
     uint32_t dotLoc   = uint32_t(aURIString.FindChar('.'));
     uint32_t colonLoc = uint32_t(aURIString.FindChar(':'));
     uint32_t spaceLoc = uint32_t(aURIString.FindChar(' '));
     if (spaceLoc == 0) {
         // Treat this as not found
         spaceLoc = uint32_t(kNotFound);
     }
     uint32_t qMarkLoc = uint32_t(aURIString.FindChar('?'));
-    uint32_t quoteLoc = NS_MIN(uint32_t(aURIString.FindChar('"')),
+    uint32_t quoteLoc = std::min(uint32_t(aURIString.FindChar('"')),
                                uint32_t(aURIString.FindChar('\'')));
 
     if (((spaceLoc < dotLoc || quoteLoc < dotLoc) &&
          (spaceLoc < colonLoc || quoteLoc < colonLoc) &&
          (spaceLoc < qMarkLoc || quoteLoc < qMarkLoc)) ||
         qMarkLoc == 0)
     {
         KeywordToURI(aURIString, aURI);
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -2,16 +2,17 @@
 /* vim: set ts=4 sw=4 tw=80 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/dom/ContentChild.h"
 #include "mozilla/dom/TabChild.h"
 #include "mozilla/Util.h"
+#include <algorithm>
 
 #ifdef MOZ_LOGGING
 // so we can get logging even in release builds (but only for some things)
 #define FORCE_PR_LOG 1
 #endif
 
 #include "nsIBrowserDOMWindow.h"
 #include "nsIComponentManager.h"
@@ -2416,18 +2417,18 @@ nsDocShell::GetLoadedTransIndex(int32_t 
 NS_IMETHODIMP
 nsDocShell::HistoryPurged(int32_t aNumEntries)
 {
     // These indices are used for fastback cache eviction, to determine
     // which session history entries are candidates for content viewer
     // eviction.  We need to adjust by the number of entries that we
     // just purged from history, so that we look at the right session history
     // entries during eviction.
-    mPreviousTransIndex = NS_MAX(-1, mPreviousTransIndex - aNumEntries);
-    mLoadedTransIndex = NS_MAX(0, mLoadedTransIndex - aNumEntries);
+    mPreviousTransIndex = std::max(-1, mPreviousTransIndex - aNumEntries);
+    mLoadedTransIndex = std::max(0, mLoadedTransIndex - aNumEntries);
 
     int32_t count = mChildList.Count();
     for (int32_t i = 0; i < count; ++i) {
         nsCOMPtr<nsIDocShell> shell = do_QueryInterface(ChildAt(i));
         if (shell) {
             shell->HistoryPurged(aNumEntries);
         }
     }
--- a/docshell/shistory/src/nsSHEntry.cpp
+++ b/docshell/shistory/src/nsSHEntry.cpp
@@ -12,16 +12,17 @@
 #include "nsISHistory.h"
 #include "nsISHistoryInternal.h"
 #include "nsDocShellEditorData.h"
 #include "nsSHEntryShared.h"
 #include "nsILayoutHistoryState.h"
 #include "nsIContentViewer.h"
 #include "nsISupportsArray.h"
 #include "nsIStructuredCloneContainer.h"
+#include <algorithm>
 
 namespace dom = mozilla::dom;
 
 static uint32_t gEntryID = 0;
 
 //*****************************************************************************
 //***    nsSHEntry: Object Management
 //*****************************************************************************
@@ -556,17 +557,17 @@ nsSHEntry::AddChild(nsISHEntry * aChild,
       aChild->SetParent(nullptr);
       return NS_ERROR_FAILURE;
     }
   } else {
     // If the new child isn't dynamically added, it should be set to aOffset.
     // If there are dynamically added children before that, those must be
     // moved to be after aOffset.
     if (mChildren.Count() > 0) {
-      int32_t start = NS_MIN(mChildren.Count() - 1, aOffset);
+      int32_t start = std::min(mChildren.Count() - 1, aOffset);
       int32_t dynEntryIndex = -1;
       nsISHEntry* dynEntry = nullptr;
       for (int32_t i = start; i >= 0; --i) {
         nsISHEntry* entry = mChildren[i];
         if (entry) {
           bool dyn = false;
           entry->IsDynamicallyAdded(&dyn);
           if (dyn) {
--- a/docshell/shistory/src/nsSHistory.cpp
+++ b/docshell/shistory/src/nsSHistory.cpp
@@ -1,16 +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/. */
 
 // Local Includes 
 #include "nsSHistory.h"
+#include <algorithm>
 
 // Helper Classes
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #include "mozilla/Preferences.h"
 
 // Interfaces Needed
 #include "nsILayoutHistoryState.h"
@@ -659,17 +660,17 @@ nsSHistory::SetMaxLength(int32_t aMaxSiz
 }
 
 NS_IMETHODIMP
 nsSHistory::PurgeHistory(int32_t aEntries)
 {
   if (mLength <= 0 || aEntries <= 0)
     return NS_ERROR_FAILURE;
 
-  aEntries = NS_MIN(aEntries, mLength);
+  aEntries = std::min(aEntries, mLength);
   
   bool purgeHistory = true;
   NOTIFY_LISTENERS_CANCELABLE(OnHistoryPurge, purgeHistory,
                               (aEntries, &purgeHistory));
 
   if (!purgeHistory) {
     // Listener asked us not to purge
     return NS_SUCCESS_LOSS_OF_INSIGNIFICANT_DATA;
@@ -950,18 +951,18 @@ nsSHistory::EvictOutOfRangeWindowContent
     return;
   }
   NS_ASSERTION(aIndex < mLength, "aIndex is out of range");
   if (aIndex >= mLength) {
     return;
   }
 
   // Calculate the range that's safe from eviction.
-  int32_t startSafeIndex = NS_MAX(0, aIndex - gHistoryMaxViewers);
-  int32_t endSafeIndex = NS_MIN(mLength, aIndex + gHistoryMaxViewers);
+  int32_t startSafeIndex = std::max(0, aIndex - gHistoryMaxViewers);
+  int32_t endSafeIndex = std::min(mLength, aIndex + gHistoryMaxViewers);
 
   LOG(("EvictOutOfRangeWindowContentViewers(index=%d), "
        "mLength=%d. Safe range [%d, %d]",
        aIndex, mLength, startSafeIndex, endSafeIndex)); 
 
   // The content viewers in range aIndex -/+ gHistoryMaxViewers will not be
   // evicted.  Collect a set of them so we don't accidentally evict one of them
   // if it appears outside this range.
@@ -1065,35 +1066,35 @@ nsSHistory::GloballyEvictContentViewers(
     //   * history.pushState or hash navigations, in which case a copy of the
     //     content viewer should exist within the range, or
     //
     //   * bugs which cause us not to call nsSHistory::EvictContentViewers()
     //     often enough.  Once we do call EvictContentViewers() for the
     //     SHistory object in question, we'll do a full search of its history
     //     and evict the out-of-range content viewers, so we don't bother here.
     //
-    int32_t startIndex = NS_MAX(0, shist->mIndex - gHistoryMaxViewers);
-    int32_t endIndex = NS_MIN(shist->mLength - 1,
+    int32_t startIndex = std::max(0, shist->mIndex - gHistoryMaxViewers);
+    int32_t endIndex = std::min(shist->mLength - 1,
                               shist->mIndex + gHistoryMaxViewers);
     nsCOMPtr<nsISHTransaction> trans;
     shist->GetTransactionAtIndex(startIndex, getter_AddRefs(trans));
     for (int32_t i = startIndex; trans && i <= endIndex; i++) {
       nsCOMPtr<nsIContentViewer> contentViewer =
         GetContentViewerForTransaction(trans);
 
       if (contentViewer) {
         // 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 = NS_MIN(container.mDistance,
+            container.mDistance = std::min(container.mDistance,
                                          std::abs(i - shist->mIndex));
             found = true;
             break;
           }
         }
 
         // If we didn't find a TransactionAndDistance for this content viewer, make a new
         // one.
@@ -1131,18 +1132,18 @@ nsSHistory::GloballyEvictContentViewers(
     EvictContentViewerForTransaction(transactions[i].mTransaction);
 
   }
 }
 
 nsresult
 nsSHistory::EvictExpiredContentViewerForEntry(nsIBFCacheEntry *aEntry)
 {
-  int32_t startIndex = NS_MAX(0, mIndex - gHistoryMaxViewers);
-  int32_t endIndex = NS_MIN(mLength - 1,
+  int32_t startIndex = std::max(0, mIndex - gHistoryMaxViewers);
+  int32_t endIndex = std::min(mLength - 1,
                             mIndex + gHistoryMaxViewers);
   nsCOMPtr<nsISHTransaction> trans;
   GetTransactionAtIndex(startIndex, getter_AddRefs(trans));
 
   int32_t i;
   for (i = startIndex; trans && i <= endIndex; ++i) {
     nsCOMPtr<nsISHEntry> entry;
     trans->GetSHEntry(getter_AddRefs(entry));
@@ -1270,17 +1271,17 @@ bool IsSameTree(nsISHEntry* aEntry1, nsI
   }
 
   nsCOMPtr<nsISHContainer> container1 = do_QueryInterface(aEntry1);
   nsCOMPtr<nsISHContainer> container2 = do_QueryInterface(aEntry2);
   int32_t count1, count2;
   container1->GetChildCount(&count1);
   container2->GetChildCount(&count2);
   // We allow null entries in the end of the child list.
-  int32_t count = NS_MAX(count1, count2);
+  int32_t count = std::max(count1, count2);
   for (int32_t i = 0; i < count; ++i) {
     nsCOMPtr<nsISHEntry> child1, child2;
     container1->GetChildAt(i, getter_AddRefs(child1));
     container2->GetChildAt(i, getter_AddRefs(child2));
     if (!IsSameTree(child1, child2)) {
       return false;
     }
   }
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -45,16 +45,17 @@
 #include "nsCSSProps.h"
 #include "nsDOMFile.h"
 #include "BasicLayers.h"
 #include "nsTArrayHelpers.h"
 #include "nsIDocShell.h"
 #include "nsIContentViewer.h"
 #include "nsIMarkupDocumentViewer.h"
 #include "nsClientRect.h"
+#include <algorithm>
 
 #if defined(MOZ_X11) && defined(MOZ_WIDGET_GTK)
 #include <gdk/gdk.h>
 #include <gdk/gdkx.h>
 #endif
 
 #include "Layers.h"
 #include "nsIIOService.h"
@@ -1306,20 +1307,20 @@ nsDOMWindowUtils::CompareCanvases(nsIDOM
     v = memcmp(p1, p2, stride);
 
     if (v) {
       for (int i = 0; i < size.width; i++) {
         if (*(uint32_t*) p1 != *(uint32_t*) p2) {
 
           different++;
 
-          dc = NS_MAX((uint32_t)abs(p1[0] - p2[0]), dc);
-          dc = NS_MAX((uint32_t)abs(p1[1] - p2[1]), dc);
-          dc = NS_MAX((uint32_t)abs(p1[2] - p2[2]), dc);
-          dc = NS_MAX((uint32_t)abs(p1[3] - p2[3]), dc);
+          dc = std::max((uint32_t)abs(p1[0] - p2[0]), dc);
+          dc = std::max((uint32_t)abs(p1[1] - p2[1]), dc);
+          dc = std::max((uint32_t)abs(p1[2] - p2[2]), dc);
+          dc = std::max((uint32_t)abs(p1[3] - p2[3]), dc);
         }
 
         p1 += 4;
         p2 += 4;
       }
     }
   }
 
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -49,16 +49,17 @@
 #include "mozAutoDocUpdate.h"
 #include "nsFrameLoader.h"
 #include "nsIObserverService.h"
 #include "nsIScriptError.h"
 
 #include "mozilla/dom/Element.h"
 #include "mozilla/LookAndFeel.h"
 #include "mozilla/Preferences.h"
+#include <algorithm>
 
 #ifdef MOZ_XUL
 #include "nsIDOMXULTextboxElement.h"
 #include "nsIDOMXULMenuListElement.h"
 #endif
 
 #ifdef ACCESSIBILITY
 #include "nsAccessibilityService.h"
@@ -1318,17 +1319,17 @@ nsFocusManager::GetCommonAncestor(nsPIDO
     dsti2->GetParent(getter_AddRefs(parentDsti2));
     dsti2.swap(parentDsti2);
   } while (dsti2);
 
   uint32_t pos1 = parents1.Length();
   uint32_t pos2 = parents2.Length();
   nsIDocShellTreeItem* parent = nullptr;
   uint32_t len;
-  for (len = NS_MIN(pos1, pos2); len > 0; --len) {
+  for (len = std::min(pos1, pos2); len > 0; --len) {
     nsIDocShellTreeItem* child1 = parents1.ElementAt(--pos1);
     nsIDocShellTreeItem* child2 = parents2.ElementAt(--pos2);
     if (child1 != child2) {
       break;
     }
     parent = child1;
   }
 
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=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/. */
 
 #include "base/basictypes.h"
+#include <algorithm>
 
 /* This must occur *after* base/basictypes.h to avoid typedefs conflicts. */
 #include "mozilla/Util.h"
 
 // Local Includes
 #include "nsGlobalWindow.h"
 #include "Navigator.h"
 #include "nsScreen.h"
@@ -286,17 +287,17 @@ static bool                 gDOMWindowDu
 #define DEFAULT_MIN_TIMEOUT_VALUE 4 // 4ms
 #define DEFAULT_MIN_BACKGROUND_TIMEOUT_VALUE 1000 // 1000ms
 static int32_t gMinTimeoutValue;
 static int32_t gMinBackgroundTimeoutValue;
 inline int32_t
 nsGlobalWindow::DOMMinTimeoutValue() const {
   bool isBackground = !mOuterWindow || mOuterWindow->IsBackground();
   return
-    NS_MAX(isBackground ? gMinBackgroundTimeoutValue : gMinTimeoutValue, 0);
+    std::max(isBackground ? gMinBackgroundTimeoutValue : gMinTimeoutValue, 0);
 }
 
 // The number of nested timeouts before we start clamping. HTML5 says 1, WebKit
 // uses 5.
 #define DOM_CLAMP_TIMEOUT_NESTING_LEVEL 5
 
 // The longest interval (as PRIntervalTime) we permit, or that our
 // timer code can handle, really. See DELAY_INTERVAL_LIMIT in
@@ -4296,20 +4297,20 @@ nsGlobalWindow::GetScrollMaxXY(int32_t* 
   FlushPendingNotifications(Flush_Layout);
   nsIScrollableFrame *sf = GetScrollFrame();
   if (!sf)
     return NS_OK;
 
   nsRect scrollRange = sf->GetScrollRange();
 
   if (aScrollMaxX)
-    *aScrollMaxX = NS_MAX(0,
+    *aScrollMaxX = std::max(0,
       (int32_t)floor(nsPresContext::AppUnitsToFloatCSSPixels(scrollRange.XMost())));
   if (aScrollMaxY)
-    *aScrollMaxY = NS_MAX(0,
+    *aScrollMaxY = std::max(0,
       (int32_t)floor(nsPresContext::AppUnitsToFloatCSSPixels(scrollRange.YMost())));
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGlobalWindow::GetScrollMaxX(int32_t* aScrollMaxX)
 {
@@ -9531,17 +9532,17 @@ nsGlobalWindow::SetTimeoutOrInterval(nsI
   // If we don't have a document (we could have been unloaded since
   // the call to setTimeout was made), do nothing.
   if (!mDocument) {
     return NS_OK;
   }
 
   // Disallow negative intervals.  If aIsInterval also disallow 0,
   // because we use that as a "don't repeat" flag.
-  interval = NS_MAX(aIsInterval ? 1 : 0, interval);
+  interval = std::max(aIsInterval ? 1 : 0, interval);
 
   // Make sure we don't proceed with an interval larger than our timer
   // code can handle. (Note: we already forced |interval| to be non-negative,
   // so the uint32_t cast (to avoid compiler warnings) is ok.)
   uint32_t maxTimeoutMs = PR_IntervalToMilliseconds(DOM_MAX_TIMEOUT_VALUE);
   if (static_cast<uint32_t>(interval) > maxTimeoutMs) {
     interval = maxTimeoutMs;
   }
@@ -9552,17 +9553,17 @@ nsGlobalWindow::SetTimeoutOrInterval(nsI
   timeout->mScriptHandler = aHandler;
 
   // Now clamp the actual interval we will use for the timer based on
   uint32_t nestingLevel = sNestingLevel + 1;
   uint32_t realInterval = interval;
   if (aIsInterval || nestingLevel >= DOM_CLAMP_TIMEOUT_NESTING_LEVEL) {
     // Don't allow timeouts less than DOMMinTimeoutValue() from
     // now...
-    realInterval = NS_MAX(realInterval, uint32_t(DOMMinTimeoutValue()));
+    realInterval = std::max(realInterval, uint32_t(DOMMinTimeoutValue()));
   }
 
   // Get principal of currently executing code, save for execution of timeout.
   // If our principals subsume the subject principal then use the subject
   // principal. Otherwise, use our principal to avoid running script in
   // elevated principals.
 
   nsCOMPtr<nsIPrincipal> subjectPrincipal;
@@ -9794,17 +9795,17 @@ nsGlobalWindow::RescheduleTimeout(nsTime
       aTimeout->Release();
     }
     return false;
   }
 
   // Compute time to next timeout for interval timer.
   // Make sure nextInterval is at least DOMMinTimeoutValue().
   TimeDuration nextInterval =
-    TimeDuration::FromMilliseconds(NS_MAX(aTimeout->mInterval,
+    TimeDuration::FromMilliseconds(std::max(aTimeout->mInterval,
                                           uint32_t(DOMMinTimeoutValue())));
 
   // If we're running pending timeouts, set the next interval to be
   // relative to "now", and not to when the timeout that was pending
   // should have fired.
   TimeStamp firingTime;
   if (aRunningPendingTimeouts) {
     firingTime = now + nextInterval;
@@ -10113,17 +10114,17 @@ nsresult nsGlobalWindow::ResetTimersForN
   // with an mWhen that may be semi-bogus.  In that case, we don't need to do
   // anything with mTimeoutInsertionPoint or anything before it, so should
   // start at the timer after mTimeoutInsertionPoint, if there is one.
   // Otherwise, start at the beginning of the list.
   for (nsTimeout *timeout = mTimeoutInsertionPoint ?
          mTimeoutInsertionPoint->getNext() : mTimeouts.getFirst();
        timeout; ) {
     // It's important that this check be <= so that we guarantee that
-    // taking NS_MAX with |now| won't make a quantity equal to
+    // taking std::max with |now| won't make a quantity equal to
     // timeout->mWhen below.
     if (timeout->mWhen <= now) {
       timeout = timeout->getNext();
       continue;
     }
 
     if (timeout->mWhen - now >
         TimeDuration::FromMilliseconds(gMinBackgroundTimeoutValue)) {
@@ -10132,25 +10133,25 @@ nsresult nsGlobalWindow::ResetTimersForN
       // gMinBackgroundTimeoutValue ms and hence were not clamped.
       break;
     }
 
     /* We switched from background. Re-init the timer appropriately */
     // Compute the interval the timer should have had if it had not been set in a
     // background window
     TimeDuration interval =
-      TimeDuration::FromMilliseconds(NS_MAX(timeout->mInterval,
+      TimeDuration::FromMilliseconds(std::max(timeout->mInterval,
                                             uint32_t(DOMMinTimeoutValue())));
     uint32_t oldIntervalMillisecs = 0;
     timeout->mTimer->GetDelay(&oldIntervalMillisecs);
     TimeDuration oldInterval = TimeDuration::FromMilliseconds(oldIntervalMillisecs);
     if (oldInterval > interval) {
       // unclamp
       TimeStamp firingTime =
-        NS_MAX(timeout->mWhen - oldInterval + interval, now);
+        std::max(timeout->mWhen - oldInterval + interval, now);
 
       NS_ASSERTION(firingTime < timeout->mWhen,
                    "Our firing time should strictly decrease!");
 
       TimeDuration delay = firingTime - now;
       timeout->mWhen = firingTime;
 
       // Since we reset mWhen we need to move |timeout| to the right
@@ -10642,17 +10643,17 @@ nsGlobalWindow::ResumeTimeouts(bool aTha
 #endif
         continue;
       }
 
       // XXXbz the combination of the way |delay| and |t->mWhen| are set here
       // makes no sense.  Are we trying to impose that min timeout value or
       // not???
       uint32_t delay =
-        NS_MAX(int32_t(t->mTimeRemaining.ToMilliseconds()),
+        std::max(int32_t(t->mTimeRemaining.ToMilliseconds()),
                DOMMinTimeoutValue());
 
       // Set mWhen back to the time when the timer is supposed to
       // fire.
       t->mWhen = now + t->mTimeRemaining;
 
       t->mTimer = do_CreateInstance("@mozilla.org/timer;1");
       NS_ENSURE_TRUE(t->mTimer, NS_ERROR_OUT_OF_MEMORY);
--- a/dom/base/nsJSTimeoutHandler.cpp
+++ b/dom/base/nsJSTimeoutHandler.cpp
@@ -16,16 +16,17 @@
 #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"
+#include <algorithm>
 
 static const char kSetIntervalStr[] = "setInterval";
 static const char kSetTimeoutStr[] = "setTimeout";
 
 // Our JS nsIScriptTimeoutHandler implementation.
 class nsJSScriptTimeoutHandler MOZ_FINAL : public nsIScriptTimeoutHandler
 {
 public:
@@ -274,18 +275,18 @@ nsJSScriptTimeoutHandler::Init(nsGlobalW
 
     mFunObj = funobj;
 
     // Create our arg array.  argc is the number of arguments passed
     // to setTimeout or setInterval; the first two are our callback
     // and the delay, so only arguments after that need to go in our
     // array.
     nsCOMPtr<nsIJSArgArray> array;
-    // NS_MAX(argc - 2, 0) wouldn't work right because argc is unsigned.
-    rv = NS_CreateJSArgv(cx, NS_MAX(argc, 2u) - 2, nullptr,
+    // std::max(argc - 2, 0) wouldn't work right because argc is unsigned.
+    rv = NS_CreateJSArgv(cx, std::max(argc, 2u) - 2, nullptr,
                          getter_AddRefs(array));
     if (NS_FAILED(rv)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
 
     uint32_t dummy;
     jsval *jsargv = nullptr;
     array->GetArgs(&dummy, reinterpret_cast<void **>(&jsargv));
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -832,17 +832,17 @@ class CGDeferredFinalize(CGAbstractStati
     def __init__(self, descriptor):
         CGAbstractStaticMethod.__init__(self, descriptor, "DeferredFinalize", "bool", [Argument('uint32_t', 'slice'), Argument('void*', 'data')])
 
     def definition_body(self):
         smartPtr = DeferredFinalizeSmartPtr(self.descriptor)
         return """  MOZ_ASSERT(slice > 0, "nonsensical/useless call with slice == 0");
   nsTArray<%(smartPtr)s >* pointers = static_cast<nsTArray<%(smartPtr)s >*>(data);
   uint32_t oldLen = pointers->Length();
-  slice = NS_MIN(oldLen, slice);
+  slice = std::min(oldLen, slice);
   uint32_t newLen = oldLen - slice;
   pointers->RemoveElementsAt(newLen, slice);
   if (newLen == 0) {
     delete pointers;
     return true;
   }
   return false;""" % { 'smartPtr': smartPtr }
 
@@ -4112,17 +4112,17 @@ class CGMethodCall(CGThing):
                   'return ThrowErrorMessage(cx, MSG_INVALID_ARG, "%s", "%s");'
                   % (str(distinguishingIndex), str(argCount))))
 
             argCountCases.append(CGCase(str(argCount),
                                         CGList(caseBody, "\n")))
 
         overloadCGThings = []
         overloadCGThings.append(
-            CGGeneric("unsigned argcount = NS_MIN(argc, %du);" %
+            CGGeneric("unsigned argcount = std::min(argc, %du);" %
                       maxArgCount))
         overloadCGThings.append(
             CGSwitch("argcount",
                      argCountCases,
                      CGGeneric("return ThrowErrorMessage(cx, MSG_MISSING_ARGUMENTS, %s);\n" % methodName)))
         overloadCGThings.append(
             CGGeneric('MOZ_NOT_REACHED("We have an always-returning default case");\n'
                       'return false;'))
--- a/dom/devicestorage/nsDeviceStorage.cpp
+++ b/dom/devicestorage/nsDeviceStorage.cpp
@@ -41,16 +41,17 @@
 #include "mozilla/Services.h"
 #include "nsIObserverService.h"
 #include "GeneratedEvents.h"
 #include "mozilla/dom/PermissionMessageUtils.h"
 #include "nsIMIMEService.h"
 #include "nsCExternalHandlerService.h"
 #include "nsIPermissionManager.h"
 #include "nsIStringBundle.h"
+#include <algorithm>
 
 // Microsoft's API Name hackery sucks
 #undef CreateEvent
 
 #ifdef MOZ_WIDGET_GONK
 #include "nsIVolume.h"
 #include "nsIVolumeService.h"
 #endif
@@ -436,17 +437,17 @@ DeviceStorageFile::Write(nsIInputStream*
   rv = NS_NewBufferedOutputStream(getter_AddRefs(bufferedOutputStream),
                                   outputStream,
                                   4096*4);
   NS_ENSURE_SUCCESS(rv, rv);
 
   while (bufSize) {
     uint32_t wrote;
     rv = bufferedOutputStream->WriteFrom(aInputStream,
-                                         static_cast<uint32_t>(NS_MIN<uint64_t>(bufSize, UINT32_MAX)),
+                                         static_cast<uint32_t>(std::min<uint64_t>(bufSize, UINT32_MAX)),
                                          &wrote);
     if (NS_FAILED(rv)) {
       break;
     }
     bufSize -= wrote;
   }
 
   iocomplete = new IOEventComplete(this, "modified");
--- a/dom/indexedDB/FileManager.cpp
+++ b/dom/indexedDB/FileManager.cpp
@@ -14,16 +14,17 @@
 #include "mozStorageCID.h"
 #include "mozStorageHelper.h"
 
 #include "FileInfo.h"
 #include "IndexedDatabaseManager.h"
 #include "OpenDatabaseHelper.h"
 
 #include "IndexedDatabaseInlines.h"
+#include <algorithm>
 
 #define JOURNAL_DIRECTORY_NAME "journals"
 
 USING_INDEXEDDB_NAMESPACE
 
 namespace {
 
 PLDHashOperator
@@ -124,17 +125,17 @@ FileManager::Init(nsIFile* aDirectory,
 
     NS_ASSERTION(refcount, "This shouldn't happen!");
 
     nsRefPtr<FileInfo> fileInfo = FileInfo::Create(this, id);
     fileInfo->mDBRefCnt = refcount;
 
     mFileInfos.Put(id, fileInfo);
 
-    mLastFileId = NS_MAX(id, mLastFileId);
+    mLastFileId = std::max(id, mLastFileId);
   }
 
   return NS_OK;
 }
 
 nsresult
 FileManager::Invalidate()
 {
--- a/dom/indexedDB/IDBFactory.cpp
+++ b/dom/indexedDB/IDBFactory.cpp
@@ -37,16 +37,17 @@
 #include "DatabaseInfo.h"
 #include "IDBDatabase.h"
 #include "IDBEvents.h"
 #include "IDBKeyRange.h"
 #include "IndexedDatabaseManager.h"
 #include "Key.h"
 
 #include "ipc/IndexedDBChild.h"
+#include <algorithm>
 
 USING_INDEXEDDB_NAMESPACE
 
 using mozilla::dom::ContentChild;
 using mozilla::dom::ContentParent;
 using mozilla::dom::TabChild;
 
 namespace {
@@ -440,17 +441,17 @@ IDBFactory::LoadDatabaseInformation(mozI
   if (!hasResult) {
     NS_ERROR("Database has no version!");
     return NS_ERROR_UNEXPECTED;
   }
 
   int64_t version = 0;
   rv = stmt->GetInt64(0, &version);
 
-  *aVersion = NS_MAX<int64_t>(version, 0);
+  *aVersion = std::max<int64_t>(version, 0);
 
   return rv;
 }
 
 // static
 nsresult
 IDBFactory::SetDatabaseMetadata(DatabaseInfo* aDatabaseInfo,
                                 uint64_t aVersion,
--- a/dom/indexedDB/IndexedDatabaseManager.cpp
+++ b/dom/indexedDB/IndexedDatabaseManager.cpp
@@ -42,16 +42,17 @@
 #include "IDBDatabase.h"
 #include "IDBEvents.h"
 #include "IDBFactory.h"
 #include "IDBKeyRange.h"
 #include "OpenDatabaseHelper.h"
 #include "TransactionThreadPool.h"
 
 #include "IndexedDatabaseInlines.h"
+#include <algorithm>
 
 // The amount of time, in milliseconds, that our IO thread will stay alive
 // after the last event it processes.
 #define DEFAULT_THREAD_TIMEOUT_MS 30000
 
 // The amount of time, in milliseconds, that we will wait for active database
 // transactions on shutdown before aborting them.
 #define DEFAULT_SHUTDOWN_TIMER_MS 30000
@@ -896,17 +897,17 @@ IndexedDatabaseManager::OnDatabaseClosed
     }
   }
 }
 
 // static
 uint32_t
 IndexedDatabaseManager::GetIndexedDBQuotaMB()
 {
-  return uint32_t(NS_MAX(gIndexedDBQuotaMB, 0));
+  return uint32_t(std::max(gIndexedDBQuotaMB, 0));
 }
 
 nsresult
 IndexedDatabaseManager::EnsureOriginIsInitialized(const nsACString& aOrigin,
                                                   FactoryPrivilege aPrivilege,
                                                   nsIFile** aDirectory)
 {
 #ifdef DEBUG
--- a/dom/indexedDB/Key.cpp
+++ b/dom/indexedDB/Key.cpp
@@ -7,16 +7,17 @@
 #include "mozilla/FloatingPoint.h"
 
 #include "Key.h"
 #include "nsIStreamBufferAccess.h"
 #include "jsfriendapi.h"
 #include "nsAlgorithm.h"
 #include "nsJSUtils.h"
 #include "xpcpublic.h"
+#include <algorithm>
 
 USING_INDEXEDDB_NAMESPACE
 
 /*
  Here's how we encode keys:
 
  Basic strategy is the following
 
@@ -404,17 +405,17 @@ double
 Key::DecodeNumber(const unsigned char*& aPos, const unsigned char* aEnd)
 {
   NS_ASSERTION(*aPos % eMaxType == eFloat ||
                *aPos % eMaxType == eDate, "Don't call me!");
 
   ++aPos;
 
   uint64_t number = 0;
-  memcpy(&number, aPos, NS_MIN<size_t>(sizeof(number), aEnd - aPos));
+  memcpy(&number, aPos, std::min<size_t>(sizeof(number), aEnd - aPos));
   number = NS_SWAP64(number);
 
   aPos += sizeof(number);
 
   Float64Union pun;
   pun.u = number & PR_UINT64(0x8000000000000000) ?
           (number & ~PR_UINT64(0x8000000000000000)) :
           -number;
--- a/dom/indexedDB/OpenDatabaseHelper.cpp
+++ b/dom/indexedDB/OpenDatabaseHelper.cpp
@@ -14,16 +14,17 @@
 #include "nsNetUtil.h"
 #include "nsThreadUtils.h"
 #include "snappy/snappy.h"
 
 #include "nsIBFCacheEntry.h"
 #include "IDBEvents.h"
 #include "IDBFactory.h"
 #include "IndexedDatabaseManager.h"
+#include <algorithm>
 
 using namespace mozilla;
 USING_INDEXEDDB_NAMESPACE
 USING_QUOTA_NAMESPACE
 
 namespace {
 
 // If JS_STRUCTURED_CLONE_VERSION changes then we need to update our major
@@ -1674,19 +1675,19 @@ OpenDatabaseHelper::DoDatabaseWork()
     mState = eDeletePending;
     return NS_OK;
   }
 
   for (uint32_t i = 0; i < mObjectStores.Length(); i++) {
     nsRefPtr<ObjectStoreInfo>& objectStoreInfo = mObjectStores[i];
     for (uint32_t j = 0; j < objectStoreInfo->indexes.Length(); j++) {
       IndexInfo& indexInfo = objectStoreInfo->indexes[j];
-      mLastIndexId = NS_MAX(indexInfo.id, mLastIndexId);
+      mLastIndexId = std::max(indexInfo.id, mLastIndexId);
     }
-    mLastObjectStoreId = NS_MAX(objectStoreInfo->id, mLastObjectStoreId);
+    mLastObjectStoreId = std::max(objectStoreInfo->id, mLastObjectStoreId);
   }
 
   // See if we need to do a VERSION_CHANGE transaction
 
   // Optional version semantics.
   if (!mRequestedVersion) {
     // If the requested version was not specified and the database was created,
     // treat it as if version 1 were requested.
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -25,16 +25,17 @@
 #include "mozilla/StaticPtr.h"
 #include "mozilla/unused.h"
 #include "mozIApplication.h"
 #include "nsComponentManagerUtils.h"
 #include "nsComponentManagerUtils.h"
 #include "nsContentUtils.h"
 #include "nsEmbedCID.h"
 #include "nsEventListenerManager.h"
+#include <algorithm>
 #ifdef MOZ_CRASHREPORTER
 #include "nsExceptionHandler.h"
 #endif
 #include "mozilla/dom/Element.h"
 #include "nsIAppsService.h"
 #include "nsIBaseWindow.h"
 #include "nsIComponentManager.h"
 #include "nsIDocumentInlines.h"
@@ -438,31 +439,31 @@ TabChild::HandlePossibleViewportChange()
   int32_t bodyWidth = 0, bodyHeight = 0;
   if (bodyDOMElement) {
     bodyWidth = bodyDOMElement->ScrollWidth();
     bodyHeight = bodyDOMElement->ScrollHeight();
   }
 
   float pageWidth, pageHeight;
   if (htmlDOMElement || bodyDOMElement) {
-    pageWidth = NS_MAX(htmlWidth, bodyWidth);
-    pageHeight = NS_MAX(htmlHeight, bodyHeight);
+    pageWidth = std::max(htmlWidth, bodyWidth);
+    pageHeight = std::max(htmlHeight, bodyHeight);
   } else {
     // For non-HTML content (e.g. SVG), just assume page size == viewport size.
     pageWidth = viewportW;
     pageHeight = viewportH;
   }
   NS_ENSURE_TRUE_VOID(pageWidth); // (return early rather than divide by 0)
 
   minScale = mInnerSize.width / pageWidth;
   minScale = clamped((double)minScale, viewportInfo.GetMinZoom(),
                      viewportInfo.GetMaxZoom());
   NS_ENSURE_TRUE_VOID(minScale); // (return early rather than divide by 0)
 
-  viewportH = NS_MAX(viewportH, screenH / minScale);
+  viewportH = std::max(viewportH, screenH / minScale);
   SetCSSViewport(viewportW, viewportH);
 
   // This change to the zoom accounts for all types of changes I can conceive:
   // 1. screen size changes, CSS viewport does not (pages with no meta viewport
   //    or a fixed size viewport)
   // 2. screen size changes, CSS viewport also does (pages with a device-width
   //    viewport)
   // 3. screen size remains constant, but CSS viewport changes (meta viewport
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -47,16 +47,17 @@
 #include "nsNetUtil.h"
 #include "nsPIDOMWindow.h"
 #include "nsPrintfCString.h"
 #include "nsSerializationHelper.h"
 #include "nsServiceManagerUtils.h"
 #include "nsThreadUtils.h"
 #include "StructuredCloneUtils.h"
 #include "TabChild.h"
+#include <algorithm>
 
 using namespace mozilla::dom;
 using namespace mozilla::ipc;
 using namespace mozilla::layers;
 using namespace mozilla::layout;
 using namespace mozilla::services;
 using namespace mozilla::widget;
 using namespace mozilla::dom::indexedDB;
@@ -655,17 +656,17 @@ TabParent::HandleQueryContentEvent(nsQue
   aEvent.mSucceeded = false;
   aEvent.mWasAsync = false;
   aEvent.mReply.mFocusedWidget = nsCOMPtr<nsIWidget>(GetWidget()).get();
 
   switch (aEvent.message)
   {
   case NS_QUERY_SELECTED_TEXT:
     {
-      aEvent.mReply.mOffset = NS_MIN(mIMESelectionAnchor, mIMESelectionFocus);
+      aEvent.mReply.mOffset = std::min(mIMESelectionAnchor, mIMESelectionFocus);
       if (mIMESelectionAnchor == mIMESelectionFocus) {
         aEvent.mReply.mString.Truncate(0);
       } else {
         if (mIMESelectionAnchor > mIMECacheText.Length() ||
             mIMESelectionFocus > mIMECacheText.Length()) {
           break;
         }
         uint32_t selLen = mIMESelectionAnchor > mIMESelectionFocus ?
@@ -704,17 +705,17 @@ TabParent::HandleQueryContentEvent(nsQue
 
 bool
 TabParent::SendCompositionEvent(nsCompositionEvent& event)
 {
   if (mIsDestroyed) {
     return false;
   }
   mIMEComposing = event.message != NS_COMPOSITION_END;
-  mIMECompositionStart = NS_MIN(mIMESelectionAnchor, mIMESelectionFocus);
+  mIMECompositionStart = std::min(mIMESelectionAnchor, mIMESelectionFocus);
   if (mIMECompositionEnding)
     return true;
   event.seqno = ++mIMESeqno;
   return PBrowserParent::SendCompositionEvent(event);
 }
 
 /**
  * During ResetInputState or CancelComposition, widget usually sends a
@@ -732,17 +733,17 @@ TabParent::SendTextEvent(nsTextEvent& ev
   if (mIMECompositionEnding) {
     mIMECompositionText = event.theText;
     return true;
   }
 
   // We must be able to simulate the selection because
   // we might not receive selection updates in time
   if (!mIMEComposing) {
-    mIMECompositionStart = NS_MIN(mIMESelectionAnchor, mIMESelectionFocus);
+    mIMECompositionStart = std::min(mIMESelectionAnchor, mIMESelectionFocus);
   }
   mIMESelectionAnchor = mIMESelectionFocus =
       mIMECompositionStart + event.theText.Length();
 
   event.seqno = ++mIMESeqno;
   return PBrowserParent::SendTextEvent(event);
 }
 
--- a/dom/plugins/base/nsNPAPIPluginStreamListener.cpp
+++ b/dom/plugins/base/nsNPAPIPluginStreamListener.cpp
@@ -12,16 +12,17 @@
 #include "nsNetUtil.h"
 #include "nsPluginHost.h"
 #include "nsNPAPIPlugin.h"
 #include "nsPluginSafety.h"
 #include "nsPluginLogging.h"
 #include "nsPluginStreamListenerPeer.h"
 
 #include "mozilla/StandardInteger.h"
+#include <algorithm>
 
 nsNPAPIStreamWrapper::nsNPAPIStreamWrapper(nsIOutputStream *outputStream,
                                            nsNPAPIPluginStreamListener *streamListener)
 {
   mOutputStream = outputStream;
   mStreamListener = streamListener;
 
   memset(&mNPStream, 0, sizeof(mNPStream));
@@ -456,22 +457,22 @@ nsNPAPIPluginStreamListener::OnDataAvail
     // mStreamBuffer here in first ODA when length of data available
     // in input stream is known.  mStreamBuffer will be freed in DTOR.
     // we also have to remember the size of that buff to make safe
     // consecutive Read() calls form input stream into our buff.
     
     uint32_t contentLength;
     streamPeer->GetLength(&contentLength);
     
-    mStreamBufferSize = NS_MAX(length, contentLength);
+    mStreamBufferSize = std::max(length, contentLength);
     
     // Limit the size of the initial buffer to MAX_PLUGIN_NECKO_BUFFER
     // (16k). This buffer will grow if needed, as in the case where
     // we're getting data faster than the plugin can process it.
-    mStreamBufferSize = NS_MIN(mStreamBufferSize,
+    mStreamBufferSize = std::min(mStreamBufferSize,
                                uint32_t(MAX_PLUGIN_NECKO_BUFFER));
     
     mStreamBuffer = (char*) PR_Malloc(mStreamBufferSize);
     if (!mStreamBuffer)
       return NS_ERROR_OUT_OF_MEMORY;
   }
   
   // prepare NPP_ calls params
@@ -517,17 +518,17 @@ nsNPAPIPluginStreamListener::OnDataAvail
         char *buf = (char*)PR_Realloc(mStreamBuffer, mStreamBufferSize);
         if (!buf)
           return NS_ERROR_OUT_OF_MEMORY;
         
         mStreamBuffer = buf;
       }
       
       uint32_t bytesToRead =
-      NS_MIN(length, mStreamBufferSize - mStreamBufferByteCount);
+      std::min(length, mStreamBufferSize - mStreamBufferByteCount);
       
       uint32_t amountRead = 0;
       rv = input->Read(mStreamBuffer + mStreamBufferByteCount, bytesToRead,
                        &amountRead);
       NS_ENSURE_SUCCESS(rv, rv);
       
       if (amountRead == 0) {
         NS_NOTREACHED("input->Read() returns no data, it's almost impossible "
@@ -596,17 +597,17 @@ nsNPAPIPluginStreamListener::OnDataAvail
           
           // Break out of the inner loop, but keep going through the
           // outer loop in case there's more data to read from the
           // input stream.
           
           break;
         }
         
-        numtowrite = NS_MIN(numtowrite, mStreamBufferByteCount);
+        numtowrite = std::min(numtowrite, mStreamBufferByteCount);
       } else {
         // if WriteReady is not supported by the plugin, just write
         // the whole buffer
         numtowrite = mStreamBufferByteCount;
       }
       
       NPPAutoPusher nppPusher(npp);
       
@@ -624,17 +625,17 @@ nsNPAPIPluginStreamListener::OnDataAvail
         // NPP_Write(), kill the stream.
         return NS_BINDING_ABORTED;
       }
       
       if (writeCount > 0) {
         NS_ASSERTION(writeCount <= mStreamBufferByteCount,
                      "Plugin read past the end of the available data!");
         
-        writeCount = NS_MIN(writeCount, mStreamBufferByteCount);
+        writeCount = std::min(writeCount, mStreamBufferByteCount);
         mStreamBufferByteCount -= writeCount;
         
         streamPosition += writeCount;
         
         zeroBytesWriteCount = 0;
         
         if (mStreamBufferByteCount > 0) {
           // This alignment code is most likely bogus, but we'll leave
--- a/dom/plugins/test/testplugin/nptest_macosx.mm
+++ b/dom/plugins/test/testplugin/nptest_macosx.mm
@@ -29,16 +29,17 @@
  * Contributor(s):
  *   Josh Aas <josh@mozilla.com>
  * 
  * ***** END LICENSE BLOCK ***** */
 
 #include "nptest_platform.h"
 #include "nsAlgorithm.h"
 #include <CoreServices/CoreServices.h>
+#include <algorithm>
 
 using namespace std;
 
 bool
 pluginSupportsWindowMode()
 {
   return false;
 }
@@ -170,18 +171,18 @@ pluginDraw(InstanceData* instanceData, N
     CGContextSetLineWidth(cgContext, 6.0);
     CGContextStrokePath(cgContext);
 
     // draw the UA string using Core Text
     CGContextSetTextMatrix(cgContext, CGAffineTransformIdentity);
 
     // Initialize a rectangular path.
     CGMutablePathRef path = CGPathCreateMutable();
-    CGRect bounds = CGRectMake(10.0, 10.0, NS_MAX(0.0, windowWidth - 20.0),
-                               NS_MAX(0.0, windowHeight - 20.0));
+    CGRect bounds = CGRectMake(10.0, 10.0, std::max(0.0, windowWidth - 20.0),
+                               std::max(0.0, windowHeight - 20.0));
     CGPathAddRect(path, NULL, bounds);
 
     // Initialize an attributed string.
     CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
     CFAttributedStringReplaceString(attrString, CFRangeMake(0, 0), uaCFString);
 
     // Create a color and add it as an attribute to the string.
     CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
--- a/dom/src/geolocation/nsGeolocation.cpp
+++ b/dom/src/geolocation/nsGeolocation.cpp
@@ -40,16 +40,17 @@
 #include "nsThreadUtils.h"
 #include "mozilla/Services.h"
 #include "mozilla/unused.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/ClearOnShutdown.h"
 
 #include <math.h>
+#include <algorithm>
 
 #ifdef MOZ_MAEMO_LIBLOCATION
 #include "MaemoLocationProvider.h"
 #endif
 
 #ifdef MOZ_ENABLE_QTMOBILITY
 #include "QTMLocationProvider.h"
 #endif
@@ -936,17 +937,17 @@ nsGeolocationService::IsBetterPosition(n
   // http://en.wikipedia.org/wiki/Great-circle_distance
 
   double delta = acos( (sin(newLat) * sin(oldLat)) +
                        (cos(newLat) * cos(oldLat) * cos(oldLon - newLon)) ) * radius; 
 
   // The threshold is when the distance between the two
   // positions exceeds the worse (larger value) of the two
   // accuracies.
-  double max_accuracy = NS_MAX(oldAccuracy, newAccuracy);
+  double max_accuracy = std::max(oldAccuracy, newAccuracy);
   if (delta > max_accuracy)
     return true;
 
   // check to see if the aSomewhere position is more accurate
   if (oldAccuracy >= newAccuracy)
     return true;
 
   return false;
--- a/dom/src/json/nsJSON.cpp
+++ b/dom/src/json/nsJSON.cpp
@@ -16,16 +16,17 @@
 #include "nsICharsetConverterManager.h"
 #include "nsXPCOMStrings.h"
 #include "nsNetUtil.h"
 #include "nsContentUtils.h"
 #include "nsIScriptError.h"
 #include "nsCRTGlue.h"
 #include "nsAutoPtr.h"
 #include "nsIScriptSecurityManager.h"
+#include <algorithm>
 
 static const char kXPConnectServiceCID[] = "@mozilla.org/js/xpc/XPConnect;1";
 
 #define JSON_STREAM_BUFSIZE 4096
 
 NS_INTERFACE_MAP_BEGIN(nsJSON)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIJSON)
   NS_INTERFACE_MAP_ENTRY(nsIJSON)
@@ -601,17 +602,17 @@ nsJSONListener::OnDataAvailable(nsIReque
       return NS_OK;
   }
   
   char buffer[JSON_STREAM_BUFSIZE];
   unsigned long bytesRemaining = aLength - mSniffBuffer.Length();
   while (bytesRemaining) {
     unsigned int bytesRead;
     rv = aStream->Read(buffer,
-                       NS_MIN((unsigned long)sizeof(buffer), bytesRemaining),
+                       std::min((unsigned long)sizeof(buffer), bytesRemaining),
                        &bytesRead);
     NS_ENSURE_SUCCESS(rv, rv);
     rv = ProcessBytes(buffer, bytesRead);
     NS_ENSURE_SUCCESS(rv, rv);
     bytesRemaining -= bytesRead;
   }
 
   return rv;
--- a/dom/workers/RuntimeService.cpp
+++ b/dom/workers/RuntimeService.cpp
@@ -35,16 +35,17 @@
 #include "nsXPCOMPrivate.h"
 #include "xpcpublic.h"
 
 #include "Events.h"
 #include "Worker.h"
 #include "WorkerPrivate.h"
 
 #include "OSFileConstants.h"
+#include <algorithm>
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 USING_WORKERS_NAMESPACE
 
 using mozilla::MutexAutoLock;
 using mozilla::MutexAutoUnlock;
@@ -1085,17 +1086,17 @@ RuntimeService::Init()
   if (NS_FAILED(Preferences::AddIntVarCache(&sCloseHandlerTimeoutSeconds,
                                             PREF_MAX_SCRIPT_RUN_TIME,
                                             MAX_SCRIPT_RUN_TIME_SEC))) {
       NS_WARNING("Failed to register timeout cache?!");
   }
 
   int32_t maxPerDomain = Preferences::GetInt(PREF_WORKERS_MAX_PER_DOMAIN,
                                              MAX_WORKERS_PER_DOMAIN);
-  gMaxWorkersPerDomain = NS_MAX(0, maxPerDomain);
+  gMaxWorkersPerDomain = std::max(0, maxPerDomain);
 
   mDetectorName = Preferences::GetLocalizedCString("intl.charset.detector");
 
   nsCOMPtr<nsIPlatformCharset> platformCharset =
     do_GetService(NS_PLATFORMCHARSET_CONTRACTID, &rv);
   if (NS_SUCCEEDED(rv)) {
     rv = platformCharset->GetCharset(kPlatformCharsetSel_PlainTextInFile,
                                      mSystemCharset);
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -39,16 +39,17 @@
 #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"
+#include <algorithm>
 
 #ifdef ANDROID
 #include <android/log.h>
 #endif
 
 #include "Events.h"
 #include "Exceptions.h"
 #include "File.h"
@@ -3882,17 +3883,17 @@ WorkerPrivate::RunExpiredTimeouts(JSCont
   bool retval = true;
 
   AutoPtrComparator<TimeoutInfo> comparator = GetAutoPtrComparator(mTimeouts);
   js::RootedObject global(aCx, JS_GetGlobalObject(aCx));
   JSPrincipals* principal = GetWorkerPrincipal();
 
   // We want to make sure to run *something*, even if the timer fired a little
   // early. Fudge the value of now to at least include the first timeout.
-  const TimeStamp now = NS_MAX(TimeStamp::Now(), mTimeouts[0]->mTargetTime);
+  const TimeStamp now = std::max(TimeStamp::Now(), mTimeouts[0]->mTargetTime);
 
   nsAutoTArray<TimeoutInfo*, 10> expiredTimeouts;
   for (uint32_t index = 0; index < mTimeouts.Length(); index++) {
     nsAutoPtr<TimeoutInfo>& info = mTimeouts[index];
     if (info->mTargetTime > now) {
       break;
     }
     expiredTimeouts.AppendElement(info);
@@ -4000,17 +4001,17 @@ bool
 WorkerPrivate::RescheduleTimeoutTimer(JSContext* aCx)
 {
   AssertIsOnWorkerThread();
   NS_ASSERTION(!mTimeouts.IsEmpty(), "Should have some timeouts!");
   NS_ASSERTION(mTimer, "Should have a timer!");
 
   double delta =
     (mTimeouts[0]->mTargetTime - TimeStamp::Now()).ToMilliseconds();
-  uint32_t delay = delta > 0 ? NS_MIN(delta, double(UINT32_MAX)) : 0;
+  uint32_t delay = delta > 0 ? std::min(delta, double(UINT32_MAX)) : 0;
 
   nsresult rv = mTimer->InitWithFuncCallback(DummyCallback, nullptr, delay,
                                              nsITimer::TYPE_ONE_SHOT);
   if (NS_FAILED(rv)) {
     JS_ReportError(aCx, "Failed to start timer!");
     return false;
   }
 
--- a/editor/libeditor/base/CreateElementTxn.cpp
+++ b/editor/libeditor/base/CreateElementTxn.cpp
@@ -16,16 +16,17 @@
 #include "nsINode.h"
 #include "nsISelection.h"
 #include "nsISupportsUtils.h"
 #include "nsMemory.h"
 #include "nsReadableUtils.h"
 #include "nsStringFwd.h"
 #include "nsString.h"
 #include "nsAString.h"
+#include <algorithm>
 
 #ifdef DEBUG
 static bool gNoisy = false;
 #endif
 
 using namespace mozilla;
 
 CreateElementTxn::CreateElementTxn()
@@ -103,17 +104,17 @@ NS_IMETHODIMP CreateElementTxn::DoTransa
   // insert the new node
   if (CreateElementTxn::eAppend == int32_t(mOffsetInParent)) {
     ErrorResult rv;
     mParent->AppendChild(*mNewNode, rv);
     return rv.ErrorCode();
   }
 
 
-  mOffsetInParent = NS_MIN(mOffsetInParent, mParent->GetChildCount());
+  mOffsetInParent = std::min(mOffsetInParent, mParent->GetChildCount());
 
   // note, it's ok for mRefNode to be null.  that means append
   mRefNode = mParent->GetChildAt(mOffsetInParent);
 
   ErrorResult rv;
   mParent->InsertBefore(*mNewNode, mRefNode, rv);
   NS_ENSURE_SUCCESS(rv.ErrorCode(), rv.ErrorCode());
 
--- a/editor/libeditor/html/nsHTMLAbsPosition.cpp
+++ b/editor/libeditor/html/nsHTMLAbsPosition.cpp
@@ -44,16 +44,17 @@
 #include "nsISupportsUtils.h"
 #include "nsLiteralString.h"
 #include "nsReadableUtils.h"
 #include "nsString.h"
 #include "nsStringFwd.h"
 #include "nsTextEditRules.h"
 #include "nsTextEditUtils.h"
 #include "nscore.h"
+#include <algorithm>
 
 using namespace mozilla;
 
 #define  BLACK_BG_RGB_TRIGGER 0xd0
 
 NS_IMETHODIMP
 nsHTMLEditor::AbsolutePositionSelection(bool aEnabled)
 {
@@ -139,17 +140,17 @@ nsHTMLEditor::RelativeChangeElementZInde
   NS_ENSURE_ARG_POINTER(aReturn);
   if (!aChange) // early way out, no change
     return NS_OK;
 
   int32_t zIndex;
   nsresult res = GetElementZIndex(aElement, &zIndex);
   NS_ENSURE_SUCCESS(res, res);
 
-  zIndex = NS_MAX(zIndex + aChange, 0);
+  zIndex = std::max(zIndex + aChange, 0);
   SetElementZIndex(aElement, zIndex);
   *aReturn = zIndex;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLEditor::SetElementZIndex(nsIDOMElement * aElement,
--- a/editor/libeditor/html/nsHTMLEditRules.cpp
+++ b/editor/libeditor/html/nsHTMLEditRules.cpp
@@ -52,16 +52,17 @@
 #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";
 //const static char* kMOZEditorBogusNodeValue="TRUE";
@@ -1926,17 +1927,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, NS_MIN(so, eo), std::abs(eo - so));
+      res = mHTMLEditor->DeleteText(nodeAsText, std::min(so, eo), std::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))
--- a/editor/libeditor/html/nsHTMLObjectResizer.cpp
+++ b/editor/libeditor/html/nsHTMLObjectResizer.cpp
@@ -39,16 +39,17 @@
 #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;
 
 // ==================================================================
@@ -793,44 +794,44 @@ nsHTMLEditor::GetNewResizingIncrement(in
 }
 
 int32_t
 nsHTMLEditor::GetNewResizingX(int32_t aX, int32_t aY)
 {
   int32_t resized = mResizedObjectX +
                     GetNewResizingIncrement(aX, aY, kX) * mXIncrementFactor;
   int32_t max =   mResizedObjectX + mResizedObjectWidth;
-  return NS_MIN(resized, max);
+  return std::min(resized, max);
 }
 
 int32_t
 nsHTMLEditor::GetNewResizingY(int32_t aX, int32_t aY)
 {
   int32_t resized = mResizedObjectY +
                     GetNewResizingIncrement(aX, aY, kY) * mYIncrementFactor;
   int32_t max =   mResizedObjectY + mResizedObjectHeight;
-  return NS_MIN(resized, max);
+  return std::min(resized, max);
 }
 
 int32_t
 nsHTMLEditor::GetNewResizingWidth(int32_t aX, int32_t aY)
 {
   int32_t resized = mResizedObjectWidth +
                      GetNewResizingIncrement(aX, aY, kWidth) *
                          mWidthIncrementFactor;
-  return NS_MAX(resized, 1);
+  return std::max(resized, 1);
 }
 
 int32_t
 nsHTMLEditor::GetNewResizingHeight(int32_t aX, int32_t aY)
 {
   int32_t resized = mResizedObjectHeight +
                      GetNewResizingIncrement(aX, aY, kHeight) *
                          mHeightIncrementFactor;
-  return NS_MAX(resized, 1);
+  return std::max(resized, 1);
 }
 
 
 NS_IMETHODIMP
 nsHTMLEditor::MouseMove(nsIDOMEvent* aMouseEvent)
 {
   NS_NAMED_LITERAL_STRING(leftStr, "left");
   NS_NAMED_LITERAL_STRING(topStr, "top");
--- a/editor/libeditor/html/nsTableEditor.cpp
+++ b/editor/libeditor/html/nsTableEditor.cpp
@@ -34,16 +34,17 @@
 #include "nsITableEditor.h"
 #include "nsLiteralString.h"
 #include "nsQueryFrame.h"
 #include "nsString.h"
 #include "nsTArray.h"
 #include "nsTableCellFrame.h"
 #include "nsTableOuterFrame.h"
 #include "nscore.h"
+#include <algorithm>
 
 using namespace mozilla;
 
 /***************************************************************************
  * stack based helper class for restoring selection after table edit
  */
 class NS_STACK_CLASS nsSetSelectionAfterTableEdit
 {
@@ -1029,17 +1030,17 @@ nsHTMLEditor::DeleteTableColumn(int32_t 
   res = GetTableSize(table, &rowCount, &colCount);
   NS_ENSURE_SUCCESS(res, res);
 
   // Shortcut the case of deleting all columns in table
   if(startColIndex == 0 && aNumber >= colCount)
     return DeleteTable2(table, selection);
 
   // Check for counts too high
-  aNumber = NS_MIN(aNumber,(colCount-startColIndex));
+  aNumber = std::min(aNumber,(colCount-startColIndex));
 
   nsAutoEditBatch beginBatching(this);
   // Prevent rules testing until we're done
   nsAutoRules beginRulesSniffing(this, EditAction::deleteNode, nsIEditor::eNext);
 
   // Test if deletion is controlled by selected cells
   nsCOMPtr<nsIDOMElement> firstCell;
   nsCOMPtr<nsIDOMRange> range;
@@ -1263,17 +1264,17 @@ nsHTMLEditor::DeleteTableRow(int32_t aNu
       // Delete entire row
       res = DeleteRow(table, startRowIndex);          
       NS_ENSURE_SUCCESS(res, res);
     }
   }
   else
   {
     // Check for counts too high
-    aNumber = NS_MIN(aNumber,(rowCount-startRowIndex));
+    aNumber = std::min(aNumber,(rowCount-startRowIndex));
 
     for (int32_t i = 0; i < aNumber; i++)
     {
       res = DeleteRow(table, startRowIndex);
       // If failed in current row, try the next
       if (NS_FAILED(res))
         startRowIndex++;
     
@@ -1329,17 +1330,17 @@ nsHTMLEditor::DeleteRow(nsIDOMElement *a
         //  but we don't need to do this if rowspan=0,
         //  since it will automatically adjust
         if (rowSpan > 0)
         {
           // Build list of cells to change rowspan
           // We can't do it now since it upsets cell map,
           //  so we will do it after deleting the row
           spanCellList.AppendElement(cell);
-          newSpanList.AppendElement(NS_MAX((aRowIndex - startRowIndex), actualRowSpan-1));
+          newSpanList.AppendElement(std::max((aRowIndex - startRowIndex), actualRowSpan-1));
         }
       }
       else 
       {
         if (rowSpan > 1)
         {
           //Cell spans below row to delete,
           //  so we must insert new cells to keep rows below even
@@ -1452,20 +1453,20 @@ nsHTMLEditor::SelectBlockOfCells(nsIDOME
   if(NS_FAILED(res)) return res;
 
   // Suppress nsISelectionListener notification
   //  until all selection changes are finished
   nsSelectionBatcherForTable selectionBatcher(selection);
 
   // Examine all cell nodes in current selection and 
   //  remove those outside the new block cell region
-  int32_t minColumn = NS_MIN(startColIndex, endColIndex);
-  int32_t minRow    = NS_MIN(startRowIndex, endRowIndex);
-  int32_t maxColumn   = NS_MAX(startColIndex, endColIndex);
-  int32_t maxRow      = NS_MAX(startRowIndex, endRowIndex);
+  int32_t minColumn = std::min(startColIndex, endColIndex);
+  int32_t minRow    = std::min(startRowIndex, endRowIndex);
+  int32_t maxColumn   = std::max(startColIndex, endColIndex);
+  int32_t maxRow      = std::max(startRowIndex, endRowIndex);
 
   nsCOMPtr<nsIDOMElement> cell;
   int32_t currentRowIndex, currentColIndex;
   nsCOMPtr<nsIDOMRange> range;
   res = GetFirstSelectedCell(getter_AddRefs(range), getter_AddRefs(cell));
   NS_ENSURE_SUCCESS(res, res);
   if (res == NS_EDITOR_ELEMENT_NOT_FOUND) return NS_OK;
 
@@ -1484,17 +1485,17 @@ nsHTMLEditor::SelectBlockOfCells(nsIDOME
     res = GetNextSelectedCell(getter_AddRefs(range), getter_AddRefs(cell));
     NS_ENSURE_SUCCESS(res, res);
   }
 
   int32_t rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
   for (int32_t row = minRow; row <= maxRow; row++)
   {
-    for(int32_t col = minColumn; col <= maxColumn; col += NS_MAX(actualColSpan, 1))
+    for(int32_t col = minColumn; col <= maxColumn; col += std::max(actualColSpan, 1))
     {
       res = GetCellDataAt(table, row, col, getter_AddRefs(cell),
                           &currentRowIndex, &currentColIndex,
                           &rowSpan, &colSpan, 
                           &actualRowSpan, &actualColSpan, &isSelected);
       if (NS_FAILED(res)) break;
       // Skip cells that already selected or are spanned from previous locations
       if (!isSelected && cell && row == currentRowIndex && col == currentColIndex)
@@ -1543,17 +1544,17 @@ nsHTMLEditor::SelectAllTableCells()
   res = ClearSelection();
 
   // Select all cells in the same column as current cell
   bool cellSelected = false;
   int32_t rowSpan, colSpan, actualRowSpan, actualColSpan, currentRowIndex, currentColIndex;
   bool    isSelected;
   for(int32_t row = 0; row < rowCount; row++)
   {
-    for(int32_t col = 0; col < colCount; col += NS_MAX(actualColSpan, 1))
+    for(int32_t col = 0; col < colCount; col += std::max(actualColSpan, 1))
     {
       res = GetCellDataAt(table, row, col, getter_AddRefs(cell),
                           &currentRowIndex, &currentColIndex,
                           &rowSpan, &colSpan, 
                           &actualRowSpan, &actualColSpan, &isSelected);
       if (NS_FAILED(res)) break;
       // Skip cells that are spanned from previous rows or columns
       if (cell && row == currentRowIndex && col == currentColIndex)
@@ -1611,17 +1612,17 @@ nsHTMLEditor::SelectTableRow()
   // It is now safe to clear the selection
   // BE SURE TO RESET IT BEFORE LEAVING!
   res = ClearSelection();
 
   // Select all cells in the same row as current cell
   bool cellSelected = false;
   int32_t rowSpan, colSpan, actualRowSpan, actualColSpan, currentRowIndex, currentColIndex;
   bool    isSelected;
-  for(int32_t col = 0; col < colCount; col += NS_MAX(actualColSpan, 1))
+  for(int32_t col = 0; col < colCount; col += std::max(actualColSpan, 1))
   {
     res = GetCellDataAt(table, startRowIndex, col, getter_AddRefs(cell),
                         &currentRowIndex, &currentColIndex, &rowSpan, &colSpan, 
                         &actualRowSpan, &actualColSpan, &isSelected);
     if (NS_FAILED(res)) break;
     // Skip cells that are spanned from previous rows or columns
     if (cell && currentRowIndex == startRowIndex && currentColIndex == col)
     {
@@ -1674,17 +1675,17 @@ nsHTMLEditor::SelectTableColumn()
   // It is now safe to clear the selection
   // BE SURE TO RESET IT BEFORE LEAVING!
   res = ClearSelection();
 
   // Select all cells in the same column as current cell
   bool cellSelected = false;
   int32_t rowSpan, colSpan, actualRowSpan, actualColSpan, currentRowIndex, currentColIndex;
   bool    isSelected;
-  for(int32_t row = 0; row < rowCount; row += NS_MAX(actualRowSpan, 1))
+  for(int32_t row = 0; row < rowCount; row += std::max(actualRowSpan, 1))
   {
     res = GetCellDataAt(table, row, startColIndex, getter_AddRefs(cell),
                         &currentRowIndex, &currentColIndex, &rowSpan, &colSpan, 
                         &actualRowSpan, &actualColSpan, &isSelected);
     if (NS_FAILED(res)) break;
     // Skip cells that are spanned from previous rows or columns
     if (cell && currentRowIndex == row && currentColIndex == startColIndex)
     {
@@ -1892,17 +1893,17 @@ nsHTMLEditor::SplitCellIntoRows(nsIDOMEl
       }
       else
       {
         break; // Inserting before, so stop at first cell in row we want to insert into
       }
       lastCellFound = cell2;
     }
     // Skip to next available cellmap location
-    colIndex += NS_MAX(actualColSpan2, 1);
+    colIndex += std::max(actualColSpan2, 1);
 
     // Done when past end of total number of columns
     if (colIndex > colCount)
         break;
 
   } while(true);
 
   if (!cell2 && lastCellFound)
@@ -2055,17 +2056,17 @@ nsHTMLEditor::JoinTableCells(bool aMerge
       NS_ENSURE_SUCCESS(res, res);
       // Adjust rowcount by number of rows we removed
       lastRowIndex -= (currentRowCount-rowCount);
 
       bool cellFoundInRow = false;
       bool lastRowIsSet = false;
       int32_t lastColInRow = 0;
       int32_t firstColInRow = firstColIndex;
-      for (colIndex = firstColIndex; colIndex < colCount; colIndex += NS_MAX(actualColSpan2, 1))
+      for (colIndex = firstColIndex; colIndex < colCount; colIndex += std::max(actualColSpan2, 1))
       {
         res = GetCellDataAt(table, rowIndex, colIndex, getter_AddRefs(cell2),
                             &startRowIndex2, &startColIndex2,
                             &rowSpan2, &colSpan2, 
                             &actualRowSpan2, &actualColSpan2, &isSelected2);
         NS_ENSURE_SUCCESS(res, res);
 
         if (isSelected2)
@@ -2077,33 +2078,33 @@ nsHTMLEditor::JoinTableCells(bool aMerge
           if (rowIndex > firstRowIndex && firstColInRow != firstColIndex)
           {
             // We're in at least the second row,
             // but left boundary is "ragged" (not the same as 1st row's start)
             //Let's just end block on previous row
             // and keep previous lastColIndex
             //TODO: We could try to find the Maximum firstColInRow
             //      so our block can still extend down more rows?
-            lastRowIndex = NS_MAX(0,rowIndex - 1);
+            lastRowIndex = std::max(0,rowIndex - 1);
             lastRowIsSet = true;
             break;
           }
           // Save max selected column in this row, including extra colspan
           lastColInRow = colIndex + (actualColSpan2-1);
           cellFoundInRow = true;
         }
         else if (cellFoundInRow)
         {
           // No cell or not selected, but at least one cell in row was found
           
           if (rowIndex > (firstRowIndex+1) && colIndex <= lastColIndex)
           {
             // Cell is in a column less than current right border in 
             //  the third or higher selected row, so stop block at the previous row
-            lastRowIndex = NS_MAX(0,rowIndex - 1);
+            lastRowIndex = std::max(0,rowIndex - 1);
             lastRowIsSet = true;
           }
           // We're done with this row
           break;
         }
       } // End of column loop
 
       // Done with this row 
@@ -2118,42 +2119,42 @@ nsHTMLEditor::JoinTableCells(bool aMerge
         // If we didn't determine last row above...
         if (!lastRowIsSet)
         {
           if (colIndex < lastColIndex)
           {
             // (don't think we ever get here?)
             // Cell is in a column less than current right boundary,
             //  so stop block at the previous row
-            lastRowIndex = NS_MAX(0,rowIndex - 1);
+            lastRowIndex = std::max(0,rowIndex - 1);
           }
           else
           {
             // Go on to examine next row
             lastRowIndex = rowIndex+1;
           }
         }
         // Use the minimum col we found so far for right boundary
-        lastColIndex = NS_MIN(lastColIndex, lastColInRow);
+        lastColIndex = std::min(lastColIndex, lastColInRow);
       }
       else
       {
         // No selected cells in this row -- stop at row above
         //  and leave last column at its previous value
-        lastRowIndex = NS_MAX(0,rowIndex - 1);
+        lastRowIndex = std::max(0,rowIndex - 1);
       }
     }
   
     // The list of cells we will delete after joining
     nsTArray<nsCOMPtr<nsIDOMElement> > deleteList;
 
     // 2nd pass: Do the joining and merging
     for (rowIndex = 0; rowIndex < rowCount; rowIndex++)
     {
-      for (colIndex = 0; colIndex < colCount; colIndex += NS_MAX(actualColSpan2, 1))
+      for (colIndex = 0; colIndex < colCount; colIndex += std::max(actualColSpan2, 1))
       {
         res = GetCellDataAt(table, rowIndex, colIndex, getter_AddRefs(cell2),
                             &startRowIndex2, &startColIndex2,
                             &rowSpan2, &colSpan2, 
                             &actualRowSpan2, &actualColSpan2, &isSelected2);
         NS_ENSURE_SUCCESS(res, res);
 
         // If this is 0, we are past last cell in row, so exit the loop
@@ -2380,17 +2381,17 @@ nsHTMLEditor::FixBadRowSpan(nsIDOMElemen
 
   nsCOMPtr<nsIDOMElement>cell;
   int32_t startRowIndex, startColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
 
   int32_t minRowSpan = -1;
   int32_t colIndex;
   
-  for( colIndex = 0; colIndex < colCount; colIndex += NS_MAX(actualColSpan, 1))
+  for( colIndex = 0; colIndex < colCount; colIndex += std::max(actualColSpan, 1))
   {
     res = GetCellDataAt(aTable, aRowIndex, colIndex, getter_AddRefs(cell),
                         &startRowIndex, &startColIndex, &rowSpan, &colSpan, 
                         &actualRowSpan, &actualColSpan, &isSelected);
     // NOTE: This is a *real* failure. 
     // GetCellDataAt passes if cell is missing from cellmap
     if(NS_FAILED(res)) return res;
     if (!cell) break;
@@ -2402,17 +2403,17 @@ nsHTMLEditor::FixBadRowSpan(nsIDOMElemen
     }
     NS_ASSERTION((actualColSpan > 0),"ActualColSpan = 0 in FixBadRowSpan");
   }
   if(minRowSpan > 1)
   {
     // The amount to reduce everyone's rowspan
     // so at least one cell has rowspan = 1
     int32_t rowsReduced = minRowSpan - 1;
-    for(colIndex = 0; colIndex < colCount; colIndex += NS_MAX(actualColSpan, 1))
+    for(colIndex = 0; colIndex < colCount; colIndex += std::max(actualColSpan, 1))
     {
       res = GetCellDataAt(aTable, aRowIndex, colIndex, getter_AddRefs(cell),
                           &startRowIndex, &startColIndex, &rowSpan, &colSpan, 
                           &actualRowSpan, &actualColSpan, &isSelected);
       if(NS_FAILED(res)) return res;
       // Fixup rowspans only for cells starting in current row
       if(cell && rowSpan > 0 &&
          startRowIndex == aRowIndex && 
@@ -2438,17 +2439,17 @@ nsHTMLEditor::FixBadColSpan(nsIDOMElemen
 
   nsCOMPtr<nsIDOMElement> cell;
   int32_t startRowIndex, startColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
 
   int32_t minColSpan = -1;
   int32_t rowIndex;
   
-  for( rowIndex = 0; rowIndex < rowCount; rowIndex += NS_MAX(actualRowSpan, 1))
+  for( rowIndex = 0; rowIndex < rowCount; rowIndex += std::max(actualRowSpan, 1))
   {
     res = GetCellDataAt(aTable, rowIndex, aColIndex, getter_AddRefs(cell),
                         &startRowIndex, &startColIndex, &rowSpan, &colSpan, 
                         &actualRowSpan, &actualColSpan, &isSelected);
     // NOTE: This is a *real* failure. 
     // GetCellDataAt passes if cell is missing from cellmap
     if(NS_FAILED(res)) return res;
     if (!cell) break;
@@ -2460,17 +2461,17 @@ nsHTMLEditor::FixBadColSpan(nsIDOMElemen
     }
     NS_ASSERTION((actualRowSpan > 0),"ActualRowSpan = 0 in FixBadColSpan");
   }
   if(minColSpan > 1)
   {
     // The amount to reduce everyone's colspan
     // so at least one cell has colspan = 1
     int32_t colsReduced = minColSpan - 1;
-    for(rowIndex = 0; rowIndex < rowCount; rowIndex += NS_MAX(actualRowSpan, 1))
+    for(rowIndex = 0; rowIndex < rowCount; rowIndex += std::max(actualRowSpan, 1))
     {
       res = GetCellDataAt(aTable, rowIndex, aColIndex, getter_AddRefs(cell),
                           &startRowIndex, &startColIndex, &rowSpan, &colSpan, 
                           &actualRowSpan, &actualColSpan, &isSelected);
       if(NS_FAILED(res)) return res;
       // Fixup colspans only for cells starting in current column
       if(cell && colSpan > 0 &&
          startColIndex == aColIndex && 
@@ -3336,17 +3337,17 @@ nsHTMLEditor::GetSelectedCellsType(nsIDO
 bool 
 nsHTMLEditor::AllCellsInRowSelected(nsIDOMElement *aTable, int32_t aRowIndex, int32_t aNumberOfColumns)
 {
   NS_ENSURE_TRUE(aTable, false);
 
   int32_t curStartRowIndex, curStartColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
 
-  for( int32_t col = 0; col < aNumberOfColumns; col += NS_MAX(actualColSpan, 1))
+  for( int32_t col = 0; col < aNumberOfColumns; col += std::max(actualColSpan, 1))
   {
     nsCOMPtr<nsIDOMElement> cell;    
     nsresult res = GetCellDataAt(aTable, aRowIndex, col, getter_AddRefs(cell),
                                  &curStartRowIndex, &curStartColIndex,
                                  &rowSpan, &colSpan,
                                  &actualRowSpan, &actualColSpan, &isSelected);
  
     NS_ENSURE_SUCCESS(res, false);
@@ -3365,17 +3366,17 @@ nsHTMLEditor::AllCellsInRowSelected(nsID
 bool 
 nsHTMLEditor::AllCellsInColumnSelected(nsIDOMElement *aTable, int32_t aColIndex, int32_t aNumberOfRows)
 {
   NS_ENSURE_TRUE(aTable, false);
 
   int32_t curStartRowIndex, curStartColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
 
-  for( int32_t row = 0; row < aNumberOfRows; row += NS_MAX(actualRowSpan, 1))
+  for( int32_t row = 0; row < aNumberOfRows; row += std::max(actualRowSpan, 1))
   {
     nsCOMPtr<nsIDOMElement> cell;    
     nsresult res = GetCellDataAt(aTable, row, aColIndex, getter_AddRefs(cell),
                                  &curStartRowIndex, &curStartColIndex,
                                  &rowSpan, &colSpan,
                                  &actualRowSpan, &actualColSpan, &isSelected);
     
     NS_ENSURE_SUCCESS(res, false);
--- a/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
+++ b/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
@@ -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/. */
 
 #include "mozilla/Util.h"
 
 #include "nspr.h"
 
 #include "nsIFileStreams.h"       // New Necko file streams
+#include <algorithm>
 
 #ifdef XP_OS2
 #include "nsILocalFileOS2.h"
 #endif
 
 #include "nsNetUtil.h"
 #include "nsComponentManagerUtils.h"
 #include "nsIComponentRegistrar.h"
@@ -827,17 +828,17 @@ nsWebBrowserPersist::OnDataAvailable(
 
         // Read data from the input and write to the output
         char buffer[8192];
         uint32_t bytesRead;
         while (!cancel && bytesRemaining)
         {
             readError = true;
             rv = aIStream->Read(buffer,
-                                NS_MIN(uint32_t(sizeof(buffer)), bytesRemaining),
+                                std::min(uint32_t(sizeof(buffer)), bytesRemaining),
                                 &bytesRead);
             if (NS_SUCCEEDED(rv))
             {
                 readError = false;
                 // Write out the data until something goes wrong, or, it is
                 // all written.  We loop because for some errors (e.g., disk
                 // full), we get NS_OK with some bytes written, then an error.
                 // So, we want to write again in that case to get the actual
--- a/extensions/gio/nsGIOProtocolHandler.cpp
+++ b/extensions/gio/nsGIOProtocolHandler.cpp
@@ -14,16 +14,17 @@
 #include "nsThreadUtils.h"
 #include "nsProxyRelease.h"
 #include "nsIStringBundle.h"
 #include "nsIStandardURL.h"
 #include "nsMimeTypes.h"
 #include "nsNetUtil.h"
 #include "mozilla/Monitor.h"
 #include <gio/gio.h>
+#include <algorithm>
 
 #define MOZ_GIO_SCHEME              "moz-gio"
 #define MOZ_GIO_SUPPORTED_PROTOCOLS "network.gio.supported-protocols"
 
 //-----------------------------------------------------------------------------
 
 // NSPR_LOG_MODULES=gio:5
 #ifdef PR_LOGGING
@@ -442,17 +443,17 @@ nsGIOInputStream::DoRead(char *aBuf, uin
   else if (mDirOpen) {
     // directory read
     while (aCount && rv != NS_BASE_STREAM_CLOSED)
     {
       // Copy data out of our buffer
       uint32_t bufLen = mDirBuf.Length() - mDirBufCursor;
       if (bufLen)
       {
-        uint32_t n = NS_MIN(bufLen, aCount);
+        uint32_t n = std::min(bufLen, aCount);
         memcpy(aBuf, mDirBuf.get() + mDirBufCursor, n);
         *aCountRead += n;
         aBuf += n;
         aCount -= n;
         mDirBufCursor += n;
       }
 
       if (!mDirListPtr)    // Are we at the end of the directory list?
--- a/extensions/gnomevfs/nsGnomeVFSProtocolHandler.cpp
+++ b/extensions/gnomevfs/nsGnomeVFSProtocolHandler.cpp
@@ -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/. */
 
 // GnomeVFS v2.2.2 is missing G_BEGIN_DECLS in gnome-vfs-module-callback.h
 extern "C" {
 #include <libgnomevfs/gnome-vfs.h>
 #include <libgnomevfs/gnome-vfs-standard-callbacks.h>
 #include <libgnomevfs/gnome-vfs-mime-utils.h>
+#include <algorithm>
 }
 
 #include "nsServiceManagerUtils.h"
 #include "nsComponentManagerUtils.h"
 #include "mozilla/ModuleUtils.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
@@ -490,17 +491,17 @@ nsGnomeVFSInputStream::DoRead(char *aBuf
     rv = GNOME_VFS_OK;
 
     while (aCount && rv != GNOME_VFS_ERROR_EOF)
     {
       // Copy data out of our buffer
       uint32_t bufLen = mDirBuf.Length() - mDirBufCursor;
       if (bufLen)
       {
-        uint32_t n = NS_MIN(bufLen, aCount);
+        uint32_t n = std::min(bufLen, aCount);
         memcpy(aBuf, mDirBuf.get() + mDirBufCursor, n);
         *aCountRead += n;
         aBuf += n;
         aCount -= n;
         mDirBufCursor += n;
       }
 
       if (!mDirListPtr)    // Are we at the end of the directory list?
--- a/extensions/pref/autoconfig/src/nsAutoConfig.cpp
+++ b/extensions/pref/autoconfig/src/nsAutoConfig.cpp
@@ -16,16 +16,17 @@
 #include "prmem.h"
 #include "nsIObserverService.h"
 #include "nsLiteralString.h"
 #include "nsIPromptService.h"
 #include "nsIServiceManager.h"
 #include "nsIStringBundle.h"
 #include "nsCRT.h"
 #include "nspr.h"
+#include <algorithm>
 
 PRLogModuleInfo *MCD;
 
 extern nsresult EvaluateAdminConfigScript(const char *js_buffer, size_t length,
                                           const char *filename, 
                                           bool bGlobalContext, 
                                           bool bCallbacks, 
                                           bool skipFirstLine);
@@ -98,17 +99,17 @@ nsAutoConfig::OnDataAvailable(nsIRequest
                               uint64_t aSourceOffset,
                               uint32_t aLength)
 {    
     uint32_t amt, size;
     nsresult rv;
     char buf[1024];
     
     while (aLength) {
-        size = NS_MIN<size_t>(aLength, sizeof(buf));
+        size = std::min<size_t>(aLength, sizeof(buf));
         rv = aIStream->Read(buf, size, &amt);
         if (NS_FAILED(rv))
             return rv;
         mBuf.Append(buf, amt);
         aLength -= amt;
     }
     return NS_OK;
 }
--- a/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
+++ b/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
@@ -17,16 +17,17 @@
 #include "nsUnicodeProperties.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIContent.h"
 #include "nsTextFragment.h"
 #include "mozilla/dom/Element.h"
 #include "nsRange.h"
 #include "nsContentUtils.h"
 #include "nsIFrame.h"
+#include <algorithm>
 
 using namespace mozilla;
 
 // IsIgnorableCharacter
 //
 //    These characters are ones that we should ignore in input.
 
 inline bool IsIgnorableCharacter(PRUnichar ch)
@@ -383,17 +384,17 @@ static bool
 TextNodeContainsDOMWordSeparator(nsINode* aNode,
                                  int32_t aBeforeOffset,
                                  int32_t* aSeparatorOffset)
 {
   // aNode is actually an nsIContent, since it's eTEXT
   nsIContent* content = static_cast<nsIContent*>(aNode);
   const nsTextFragment* textFragment = content->GetText();
   NS_ASSERTION(textFragment, "Where is our text?");
-  for (int32_t i = NS_MIN(aBeforeOffset, int32_t(textFragment->GetLength())) - 1; i >= 0; --i) {
+  for (int32_t i = std::min(aBeforeOffset, int32_t(textFragment->GetLength())) - 1; i >= 0; --i) {
     if (IsDOMWordSeparator(textFragment->CharAt(i))) {
       // Be greedy, find as many separators as we can
       for (int32_t j = i - 1; j >= 0; --j) {
         if (IsDOMWordSeparator(textFragment->CharAt(j))) {
           i = j;
         } else {
           break;
         }
--- a/gfx/2d/BaseRect.h
+++ b/gfx/2d/BaseRect.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 MOZILLA_GFX_BASERECT_H_
 #define MOZILLA_GFX_BASERECT_H_
 
 #include <cmath>
 #include <mozilla/Assertions.h>
+#include <algorithm>
 
 namespace mozilla {
 namespace gfx {
 
 // XXX - <algorithm> conflicts with exceptions on 10.6. Define our own gfx_min/gfx_max
 // functions here. Avoid min/max to avoid conflicts with existing #defines on windows.
 template<typename T>
 T gfx_min(T aVal1, T aVal2)
@@ -420,18 +421,18 @@ struct BaseRect {
   }
 
   /**
    * Clamp aPoint to this rectangle. It is allowed to end up on any
    * edge of the rectangle.
    */
   Point ClampPoint(const Point& aPoint) const
   {
-    return Point(NS_MAX(x, NS_MIN(XMost(), aPoint.x)),
-                 NS_MAX(y, NS_MIN(YMost(), aPoint.y)));
+    return Point(std::max(x, std::min(XMost(), aPoint.x)),
+                 std::max(y, std::min(YMost(), aPoint.y)));
   }
 
 private:
   // Do not use the default operator== or operator!= !
   // Use IsEqualEdges or IsEqualInterior explicitly.
   bool operator==(const Sub& aRect) const { return false; }
   bool operator!=(const Sub& aRect) const { return false; }
 };
--- a/gfx/2d/convolver.cpp
+++ b/gfx/2d/convolver.cpp
@@ -249,18 +249,18 @@ void ConvolveVertically(const Convolutio
 
       // Make sure the alpha channel doesn't come out smaller than any of the
       // color channels. We use premultipled alpha channels, so this should
       // never happen, but rounding errors will cause this from time to time.
       // These "impossible" colors will cause overflows (and hence random pixel
       // values) when the resulting bitmap is drawn to the screen.
       //
       // We only need to do this when generating the final output row (here).
-      int max_color_channel = NS_MAX(out_row[byte_offset + R_OFFSET_IDX],
-          NS_MAX(out_row[byte_offset + G_OFFSET_IDX], out_row[byte_offset + B_OFFSET_IDX]));
+      int max_color_channel = std::max(out_row[byte_offset + R_OFFSET_IDX],
+          std::max(out_row[byte_offset + G_OFFSET_IDX], out_row[byte_offset + B_OFFSET_IDX]));
       if (alpha < max_color_channel)
         out_row[byte_offset + A_OFFSET_IDX] = max_color_channel;
       else
         out_row[byte_offset + A_OFFSET_IDX] = alpha;
     } else {
       // No alpha channel, the image is opaque.
       out_row[byte_offset + A_OFFSET_IDX] = 0xff;
     }
@@ -751,17 +751,17 @@ void ConvolutionFilter1D::AddFilter(int 
 
   // We pushed filter_length elements onto filter_values_
   instance.data_location = (static_cast<int>(filter_values_.size()) -
                             filter_length);
   instance.offset = filter_offset;
   instance.length = filter_length;
   filters_.push_back(instance);
 
-  max_filter_ = NS_MAX(max_filter_, filter_length);
+  max_filter_ = std::max(max_filter_, filter_length);
 }
 
 void BGRAConvolve2D(const unsigned char* source_data,
                     int source_byte_row_stride,
                     bool source_has_alpha,
                     const ConvolutionFilter1D& filter_x,
                     const ConvolutionFilter1D& filter_y,
                     int output_byte_row_stride,
--- a/gfx/2d/image_operations.cpp
+++ b/gfx/2d/image_operations.cpp
@@ -241,17 +241,17 @@ void ResizeFilter::ComputeFilters(int sr
                                   ConvolutionFilter1D* output) {
   int dest_subset_hi = dest_subset_lo + dest_subset_size;  // [lo, hi)
 
   // When we're doing a magnification, the scale will be larger than one. This
   // means the destination pixels are much smaller than the source pixels, and
   // that the range covered by the filter won't necessarily cover any source
   // pixel boundaries. Therefore, we use these clamped values (max of 1) for
   // some computations.
-  float clamped_scale = NS_MIN(1.0f, scale);
+  float clamped_scale = std::min(1.0f, scale);
 
   // Speed up the divisions below by turning them into multiplies.
   float inv_scale = 1.0f / scale;
 
   StackVector<float, 64> filter_values;
   StackVector<int16_t, 64> fixed_filter_values;
 
   // Loop over all pixels in the output range. We will generate one set of
@@ -268,18 +268,18 @@ void ResizeFilter::ComputeFilters(int sr
     // Note that we base computations on the "center" of the pixels. To see
     // why, observe that the destination pixel at coordinates (0, 0) in a 5.0x
     // downscale should "cover" the pixels around the pixel with *its center*
     // at coordinates (2.5, 2.5) in the source, not those around (0, 0).
     // Hence we need to scale coordinates (0.5, 0.5), not (0, 0).
     float src_pixel = (static_cast<float>(dest_subset_i) + 0.5f) * inv_scale;
 
     // Compute the (inclusive) range of source pixels the filter covers.
-    int src_begin = NS_MAX(0, FloorInt(src_pixel - src_support));
-    int src_end = NS_MIN(src_size - 1, CeilInt(src_pixel + src_support));
+    int src_begin = std::max(0, FloorInt(src_pixel - src_support));
+    int src_end = std::min(src_size - 1, CeilInt(src_pixel + src_support));
 
     // Compute the unnormalized filter value at each location of the source
     // it covers.
     float filter_sum = 0.0f;  // Sub of the filter values for normalizing.
     for (int cur_filter_pixel = src_begin; cur_filter_pixel <= src_end;
          cur_filter_pixel++) {
       // Distance from the center of the filter, this is the filter coordinate
       // in source space. We also need to consider the center of the pixel
--- a/gfx/gl/GLContext.cpp
+++ b/gfx/gl/GLContext.cpp
@@ -541,28 +541,28 @@ GLContext::InitWithPrefix(const char *pr
         raw_fGetIntegerv(LOCAL_GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
         raw_fGetIntegerv(LOCAL_GL_MAX_CUBE_MAP_TEXTURE_SIZE, &mMaxCubeMapTextureSize);
         raw_fGetIntegerv(LOCAL_GL_MAX_RENDERBUFFER_SIZE, &mMaxRenderbufferSize);
 
 #ifdef XP_MACOSX
         if (mWorkAroundDriverBugs &&
             mVendor == VendorIntel) {
             // see bug 737182 for 2D textures, bug 684882 for cube map textures.
-            mMaxTextureSize        = NS_MIN(mMaxTextureSize,        4096);
-            mMaxCubeMapTextureSize = NS_MIN(mMaxCubeMapTextureSize, 512);
+            mMaxTextureSize        = std::min(mMaxTextureSize,        4096);
+            mMaxCubeMapTextureSize = std::min(mMaxCubeMapTextureSize, 512);
             // for good measure, we align renderbuffers on what we do for 2D textures
-            mMaxRenderbufferSize   = NS_MIN(mMaxRenderbufferSize,   4096);
+            mMaxRenderbufferSize   = std::min(mMaxRenderbufferSize,   4096);
             mNeedsTextureSizeChecks = true;
         }
 #endif
 #ifdef MOZ_X11
         if (mWorkAroundDriverBugs &&
             mVendor == VendorNouveau) {
             // see bug 814716. Clamp MaxCubeMapTextureSize at 2K for Nouveau.
-            mMaxCubeMapTextureSize = NS_MIN(mMaxCubeMapTextureSize, 2048);
+            mMaxCubeMapTextureSize = std::min(mMaxCubeMapTextureSize, 2048);
             mNeedsTextureSizeChecks = true;
         }
 #endif
 
         mMaxTextureImageSize = mMaxTextureSize;
 
         UpdateActualFormat();
     }
@@ -875,17 +875,17 @@ GLContext::ChooseGLFormats(ContextFormat
         }
     }
 
     GLsizei samples = aCF.samples;
 
     GLsizei maxSamples = 0;
     if (SupportsFramebufferMultisample())
         fGetIntegerv(LOCAL_GL_MAX_SAMPLES, (GLint*)&maxSamples);
-    samples = NS_MIN(samples, maxSamples);
+    samples = std::min(samples, maxSamples);
 
     // bug 778765
     if (WorkAroundDriverBugs() && samples == 1) {
         samples = 0;
     }
 
     formats.samples = samples;
     aCF.samples = samples;
@@ -1986,17 +1986,17 @@ GLContext::TexImage2D(GLenum target, GLi
             GLvoid* paddedPixels = new unsigned char[paddedWidth * paddedHeight * pixelsize];
 
             // Pad out texture data to be in a POT sized buffer for uploading to
             // a POT sized texture
             CopyAndPadTextureData(pixels, paddedPixels, width, height,
                                   paddedWidth, paddedHeight, stride, pixelsize);
 
             fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT,
-                    NS_MIN(GetAddressAlignment((ptrdiff_t)paddedPixels),
+                    std::min(GetAddressAlignment((ptrdiff_t)paddedPixels),
                             GetAddressAlignment((ptrdiff_t)paddedWidth * pixelsize)));
             fTexImage2D(target,
                         border,
                         internalformat,
                         paddedWidth,
                         paddedHeight,
                         border,
                         format,
@@ -2005,17 +2005,17 @@ GLContext::TexImage2D(GLenum target, GLi
             fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT, 4);
 
             delete[] static_cast<unsigned char*>(paddedPixels);
             return;
         }
 
         if (stride == width * pixelsize) {
             fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT,
-                    NS_MIN(GetAddressAlignment((ptrdiff_t)pixels),
+                    std::min(GetAddressAlignment((ptrdiff_t)pixels),
                             GetAddressAlignment((ptrdiff_t)stride)));
             fTexImage2D(target,
                         border,
                         internalformat,
                         width,
                         height,
                         border,
                         format,
@@ -2045,17 +2045,17 @@ GLContext::TexImage2D(GLenum target, GLi
                           format,
                           type,
                           pixels);
         }
     } else {
         // desktop GL (non-ES) path
 
         fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT,
-                    NS_MIN(GetAddressAlignment((ptrdiff_t)pixels),
+                    std::min(GetAddressAlignment((ptrdiff_t)pixels),
                             GetAddressAlignment((ptrdiff_t)stride)));
         int rowLength = stride/pixelsize;
         fPixelStorei(LOCAL_GL_UNPACK_ROW_LENGTH, rowLength);
         fTexImage2D(target,
                     level,
                     internalformat,
                     width,
                     height,
@@ -2073,17 +2073,17 @@ GLContext::TexSubImage2D(GLenum target, 
                          GLint xoffset, GLint yoffset,
                          GLsizei width, GLsizei height, GLsizei stride,
                          GLint pixelsize, GLenum format,
                          GLenum type, const GLvoid* pixels)
 {
     if (mIsGLES2) {
         if (stride == width * pixelsize) {
             fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT,
-                    NS_MIN(GetAddressAlignment((ptrdiff_t)pixels),
+                    std::min(GetAddressAlignment((ptrdiff_t)pixels),
                             GetAddressAlignment((ptrdiff_t)stride)));
             fTexSubImage2D(target,
                           level,
                           xoffset,
                           yoffset,
                           width,
                           height,
                           format,
@@ -2098,17 +2098,17 @@ GLContext::TexSubImage2D(GLenum target, 
         } else {
             TexSubImage2DWithoutUnpackSubimage(target, level, xoffset, yoffset,
                                               width, height, stride,
                                               pixelsize, format, type, pixels);
         }
     } else {
         // desktop GL (non-ES) path
         fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT,
-                    NS_MIN(GetAddressAlignment((ptrdiff_t)pixels),
+                    std::min(GetAddressAlignment((ptrdiff_t)pixels),
                             GetAddressAlignment((ptrdiff_t)stride)));
         int rowLength = stride/pixelsize;
         fPixelStorei(LOCAL_GL_UNPACK_ROW_LENGTH, rowLength);
         fTexSubImage2D(target,
                       level,
                       xoffset,
                       yoffset,
                       width,
@@ -2125,17 +2125,17 @@ void
 GLContext::TexSubImage2DWithUnpackSubimageGLES(GLenum target, GLint level,
                                                GLint xoffset, GLint yoffset,
                                                GLsizei width, GLsizei height,
                                                GLsizei stride, GLint pixelsize,
                                                GLenum format, GLenum type,
                                                const GLvoid* pixels)
 {
     fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT,
-                 NS_MIN(GetAddressAlignment((ptrdiff_t)pixels),
+                 std::min(GetAddressAlignment((ptrdiff_t)pixels),
                         GetAddressAlignment((ptrdiff_t)stride)));
     // When using GL_UNPACK_ROW_LENGTH, we need to work around a Tegra
     // driver crash where the driver apparently tries to read
     // (stride - width * pixelsize) bytes past the end of the last input
     // row. We only upload the first height-1 rows using GL_UNPACK_ROW_LENGTH,
     // and then we upload the final row separately. See bug 697990.
     int rowLength = stride/pixelsize;
     fPixelStorei(LOCAL_GL_UNPACK_ROW_LENGTH, rowLength);
@@ -2179,17 +2179,17 @@ GLContext::TexSubImage2DWithoutUnpackSub
     for (int h = 0; h < height; h++) {
             memcpy(rowDest, rowSource, width*pixelsize);
             rowDest += width*pixelsize;
             rowSource += stride;
     }
 
     stride = width*pixelsize;
     fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT,
-                    NS_MIN(GetAddressAlignment((ptrdiff_t)newPixels),
+                    std::min(GetAddressAlignment((ptrdiff_t)newPixels),
                             GetAddressAlignment((ptrdiff_t)stride)));
     fTexSubImage2D(target,
                     level,
                     xoffset,
                     yoffset,
                     width,
                     height,
                     format,
--- a/gfx/gl/GLContext.h
+++ b/gfx/gl/GLContext.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 GLCONTEXT_H_
 #define GLCONTEXT_H_
 
 #include <stdio.h>
+#include <algorithm>
 #if defined(XP_UNIX)
 #include <stdint.h>
 #endif
 #include <string.h>
 #include <ctype.h>
 
 #ifdef WIN32
 #include <windows.h>
@@ -1580,18 +1581,18 @@ protected:
     CreateBasicTextureImage(GLuint aTexture,
                             const nsIntSize& aSize,
                             GLenum aWrapMode,
                             TextureImage::ContentType aContentType,
                             GLContext* aContext,
                             TextureImage::Flags aFlags = TextureImage::NoFlags);
 
     bool IsOffscreenSizeAllowed(const gfxIntSize& aSize) const {
-        int32_t biggerDimension = NS_MAX(aSize.width, aSize.height);
-        int32_t maxAllowed = NS_MIN(mMaxRenderbufferSize, mMaxTextureSize);
+        int32_t biggerDimension = std::max(aSize.width, aSize.height);
+        int32_t maxAllowed = std::min(mMaxRenderbufferSize, mMaxTextureSize);
         return biggerDimension <= maxAllowed;
     }
 
     nsTArray<nsIntRect> mViewportStack;
     nsTArray<nsIntRect> mScissorStack;
 
     GLint mMaxTextureSize;
     GLint mMaxCubeMapTextureSize;
--- a/gfx/layers/ThebesLayerBuffer.cpp
+++ b/gfx/layers/ThebesLayerBuffer.cpp
@@ -8,16 +8,17 @@
 #include "ThebesLayerBuffer.h"
 #include "Layers.h"
 #include "gfxContext.h"
 #include "gfxPlatform.h"
 #include "gfxUtils.h"
 #include "ipc/AutoOpenSurface.h"
 #include "nsDeviceContext.h"
 #include "sampler.h"
+#include <algorithm>
 
 namespace mozilla {
 namespace layers {
 
 nsIntRect
 ThebesLayerBuffer::GetQuadrantRectangle(XSide aXSide, YSide aYSide)
 {
   // quadrantTranslation is the amount we translate the top-left
@@ -173,17 +174,17 @@ static nsIntRect
 ComputeBufferRect(const nsIntRect& aRequestedRect)
 {
   nsIntRect rect(aRequestedRect);
   // Set a minimum width to guarantee a minimum size of buffers we
   // allocate (and work around problems on some platforms with smaller
   // dimensions).  64 is the magic number needed to work around the
   // rendering glitch, and guarantees image rows can be SIMD'd for
   // even r5g6b5 surfaces pretty much everywhere.
-  rect.width = NS_MAX(aRequestedRect.width, 64);
+  rect.width = std::max(aRequestedRect.width, 64);
   return rect;
 }
 
 ThebesLayerBuffer::PaintState
 ThebesLayerBuffer::BeginPaint(ThebesLayer* aLayer, ContentType aContentType,
                               uint32_t aFlags)
 {
   PaintState result;
--- a/gfx/layers/d3d9/DeviceManagerD3D9.cpp
+++ b/gfx/layers/d3d9/DeviceManagerD3D9.cpp
@@ -6,16 +6,17 @@
 #include "DeviceManagerD3D9.h"
 #include "LayerManagerD3D9Shaders.h"
 #include "ThebesLayerD3D9.h"
 #include "nsIServiceManager.h"
 #include "nsIConsoleService.h"
 #include "nsPrintfCString.h"
 #include "Nv3DVUtils.h"
 #include "plstr.h"
+#include <algorithm>
 
 namespace mozilla {
 namespace layers {
 
 const LPCWSTR kClassName       = L"D3D9WindowClass";
 
 #define USE_D3D9EX
 
@@ -756,17 +757,17 @@ DeviceManagerD3D9::VerifyCaps()
   if (LACKS_CAP(caps.TextureAddressCaps, D3DPTADDRESSCAPS_CLAMP)) {
     return false;
   }
 
   if (caps.MaxTextureHeight < 4096 ||
       caps.MaxTextureWidth < 4096) {
     return false;
   }
-  mMaxTextureSize = NS_MIN(caps.MaxTextureHeight, caps.MaxTextureWidth);
+  mMaxTextureSize = std::min(caps.MaxTextureHeight, caps.MaxTextureWidth);
 
   if ((caps.PixelShaderVersion & 0xffff) < 0x200 ||
       (caps.VertexShaderVersion & 0xffff) < 0x200) {
     return false;
   }
 
   if (HAS_CAP(caps.Caps2, D3DCAPS2_DYNAMICTEXTURES)) {
     mHasDynamicTextures = true;
--- a/gfx/layers/ipc/AsyncPanZoomController.cpp
+++ b/gfx/layers/ipc/AsyncPanZoomController.cpp
@@ -13,16 +13,17 @@
 #include "mozilla/Monitor.h"
 #include "mozilla/StaticPtr.h"
 #include "AsyncPanZoomController.h"
 #include "GestureEventListener.h"
 #include "nsIThreadManager.h"
 #include "nsThreadUtils.h"
 #include "Layers.h"
 #include "AnimationCommon.h"
+#include <algorithm>
 
 using namespace mozilla::css;
 
 namespace mozilla {
 namespace layers {
 
 /**
  * Constant describing the tolerance in distance we use, multiplied by the
@@ -1054,17 +1055,17 @@ void AsyncPanZoomController::RequestCont
 
   SendAsyncScrollEvent();
 
   // Cache the zoom since we're temporarily changing it for
   // acceleration-scaled painting.
   gfxFloat actualZoom = mFrameMetrics.mZoom.width;
   // Calculate the factor of acceleration based on the faster of the two axes.
   float accelerationFactor =
-    clamped(NS_MAX(mX.GetAccelerationFactor(), mY.GetAccelerationFactor()),
+    clamped(std::max(mX.GetAccelerationFactor(), mY.GetAccelerationFactor()),
             float(MIN_ZOOM) / 2.0f, float(MAX_ZOOM));
   // Scale down the resolution a bit based on acceleration.
   mFrameMetrics.mZoom.width = mFrameMetrics.mZoom.height =
                               actualZoom / accelerationFactor;
 
   // This message is compressed, so fire whether or not we already have a paint
   // queued up. We need to know whether or not a paint was requested anyways,
   // for the purposes of content calling window.scrollTo().
@@ -1339,28 +1340,28 @@ void AsyncPanZoomController::ZoomToRect(
 
       zoomToRect = gfx::Rect(0.0f,
                              y + dh/2,
                              cssPageRect.width,
                              y + dh/2 + newHeight);
     }
 
     gfxFloat targetResolution =
-      NS_MIN(compositionBounds.width / zoomToRect.width,
+      std::min(compositionBounds.width / zoomToRect.width,
              compositionBounds.height / zoomToRect.height);
 
     // Recalculate the zoom to rect using the new dimensions.
     zoomToRect.width = compositionBounds.width / targetResolution;
     zoomToRect.height = compositionBounds.height / targetResolution;
 
     // Clamp the zoom to rect to the CSS rect to make sure it fits.
     zoomToRect = zoomToRect.Intersect(cssPageRect);
 
     // Do one final recalculation to get the resolution.
-    targetResolution = NS_MAX(compositionBounds.width / zoomToRect.width,
+    targetResolution = std::max(compositionBounds.width / zoomToRect.width,
                               compositionBounds.height / zoomToRect.height);
     float targetZoom = float(targetResolution / resolution.width) * mFrameMetrics.mZoom.width;
 
     // If current zoom is equal to mMaxZoom,
     // user still double-tapping it, just zoom-out to the full page size
     if (mFrameMetrics.mZoom.width == mMaxZoom && targetZoom >= mMaxZoom) {
       nsIntRect cssCompositionBounds = compositionBounds;
       cssCompositionBounds.ScaleInverseRoundIn(resolution.width,
--- a/gfx/layers/ipc/Axis.cpp
+++ b/gfx/layers/ipc/Axis.cpp
@@ -2,16 +2,17 @@
 /* vim: set sw=4 ts=8 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 "Axis.h"
 #include "AsyncPanZoomController.h"
 #include "mozilla/Preferences.h"
+#include <algorithm>
 
 namespace mozilla {
 namespace layers {
 
 static const float EPSILON = 0.0001f;
 
 /**
  * Maximum acceleration that can happen between two frames. Velocity is
@@ -105,17 +106,17 @@ void Axis::UpdateWithTouchAtDevicePoint(
   }
 
   // If a direction change has happened, or the current velocity due to this new
   // touch is relatively low, then just apply it. If not, throttle it.
   if (curVelocityIsLow || (directionChange && fabs(newVelocity) - EPSILON <= 0.0f)) {
     mVelocity = newVelocity;
   } else {
     float maxChange = fabsf(mVelocity * aTimeDelta.ToMilliseconds() * gMaxEventAcceleration);
-    mVelocity = NS_MIN(mVelocity + maxChange, NS_MAX(mVelocity - maxChange, newVelocity));
+    mVelocity = std::min(mVelocity + maxChange, std::max(mVelocity - maxChange, newVelocity));
   }
 
   mVelocity = newVelocity;
   mPos = aPos;
 }
 
 void Axis::StartTouch(int32_t aPos) {
   mStartPos = aPos;
@@ -255,17 +256,17 @@ float Axis::ScaleWillOverscrollAmount(fl
   }
 }
 
 float Axis::GetVelocity() {
   return mVelocity;
 }
 
 float Axis::GetAccelerationFactor() {
-  return powf(gAccelerationMultiplier, NS_MAX(0, (mAcceleration - 4) * 3));
+  return powf(gAccelerationMultiplier, std::max(0, (mAcceleration - 4) * 3));
 }
 
 float Axis::GetCompositionEnd() {
   return GetOrigin() + GetCompositionLength();
 }
 
 float Axis::GetPageEnd() {
   return GetPageStart() + GetPageLength();
--- a/gfx/layers/ipc/CompositorParent.cpp
+++ b/gfx/layers/ipc/CompositorParent.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 <map>
 
 #include "mozilla/DebugOnly.h"
 
 #include "base/basictypes.h"
+#include <algorithm>
 
 #if defined(MOZ_WIDGET_ANDROID)
 # include <android/log.h>
 # include "AndroidBridge.h"
 #endif
 
 #include "AsyncPanZoomController.h"
 #include "AutoOpenSurface.h"
@@ -978,27 +979,27 @@ CompositorParent::TransformScrollableLay
   treeTransform = gfx3DMatrix(ViewTransform(-scrollCompensation,
                                             gfxSize(mXScale, mYScale)));
 
   // If the contents can fit entirely within the widget area on a particular
   // dimenson, we need to translate and scale so that the fixed layers remain
   // within the page boundaries.
   if (mContentRect.width * tempScaleDiffX < metrics.mCompositionBounds.width) {
     offset.x = -metricsScrollOffset.x;
-    scaleDiff.width = NS_MIN(1.0f, metrics.mCompositionBounds.width / (float)mContentRect.width);
+    scaleDiff.width = std::min(1.0f, metrics.mCompositionBounds.width / (float)mContentRect.width);
   } else {
     offset.x = clamped(mScrollOffset.x / tempScaleDiffX, (float)mContentRect.x,
                        mContentRect.XMost() - metrics.mCompositionBounds.width / tempScaleDiffX) -
                metricsScrollOffset.x;
     scaleDiff.width = tempScaleDiffX;
   }
 
   if (mContentRect.height * tempScaleDiffY < metrics.mCompositionBounds.height) {
     offset.y = -metricsScrollOffset.y;
-    scaleDiff.height = NS_MIN(1.0f, metrics.mCompositionBounds.height / (float)mContentRect.height);
+    scaleDiff.height = std::min(1.0f, metrics.mCompositionBounds.height / (float)mContentRect.height);
   } else {
     offset.y = clamped(mScrollOffset.y / tempScaleDiffY, (float)mContentRect.y,
                        mContentRect.YMost() - metrics.mCompositionBounds.height / tempScaleDiffY) -
                metricsScrollOffset.y;
     scaleDiff.height = tempScaleDiffY;
   }
 
   // The transform already takes the resolution scale into account.  Since we
--- a/gfx/layers/opengl/LayerManagerOGL.cpp
+++ b/gfx/layers/opengl/LayerManagerOGL.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 20; 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 "LayerManagerOGL.h"
 
 #include "mozilla/layers/PLayers.h"
+#include <algorithm>
 
 /* This must occur *after* layers/PLayers.h to avoid typedefs conflicts. */
 #include "mozilla/Util.h"
 
 #include "Composer2D.h"
 #include "ThebesLayerOGL.h"
 #include "ContainerLayerOGL.h"
 #include "ImageLayerOGL.h"
@@ -171,17 +172,17 @@ private:
     TimeStamp beginningOfWindow =
       (aNow - TimeDuration::FromMilliseconds(kFpsWindowMs));
     TimeStamp earliestFrameInWindow = aNow;
     size_t numFramesDrawnInWindow = 0;
     for (size_t i = 0; i < kNumFrameTimeStamps; ++i) {
       const TimeStamp& frame = mFrames[i];
       if (!frame.IsNull() && frame > beginningOfWindow) {
         ++numFramesDrawnInWindow;
-        earliestFrameInWindow = NS_MIN(earliestFrameInWindow, frame);
+        earliestFrameInWindow = std::min(earliestFrameInWindow, frame);
       }
     }
     double realWindowSecs = (aNow - earliestFrameInWindow).ToSeconds();
     if (realWindowSecs == 0.0 || numFramesDrawnInWindow == 1) {
       return 0.0;
     }
     return double(numFramesDrawnInWindow - 1) / realWindowSecs;
   }
--- a/gfx/src/nsBoundingMetrics.h
+++ b/gfx/src/nsBoundingMetrics.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 __nsBoundingMetrics_h
 #define __nsBoundingMetrics_h
 
 #include "nsCoord.h"
+#include <algorithm>
 
 /* Struct used for accurate measurements of a string, in order to
  * allow precise positioning when processing MathML.  This is in its
  * own header file because some very-widely-included headers need it
  * but not the rest of nsFontMetrics, or vice versa.
  */
 
 struct nsBoundingMetrics {
@@ -71,16 +72,16 @@ struct nsBoundingMetrics {
             ascent = bm.ascent;
             descent = bm.descent;
             leftBearing = width + bm.leftBearing;
             rightBearing = width + bm.rightBearing;
         }
         else {
             if (ascent < bm.ascent) ascent = bm.ascent;
             if (descent < bm.descent) descent = bm.descent;
-            leftBearing = NS_MIN(leftBearing, width + bm.leftBearing);
-            rightBearing = NS_MAX(rightBearing, width + bm.rightBearing);
+            leftBearing = std::min(leftBearing, width + bm.leftBearing);
+            rightBearing = std::max(rightBearing, width + bm.rightBearing);
         }
         width += bm.width;
     }
 };
 
 #endif // __nsBoundingMetrics_h
--- a/gfx/src/nsCoord.h
+++ b/gfx/src/nsCoord.h
@@ -8,16 +8,17 @@
 
 #include "nsAlgorithm.h"
 #include "nscore.h"
 #include "nsMathUtils.h"
 #include <math.h>
 #include <float.h>
 
 #include "nsDebug.h"
+#include <algorithm>
 
 /*
  * Basic type used for the geometry classes.
  *
  * Normally all coordinates are maintained in an app unit coordinate
  * space. An app unit is 1/60th of a CSS device pixel, which is, in turn
  * an integer number of device pixels, such at the CSS DPI is as close to
  * 96dpi as possible.
@@ -114,18 +115,18 @@ inline nscoord _nscoordSaturatingMultipl
                     ? aCoord > 0
                     : (aCoord > 0) == (aScale > 0))
                    ? floorf(aCoord * aScale) < nscoord_MAX
                    : ceilf(aCoord * aScale) > nscoord_MIN,
                    "nscoord multiplication capped");
 
   float product = aCoord * aScale;
   if (requireNotNegative ? aCoord > 0 : (aCoord > 0) == (aScale > 0))
-    return NSToCoordRoundWithClamp(NS_MIN<float>(nscoord_MAX, product));
-  return NSToCoordRoundWithClamp(NS_MAX<float>(nscoord_MIN, product));
+    return NSToCoordRoundWithClamp(std::min<float>(nscoord_MAX, product));
+  return NSToCoordRoundWithClamp(std::max<float>(nscoord_MIN, product));
 #endif
 }
 
 /**
  * Returns aCoord * aScale, capping the product to nscoord_MAX or nscoord_MIN as
  * appropriate for the sign of aCoord.  This method requires aScale to not be
  * negative; use this method when you know that aScale should never be
  * negative to get a sanity check of that invariant in debug builds.
@@ -167,23 +168,23 @@ NSCoordSaturatingAdd(nscoord a, nscoord 
     // infinity + anything = anything + infinity = infinity
     return nscoord_MAX;
   } else {
     // a + b = a + b
     NS_ASSERTION(a < nscoord_MAX && b < nscoord_MAX,
                  "Doing nscoord addition with values > nscoord_MAX");
     NS_ASSERTION((int64_t)a + (int64_t)b > (int64_t)nscoord_MIN,
                  "nscoord addition will reach or pass nscoord_MIN");
-    // This one's only a warning because the NS_MIN below means that
+    // This one's only a warning because the std::min below means that
     // we'll handle this case correctly.
     NS_WARN_IF_FALSE((int64_t)a + (int64_t)b < (int64_t)nscoord_MAX,
                      "nscoord addition capped to nscoord_MAX");
 
     // Cap the result, just in case we're dealing with numbers near nscoord_MAX
-    return NS_MIN(nscoord_MAX, a + b);
+    return std::min(nscoord_MAX, a + b);
   }
 #endif
 }
 
 /**
  * Returns a - b, gracefully handling cases involving nscoord_MAX.
  * This function assumes that neither argument is nscoord_MIN.
  *
@@ -226,23 +227,23 @@ NSCoordSaturatingSubtract(nscoord a, nsc
       // case (c) for integers
       return nscoord_MAX;
     } else {
       // case (d) for integers
       NS_ASSERTION(a < nscoord_MAX && b < nscoord_MAX,
                    "Doing nscoord subtraction with values > nscoord_MAX");
       NS_ASSERTION((int64_t)a - (int64_t)b > (int64_t)nscoord_MIN,
                    "nscoord subtraction will reach or pass nscoord_MIN");
-      // This one's only a warning because the NS_MIN below means that
+      // This one's only a warning because the std::min below means that
       // we'll handle this case correctly.
       NS_WARN_IF_FALSE((int64_t)a - (int64_t)b < (int64_t)nscoord_MAX,
                        "nscoord subtraction capped to nscoord_MAX");
 
       // Cap the result, in case we're dealing with numbers near nscoord_MAX
-      return NS_MIN(nscoord_MAX, a - b);
+      return std::min(nscoord_MAX, a - b);
     }
   }
 #endif
 }
 
 inline float NSCoordToFloat(nscoord aCoord) {
   VERIFY_COORD(aCoord);
 #ifdef NS_COORD_IS_FLOAT
--- a/gfx/src/nsDeviceContext.cpp
+++ b/gfx/src/nsDeviceContext.cpp
@@ -13,16 +13,17 @@
 #include "mozilla/Services.h"
 #include "mozilla/Preferences.h"
 #include "nsIServiceManager.h"
 #include "nsILanguageAtomService.h"
 #include "nsIObserver.h"
 #include "nsIObserverService.h"
 
 #include "gfxImageSurface.h"
+#include <algorithm>
 
 #if !XP_MACOSX
 #include "gfxPDFSurface.h"
 #endif
 
 #ifdef MOZ_WIDGET_GTK
 #include "gfxPSSurface.h"
 #elif XP_WIN
@@ -326,26 +327,26 @@ nsDeviceContext::SetDPI()
         int32_t prefDPI = Preferences::GetInt("layout.css.dpi", -1);
 
         if (prefDPI > 0) {
             dpi = prefDPI;
         } else if (mWidget) {
             dpi = mWidget->GetDPI();
 
             if (prefDPI < 0) {
-                dpi = NS_MAX(96.0f, dpi);
+                dpi = std::max(96.0f, dpi);
             }
         } else {
             dpi = 96.0f;
         }
 
         double devPixelsPerCSSPixel = mWidget ? mWidget->GetDefaultScale() : 1.0;
 
         mAppUnitsPerDevNotScaledPixel =
-            NS_MAX(1, NS_lround(AppUnitsPerCSSPixel() / devPixelsPerCSSPixel));
+            std::max(1, NS_lround(AppUnitsPerCSSPixel() / devPixelsPerCSSPixel));
     }
 
     NS_ASSERTION(dpi != -1.0, "no dpi set");
 
     mAppUnitsPerPhysicalInch = NS_lround(dpi * mAppUnitsPerDevNotScaledPixel);
     UpdateScaledAppUnits();
 }
 
@@ -713,12 +714,12 @@ nsDeviceContext::SetPixelScale(float aSc
     UpdateScaledAppUnits();
     return oldAppUnitsPerDevPixel != mAppUnitsPerDevPixel;
 }
 
 void
 nsDeviceContext::UpdateScaledAppUnits()
 {
     mAppUnitsPerDevPixel =
-        NS_MAX(1, NSToIntRound(float(mAppUnitsPerDevNotScaledPixel) / mPixelScale));
+        std::max(1, NSToIntRound(float(mAppUnitsPerDevNotScaledPixel) / mPixelScale));
     // adjust mPixelScale to reflect appunit rounding
     mPixelScale = float(mAppUnitsPerDevNotScaledPixel) / mAppUnitsPerDevPixel;
 }
--- a/gfx/src/nsFontMetrics.cpp
+++ b/gfx/src/nsFontMetrics.cpp
@@ -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/. */
 
 #include "nsFontMetrics.h"