Bug 1592992 - Part 12: Replace js::Min/Max with std::min/max. r=jonco
authorAndré Bargull <andre.bargull@gmail.com>
Fri, 08 Nov 2019 11:06:58 +0000
changeset 501264 879358fd177136a5989b627dd297957065c12105
parent 501263 2df8363a5d34e7972e18d63cec98109979207606
child 501265 6f9ec747d5b61825464b378cec980546aab79805
push id36784
push userrgurzau@mozilla.com
push dateFri, 08 Nov 2019 21:36:09 +0000
treeherdermozilla-central@f414b9e6d857 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersjonco
bugs1592992
milestone72.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1592992 - Part 12: Replace js::Min/Max with std::min/max. r=jonco For the most part another mechanical change, except for two changes: - In gc/Nursery.cpp and vm/DateTime.cpp, the initializer_list variants for std::min/max are used, because the two parameter forms of min/max take const reference parameters. And it's not possible to take the reference of a constexpr variable which wasn't previously explicitly defined. This is just a C++14 limitation and as soon as we compile with C++17, we can revert this change. - builtin/String.cpp was calling `Max(unsignedVar, 0U)` in a few places, which led to compiler warnings, because the result is always `unsignedVar`. Differential Revision: https://phabricator.services.mozilla.com/D51371
js/src/builtin/Array.cpp
js/src/builtin/DataViewObject.cpp
js/src/builtin/JSON.cpp
js/src/builtin/String.cpp
js/src/builtin/TypedObject.cpp
js/src/debugger/Object.cpp
js/src/ds/LifoAlloc.cpp
js/src/ds/LifoAlloc.h
js/src/frontend/BytecodeEmitter.cpp
js/src/gc/FindSCCs.h
js/src/gc/GC.cpp
js/src/gc/Marking.cpp
js/src/gc/Nursery.cpp
js/src/gc/Scheduling.cpp
js/src/gc/Statistics.cpp
js/src/gc/StoreBuffer.h
js/src/gc/Verifier.h
js/src/jit/BacktrackingAllocator.cpp
js/src/jit/BaselineFrame.cpp
js/src/jit/BaselineFrame.h
js/src/jit/BaselineFrameInfo.cpp
js/src/jit/BaselineJIT.cpp
js/src/jit/CompileInfo.h
js/src/jit/IonAnalysis.cpp
js/src/jit/IonBuilder.cpp
js/src/jit/IonCacheIRCompiler.cpp
js/src/jit/JitAllocPolicy.h
js/src/jit/JitFrames.cpp
js/src/jit/MIR.h
js/src/jit/MacroAssembler.cpp
js/src/jit/RangeAnalysis.cpp
js/src/jit/RangeAnalysis.h
js/src/jit/RematerializedFrame.cpp
js/src/jit/arm/Assembler-arm.h
js/src/jit/shared/IonAssemblerBuffer.h
js/src/jit/x86-shared/Assembler-x86-shared.cpp
js/src/jsapi.cpp
js/src/jsdate.cpp
js/src/jsutil.h
js/src/shell/js.cpp
js/src/shell/jsoptparse.cpp
js/src/util/StringBuffer.cpp
js/src/util/Text.h
js/src/vm/ArgumentsObject.cpp
js/src/vm/ArgumentsObject.h
js/src/vm/ArrayBufferObject.cpp
js/src/vm/DateTime.cpp
js/src/vm/HelperThreads.cpp
js/src/vm/JSFunction.cpp
js/src/vm/JSScript.cpp
js/src/vm/MemoryMetrics.cpp
js/src/vm/NativeObject.cpp
js/src/vm/NativeObject.h
js/src/vm/RegExpObject.cpp
js/src/vm/RegExpObject.h
js/src/vm/Shape.h
js/src/vm/Stack.cpp
js/src/vm/Stack.h
js/src/vm/StructuredClone.cpp
js/src/vm/Time.cpp
js/src/vm/TypeInference.cpp
js/src/vm/TypedArrayObject-inl.h
js/src/wasm/AsmJS.cpp
js/src/wasm/WasmBaselineCompile.cpp
js/src/wasm/WasmCode.cpp
js/src/wasm/WasmCompile.cpp
js/src/wasm/WasmGenerator.cpp
js/src/wasm/WasmInstance.cpp
js/src/wasm/WasmIonCompile.cpp
js/src/wasm/WasmJS.cpp
js/src/wasm/WasmStubs.cpp
--- a/js/src/builtin/Array.cpp
+++ b/js/src/builtin/Array.cpp
@@ -165,17 +165,17 @@ static bool ToLength(JSContext* cx, Hand
       return false;
     }
   }
 
   d = JS::ToInteger(d);
   if (d <= 0.0) {
     *out = 0;
   } else {
-    *out = uint64_t(Min(d, DOUBLE_INTEGRAL_PRECISION_LIMIT - 1));
+    *out = uint64_t(std::min(d, DOUBLE_INTEGRAL_PRECISION_LIMIT - 1));
   }
   return true;
 }
 
 static MOZ_ALWAYS_INLINE bool GetLengthProperty(JSContext* cx, HandleObject obj,
                                                 uint64_t* lengthp) {
   if (obj->is<ArrayObject>()) {
     *lengthp = obj->as<ArrayObject>().length();
@@ -579,18 +579,18 @@ static bool DeletePropertyOrThrow(JSCont
 }
 
 static bool DeletePropertiesOrThrow(JSContext* cx, HandleObject obj,
                                     uint64_t len, uint64_t finalLength) {
   if (obj->is<ArrayObject>() && !obj->as<NativeObject>().isIndexed() &&
       !obj->as<NativeObject>().denseElementsAreSealed()) {
     if (len <= UINT32_MAX) {
       // Skip forward to the initialized elements of this array.
-      len = Min(uint32_t(len),
-                obj->as<ArrayObject>().getDenseInitializedLength());
+      len = std::min(uint32_t(len),
+                     obj->as<ArrayObject>().getDenseInitializedLength());
     }
   }
 
   for (uint64_t k = len; k > finalLength; k--) {
     if (!CheckForInterrupt(cx)) {
       return false;
     }
 
@@ -956,17 +956,17 @@ bool js::ArraySetLength(JSContext* cx, H
 
   // All operations past here until the |!succeeded| code must be infallible,
   // so that all element fields remain properly synchronized.
 
   // Trim the initialized length, if needed, to preserve the <= length
   // invariant.  (Capacity was already reduced during element deletion, if
   // necessary.)
   ObjectElements* header = arr->getElementsHeader();
-  header->initializedLength = Min(header->initializedLength, newLen);
+  header->initializedLength = std::min(header->initializedLength, newLen);
 
   if (!arr->isExtensible()) {
     arr->shrinkCapacityToInitializedLength(cx);
   }
 
   if (attrs & JSPROP_READONLY) {
     arr->setNonWritableLength(cx);
   }
@@ -1276,17 +1276,18 @@ struct StringSeparatorOp {
 template <typename SeparatorOp>
 static bool ArrayJoinDenseKernel(JSContext* cx, SeparatorOp sepOp,
                                  HandleNativeObject obj, uint64_t length,
                                  StringBuffer& sb, uint32_t* numProcessed) {
   // This loop handles all elements up to initializedLength. If
   // length > initLength we rely on the second loop to add the
   // other elements.
   MOZ_ASSERT(*numProcessed == 0);
-  uint64_t initLength = Min<uint64_t>(obj->getDenseInitializedLength(), length);
+  uint64_t initLength =
+      std::min<uint64_t>(obj->getDenseInitializedLength(), length);
   MOZ_ASSERT(initLength <= UINT32_MAX,
              "initialized length shouldn't exceed UINT32_MAX");
   uint32_t initLengthClamped = uint32_t(initLength);
   while (*numProcessed < initLengthClamped) {
     if (!CheckForInterrupt(cx)) {
       return false;
     }
 
@@ -2833,17 +2834,17 @@ static bool CanOptimizeForDenseStorage(H
 static ArrayObject* CopyDenseArrayElements(JSContext* cx,
                                            HandleNativeObject obj,
                                            uint32_t begin, uint32_t count) {
   size_t initlen = obj->getDenseInitializedLength();
   MOZ_ASSERT(initlen <= UINT32_MAX,
              "initialized length shouldn't exceed UINT32_MAX");
   uint32_t newlength = 0;
   if (initlen > begin) {
-    newlength = Min<uint32_t>(initlen - begin, count);
+    newlength = std::min<uint32_t>(initlen - begin, count);
   }
 
   ArrayObject* narr = NewFullyAllocatedArrayTryReuseGroup(cx, obj, newlength);
   if (!narr) {
     return nullptr;
   }
 
   MOZ_ASSERT(count >= narr->length());
@@ -2861,17 +2862,17 @@ static bool CopyArrayElements(JSContext*
   MOZ_ASSERT(result->length() == count);
 
   uint64_t startIndex = 0;
   RootedValue value(cx);
 
   // Use dense storage for new indexed properties where possible.
   {
     uint32_t index = 0;
-    uint32_t limit = Min<uint32_t>(count, JSID_INT_MAX);
+    uint32_t limit = std::min<uint32_t>(count, JSID_INT_MAX);
     for (; index < limit; index++) {
       bool hole;
       if (!CheckForInterrupt(cx) ||
           !HasAndGetElement(cx, obj, begin + index, &hole, &value)) {
         return false;
       }
 
       if (!hole) {
@@ -2932,19 +2933,19 @@ static bool array_splice_impl(JSContext*
   double relativeStart;
   if (!ToInteger(cx, args.get(0), &relativeStart)) {
     return false;
   }
 
   /* Step 4. */
   uint64_t actualStart;
   if (relativeStart < 0) {
-    actualStart = Max(len + relativeStart, 0.0);
+    actualStart = std::max(len + relativeStart, 0.0);
   } else {
-    actualStart = Min(relativeStart, double(len));
+    actualStart = std::min(relativeStart, double(len));
   }
 
   /* Step 5. */
   uint64_t actualDeleteCount;
   if (args.length() == 0) {
     /* Step 5.b. */
     actualDeleteCount = 0;
   } else if (args.length() == 1) {
@@ -2954,17 +2955,17 @@ static bool array_splice_impl(JSContext*
     /* Steps 7.b. */
     double deleteCountDouble;
     if (!ToInteger(cx, args[1], &deleteCountDouble)) {
       return false;
     }
 
     /* Step 7.c. */
     actualDeleteCount =
-        Min(Max(deleteCountDouble, 0.0), double(len - actualStart));
+        std::min(std::max(deleteCountDouble, 0.0), double(len - actualStart));
 
     /* Step 8. */
     uint32_t insertCount = args.length() - 2;
     if (len + insertCount - actualDeleteCount >=
         DOUBLE_INTEGRAL_PRECISION_LIMIT) {
       JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                 JSMSG_TOO_LONG_ARRAY);
       return false;
@@ -3611,17 +3612,17 @@ static bool ArraySliceDenseKernel(JSCont
 
   if (begin > end) {
     begin = end;
   }
 
   uint32_t count = end - begin;
   size_t initlen = arr->getDenseInitializedLength();
   if (initlen > begin) {
-    uint32_t newlength = Min<uint32_t>(initlen - begin, count);
+    uint32_t newlength = std::min<uint32_t>(initlen - begin, count);
     if (newlength > 0) {
       if (!result->ensureElements(cx, newlength)) {
         return false;
       }
       result->initDenseElements(arr, begin, newlength);
     }
   }
 
--- a/js/src/builtin/DataViewObject.cpp
+++ b/js/src/builtin/DataViewObject.cpp
@@ -6,16 +6,17 @@
 
 #include "builtin/DataViewObject.h"
 
 #include "mozilla/Alignment.h"
 #include "mozilla/Casting.h"
 #include "mozilla/EndianUtils.h"
 #include "mozilla/WrappingOperations.h"
 
+#include <algorithm>
 #include <string.h>
 #include <type_traits>
 
 #include "jsapi.h"
 #include "jsnum.h"
 
 #include "builtin/Array.h"
 #include "jit/AtomicOperations.h"
@@ -347,31 +348,32 @@ static inline void Memcpy(SharedMem<uint
                           size_t nbytes) {
   jit::AtomicOperations::memcpySafeWhenRacy(dest, src, nbytes);
 }
 
 template <typename DataType, typename BufferPtrType>
 struct DataViewIO {
   typedef typename DataToRepType<DataType>::result ReadWriteType;
 
+  static constexpr auto alignMask =
+      std::min<size_t>(MOZ_ALIGNOF(void*), sizeof(DataType)) - 1;
+
   static void fromBuffer(DataType* dest, BufferPtrType unalignedBuffer,
                          bool wantSwap) {
-    MOZ_ASSERT((reinterpret_cast<uintptr_t>(dest) &
-                (Min<size_t>(MOZ_ALIGNOF(void*), sizeof(DataType)) - 1)) == 0);
+    MOZ_ASSERT((reinterpret_cast<uintptr_t>(dest) & alignMask) == 0);
     Memcpy((uint8_t*)dest, unalignedBuffer, sizeof(ReadWriteType));
     if (wantSwap) {
       ReadWriteType* rwDest = reinterpret_cast<ReadWriteType*>(dest);
       *rwDest = swapBytes(*rwDest);
     }
   }
 
   static void toBuffer(BufferPtrType unalignedBuffer, const DataType* src,
                        bool wantSwap) {
-    MOZ_ASSERT((reinterpret_cast<uintptr_t>(src) &
-                (Min<size_t>(MOZ_ALIGNOF(void*), sizeof(DataType)) - 1)) == 0);
+    MOZ_ASSERT((reinterpret_cast<uintptr_t>(src) & alignMask) == 0);
     ReadWriteType temp = *reinterpret_cast<const ReadWriteType*>(src);
     if (wantSwap) {
       temp = swapBytes(temp);
     }
     Memcpy(unalignedBuffer, (uint8_t*)&temp, sizeof(ReadWriteType));
   }
 };
 
--- a/js/src/builtin/JSON.cpp
+++ b/js/src/builtin/JSON.cpp
@@ -6,16 +6,18 @@
 
 #include "builtin/JSON.h"
 
 #include "mozilla/CheckedInt.h"
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/Range.h"
 #include "mozilla/ScopeExit.h"
 
+#include <algorithm>
+
 #include "jsnum.h"
 #include "jstypes.h"
 #include "jsutil.h"
 
 #include "builtin/Array.h"
 #include "builtin/BigInt.h"
 #include "js/PropertySpec.h"
 #include "js/StableStringChars.h"
@@ -748,17 +750,17 @@ bool js::Stringify(JSContext* cx, Mutabl
       }
 
       // Cap the initial size to a moderately small value.  This avoids
       // ridiculous over-allocation if an array with bogusly-huge length
       // is passed in.  If we end up having to add elements past this
       // size, the set will naturally resize to accommodate them.
       const uint32_t MaxInitialSize = 32;
       Rooted<GCHashSet<jsid>> idSet(
-          cx, GCHashSet<jsid>(cx, Min(len, MaxInitialSize)));
+          cx, GCHashSet<jsid>(cx, std::min(len, MaxInitialSize)));
 
       /* Step 4b(iii)(4). */
       uint32_t k = 0;
 
       /* Step 4b(iii)(5). */
       RootedValue item(cx);
       for (; k < len; k++) {
         if (!CheckForInterrupt(cx)) {
@@ -826,27 +828,27 @@ bool js::Stringify(JSContext* cx, Mutabl
   }
 
   StringBuffer gap(cx);
 
   if (space.isNumber()) {
     /* Step 6. */
     double d;
     MOZ_ALWAYS_TRUE(ToInteger(cx, space, &d));
-    d = Min(10.0, d);
+    d = std::min(10.0, d);
     if (d >= 1 && !gap.appendN(' ', uint32_t(d))) {
       return false;
     }
   } else if (space.isString()) {
     /* Step 7. */
     JSLinearString* str = space.toString()->ensureLinear(cx);
     if (!str) {
       return false;
     }
-    size_t len = Min(size_t(10), str->length());
+    size_t len = std::min(size_t(10), str->length());
     if (!gap.appendSubstring(str, 0, len)) {
       return false;
     }
   } else {
     /* Step 8. */
     MOZ_ASSERT(gap.empty());
   }
 
--- a/js/src/builtin/String.cpp
+++ b/js/src/builtin/String.cpp
@@ -11,16 +11,17 @@
 #include "mozilla/CheckedInt.h"
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/PodOperations.h"
 #include "mozilla/Range.h"
 #include "mozilla/TextUtils.h"
 #include "mozilla/TypeTraits.h"
 #include "mozilla/Unused.h"
 
+#include <algorithm>
 #include <limits>
 #include <string.h>
 #include <type_traits>
 
 #include "jsapi.h"
 #include "jsnum.h"
 #include "jstypes.h"
 #include "jsutil.h"
@@ -952,17 +953,17 @@ bool js::intl_toLocaleLowerCase(JSContex
   // Note: maximum case mapping length is three characters, so the result
   // length might be > INT32_MAX. ICU will fail in this case.
   static_assert(JSString::MAX_LENGTH <= INT32_MAX,
                 "String length must fit in int32_t for ICU");
 
   static const size_t INLINE_CAPACITY = js::intl::INITIAL_CHAR_BUFFER_SIZE;
 
   Vector<char16_t, INLINE_CAPACITY> chars(cx);
-  if (!chars.resize(Max(INLINE_CAPACITY, input.length()))) {
+  if (!chars.resize(std::max(INLINE_CAPACITY, input.length()))) {
     return false;
   }
 
   int32_t size = intl::CallICU(
       cx,
       [&input, locale](UChar* chars, int32_t size, UErrorCode* status) {
         return u_strToLower(chars, size, input.begin().get(), input.length(),
                             locale, status);
@@ -1368,17 +1369,17 @@ bool js::intl_toLocaleUpperCase(JSContex
   // Note: maximum case mapping length is three characters, so the result
   // length might be > INT32_MAX. ICU will fail in this case.
   static_assert(JSString::MAX_LENGTH <= INT32_MAX,
                 "String length must fit in int32_t for ICU");
 
   static const size_t INLINE_CAPACITY = js::intl::INITIAL_CHAR_BUFFER_SIZE;
 
   Vector<char16_t, INLINE_CAPACITY> chars(cx);
-  if (!chars.resize(Max(INLINE_CAPACITY, input.length()))) {
+  if (!chars.resize(std::max(INLINE_CAPACITY, input.length()))) {
     return false;
   }
 
   int32_t size = intl::CallICU(
       cx,
       [&input, locale](UChar* chars, int32_t size, UErrorCode* status) {
         return u_strToUpper(chars, size, input.begin().get(), input.length(),
                             locale, status);
@@ -1580,17 +1581,17 @@ static bool str_normalize(JSContext* cx,
     // Step 7.
     args.rval().setString(str);
     return true;
   }
 
   static const size_t INLINE_CAPACITY = js::intl::INITIAL_CHAR_BUFFER_SIZE;
 
   Vector<char16_t, INLINE_CAPACITY> chars(cx);
-  if (!chars.resize(Max(INLINE_CAPACITY, srcChars.length()))) {
+  if (!chars.resize(std::max(INLINE_CAPACITY, srcChars.length()))) {
     return false;
   }
 
   // Copy the already normalized prefix.
   if (spanLength > 0) {
     PodCopy(chars.begin(), srcChars.begin().get(), spanLength);
   }
 
@@ -2214,25 +2215,25 @@ bool js::str_includes(JSContext* cx, uns
     if (args[1].isInt32()) {
       int i = args[1].toInt32();
       pos = (i < 0) ? 0U : uint32_t(i);
     } else {
       double d;
       if (!ToInteger(cx, args[1], &d)) {
         return false;
       }
-      pos = uint32_t(Min(Max(d, 0.0), double(UINT32_MAX)));
+      pos = uint32_t(std::min(std::max(d, 0.0), double(UINT32_MAX)));
     }
   }
 
   // Step 7.
   uint32_t textLen = str->length();
 
   // Step 8.
-  uint32_t start = Min(Max(pos, 0U), textLen);
+  uint32_t start = std::min(pos, textLen);
 
   // Steps 9-10.
   JSLinearString* text = str->ensureLinear(cx);
   if (!text) {
     return false;
   }
 
   args.rval().setBoolean(StringMatch(text, searchStr, start) != -1);
@@ -2261,25 +2262,25 @@ bool js::str_indexOf(JSContext* cx, unsi
     if (args[1].isInt32()) {
       int i = args[1].toInt32();
       pos = (i < 0) ? 0U : uint32_t(i);
     } else {
       double d;
       if (!ToInteger(cx, args[1], &d)) {
         return false;
       }
-      pos = uint32_t(Min(Max(d, 0.0), double(UINT32_MAX)));
+      pos = uint32_t(std::min(std::max(d, 0.0), double(UINT32_MAX)));
     }
   }
 
   // Step 8
   uint32_t textLen = str->length();
 
   // Step 9
-  uint32_t start = Min(Max(pos, 0U), textLen);
+  uint32_t start = std::min(pos, textLen);
 
   if (str == searchStr) {
     // AngularJS often invokes "false".indexOf("false"). This check should
     // be cheap enough to not hurt anything else.
     args.rval().setInt32(start == 0 ? 0 : -1);
     return true;
   }
 
@@ -2447,25 +2448,25 @@ bool js::str_startsWith(JSContext* cx, u
     if (args[1].isInt32()) {
       int i = args[1].toInt32();
       pos = (i < 0) ? 0U : uint32_t(i);
     } else {
       double d;
       if (!ToInteger(cx, args[1], &d)) {
         return false;
       }
-      pos = uint32_t(Min(Max(d, 0.0), double(UINT32_MAX)));
+      pos = uint32_t(std::min(std::max(d, 0.0), double(UINT32_MAX)));
     }
   }
 
   // Step 7.
   uint32_t textLen = str->length();
 
   // Step 8.
-  uint32_t start = Min(Max(pos, 0U), textLen);
+  uint32_t start = std::min(pos, textLen);
 
   // Step 9.
   uint32_t searchLen = searchStr->length();
 
   // Step 10.
   if (searchLen + start < searchLen || searchLen + start > textLen) {
     args.rval().setBoolean(false);
     return true;
@@ -2512,22 +2513,22 @@ bool js::str_endsWith(JSContext* cx, uns
     if (args[1].isInt32()) {
       int i = args[1].toInt32();
       pos = (i < 0) ? 0U : uint32_t(i);
     } else {
       double d;
       if (!ToInteger(cx, args[1], &d)) {
         return false;
       }
-      pos = uint32_t(Min(Max(d, 0.0), double(UINT32_MAX)));
+      pos = uint32_t(std::min(std::max(d, 0.0), double(UINT32_MAX)));
     }
   }
 
   // Step 8.
-  uint32_t end = Min(Max(pos, 0U), textLen);
+  uint32_t end = std::min(pos, textLen);
 
   // Step 9.
   uint32_t searchLen = searchStr->length();
 
   // Step 11 (reordered).
   if (searchLen > end) {
     args.rval().setBoolean(false);
     return true;
--- a/js/src/builtin/TypedObject.cpp
+++ b/js/src/builtin/TypedObject.cpp
@@ -4,16 +4,18 @@
  * 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 "builtin/TypedObject-inl.h"
 
 #include "mozilla/Casting.h"
 #include "mozilla/CheckedInt.h"
 
+#include <algorithm>
+
 #include "jsutil.h"
 
 #include "gc/Marking.h"
 #include "js/CharacterEncoding.h"
 #include "js/PropertySpec.h"
 #include "js/Vector.h"
 #include "util/StringBuffer.h"
 #include "vm/GlobalObject.h"
@@ -778,17 +780,17 @@ const JSFunctionSpec StructMetaTypeDescr
 
 const JSPropertySpec StructMetaTypeDescr::typedObjectProperties[] = {JS_PS_END};
 
 const JSFunctionSpec StructMetaTypeDescr::typedObjectMethods[] = {JS_FS_END};
 
 CheckedInt32 StructMetaTypeDescr::Layout::addField(int32_t fieldAlignment,
                                                    int32_t fieldSize) {
   // Alignment of the struct is the max of the alignment of its fields.
-  structAlignment = js::Max(structAlignment, fieldAlignment);
+  structAlignment = std::max(structAlignment, fieldAlignment);
 
   // Align the pointer.
   CheckedInt32 offset = RoundUpToAlignment(sizeSoFar, fieldAlignment);
   if (!offset.isValid()) {
     return offset;
   }
 
   // Allocate space.
--- a/js/src/debugger/Object.cpp
+++ b/js/src/debugger/Object.cpp
@@ -6,16 +6,17 @@
 
 #include "debugger/Object-inl.h"
 
 #include "mozilla/Maybe.h"   // for Maybe, Nothing, Some
 #include "mozilla/Range.h"   // for Range
 #include "mozilla/Result.h"  // for Result
 #include "mozilla/Vector.h"  // for Vector
 
+#include <algorithm>
 #include <string.h>     // for size_t, strlen
 #include <type_traits>  // for remove_reference<>::type
 #include <utility>      // for move
 
 #include "jsapi.h"        // for CallArgs, RootedObject, Rooted
 #include "jsfriendapi.h"  // for GetErrorMessage
 #include "jsutil.h"       // for Min
 
@@ -978,17 +979,17 @@ bool DebuggerObject::CallData::applyMeth
     }
 
     RootedObject argsobj(cx, &args[1].toObject());
 
     unsigned argc = 0;
     if (!GetLengthProperty(cx, argsobj, &argc)) {
       return false;
     }
-    argc = unsigned(Min(argc, ARGS_LENGTH_MAX));
+    argc = unsigned(std::min(argc, ARGS_LENGTH_MAX));
 
     if (!nargs.growBy(argc) || !GetElements(cx, argsobj, argc, nargs.begin())) {
       return false;
     }
   }
 
   Rooted<Maybe<Completion>> completion(
       cx, DebuggerObject::call(cx, object, thisv, nargs));
--- a/js/src/ds/LifoAlloc.cpp
+++ b/js/src/ds/LifoAlloc.cpp
@@ -4,16 +4,18 @@
  * 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 "ds/LifoAlloc.h"
 
 #include "mozilla/Likely.h"
 #include "mozilla/MathAlgorithms.h"
 
+#include <algorithm>
+
 #include "ds/MemoryProtectionExceptionHandler.h"
 
 #ifdef LIFO_CHUNK_PROTECT
 #  include "gc/Memory.h"
 #endif
 
 using namespace js;
 
@@ -151,17 +153,17 @@ static size_t MallocGoodSize(size_t aSiz
 
 // Heuristic to choose the size of the next BumpChunk for small allocations.
 // `start` is the size of the first chunk. `used` is the total size of all
 // BumpChunks in this LifoAlloc so far.
 static size_t NextSize(size_t start, size_t used) {
   // Double the size, up to 1 MB.
   const size_t mb = 1 * 1024 * 1024;
   if (used < mb) {
-    return Max(start, used);
+    return std::max(start, used);
   }
 
   // After 1 MB, grow more gradually, to waste less memory.
   // The sequence (in megabytes) begins:
   // 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, ...
   return RoundUp(used / 8, mb);
 }
 
@@ -355,17 +357,17 @@ void LifoAlloc::steal(LifoAlloc* other) 
   // requires some care.
   chunks_ = std::move(other->chunks_);
   oversize_ = std::move(other->oversize_);
   unused_ = std::move(other->unused_);
   markCount = other->markCount;
   defaultChunkSize_ = other->defaultChunkSize_;
   oversizeThreshold_ = other->oversizeThreshold_;
   curSize_ = other->curSize_;
-  peakSize_ = Max(peakSize_, other->peakSize_);
+  peakSize_ = std::max(peakSize_, other->peakSize_);
   smallAllocsSize_ = other->smallAllocsSize_;
 #if defined(DEBUG) || defined(JS_OOM_BREAKPOINT)
   fallibleScope_ = other->fallibleScope_;
 #endif
 
   other->reset(defaultChunkSize_);
 }
 
--- a/js/src/ds/LifoAlloc.h
+++ b/js/src/ds/LifoAlloc.h
@@ -11,16 +11,17 @@
 #include "mozilla/MathAlgorithms.h"
 #include "mozilla/MemoryChecking.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/Move.h"
 #include "mozilla/PodOperations.h"
 #include "mozilla/TemplateLib.h"
 #include "mozilla/TypeTraits.h"
 
+#include <algorithm>
 #include <new>
 #include <stddef.h>  // size_t
 
 // This data structure supports stacky LIFO allocation (mark/release and
 // LifoAllocScope). It does not maintain one contiguous segment; instead, it
 // maintains a bunch of linked memory segments. In order to prevent malloc/free
 // thrashing, unused segments are deallocated when garbage collection occurs.
 
@@ -1021,17 +1022,17 @@ class LifoAllocPolicy {
   }
   template <typename T>
   T* maybe_pod_realloc(T* p, size_t oldSize, size_t newSize) {
     T* n = maybe_pod_malloc<T>(newSize);
     if (MOZ_UNLIKELY(!n)) {
       return nullptr;
     }
     MOZ_ASSERT(!(oldSize & mozilla::tl::MulOverflowMask<sizeof(T)>::value));
-    memcpy(n, p, Min(oldSize * sizeof(T), newSize * sizeof(T)));
+    memcpy(n, p, std::min(oldSize * sizeof(T), newSize * sizeof(T)));
     return n;
   }
   template <typename T>
   T* pod_malloc(size_t numElems) {
     return maybe_pod_malloc<T>(numElems);
   }
   template <typename T>
   T* pod_calloc(size_t numElems) {
--- a/js/src/frontend/BytecodeEmitter.cpp
+++ b/js/src/frontend/BytecodeEmitter.cpp
@@ -15,16 +15,17 @@
 #include "mozilla/DebugOnly.h"   // mozilla::DebugOnly
 #include "mozilla/FloatingPoint.h"  // mozilla::NumberEqualsInt32, mozilla::NumberIsInt32
 #include "mozilla/Maybe.h"          // mozilla::{Maybe,Nothing,Some}
 #include "mozilla/PodOperations.h"  // mozilla::PodCopy
 #include "mozilla/Sprintf.h"        // SprintfLiteral
 #include "mozilla/Unused.h"         // mozilla::Unused
 #include "mozilla/Variant.h"        // mozilla::AsVariant
 
+#include <algorithm>
 #include <string.h>
 
 #include "jsnum.h"    // NumberToAtom
 #include "jstypes.h"  // JS_BIT
 #include "jsutil.h"   // Min
 
 #include "ds/Nestable.h"                         // Nestable
 #include "frontend/BytecodeControlStructures.h"  // NestableControl, BreakableControl, LabelControl, LoopControl, TryFinallyControl
@@ -9699,17 +9700,17 @@ bool BytecodeEmitter::newSrcNote(SrcNote
    * Compute delta from the last annotated bytecode's offset.  If it's too
    * big to fit in sn, allocate one or more xdelta notes and reset sn.
    */
   BytecodeOffset offset = bytecodeSection().offset();
   ptrdiff_t delta = (offset - bytecodeSection().lastNoteOffset()).value();
   bytecodeSection().setLastNoteOffset(offset);
   if (delta >= SN_DELTA_LIMIT) {
     do {
-      ptrdiff_t xdelta = Min(delta, SN_XDELTA_MASK);
+      ptrdiff_t xdelta = std::min(delta, SN_XDELTA_MASK);
       SN_MAKE_XDELTA(&notes[index], xdelta);
       delta -= xdelta;
       if (!AllocSrcNote(cx, notes, &index)) {
         return false;
       }
     } while (delta >= SN_DELTA_LIMIT);
   }
 
--- a/js/src/gc/FindSCCs.h
+++ b/js/src/gc/FindSCCs.h
@@ -4,16 +4,18 @@
  * 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 gc_FindSCCs_h
 #define gc_FindSCCs_h
 
 #include "mozilla/Move.h"
 
+#include <algorithm>
+
 #include "jsfriendapi.h"
 #include "jsutil.h"
 
 #include "js/HashTable.h"
 
 namespace js {
 namespace gc {
 
@@ -124,19 +126,19 @@ class ComponentFinder {
 
   // Constant used to indicate a processed vertex that is no longer on the
   // stack.
   static const unsigned Finished = (unsigned)-1;
 
   void addEdgeTo(Node* w) {
     if (w->gcDiscoveryTime == Undefined) {
       processNode(w);
-      cur->gcLowLink = Min(cur->gcLowLink, w->gcLowLink);
+      cur->gcLowLink = std::min(cur->gcLowLink, w->gcLowLink);
     } else if (w->gcDiscoveryTime != Finished) {
-      cur->gcLowLink = Min(cur->gcLowLink, w->gcDiscoveryTime);
+      cur->gcLowLink = std::min(cur->gcLowLink, w->gcDiscoveryTime);
     }
   }
 
   void processNode(Node* v) {
     v->gcDiscoveryTime = clock;
     v->gcLowLink = clock;
     ++clock;
 
--- a/js/src/gc/GC.cpp
+++ b/js/src/gc/GC.cpp
@@ -196,16 +196,17 @@
 #include "mozilla/Move.h"
 #include "mozilla/Range.h"
 #include "mozilla/ScopeExit.h"
 #include "mozilla/TextUtils.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/TypeTraits.h"
 #include "mozilla/Unused.h"
 
+#include <algorithm>
 #include <initializer_list>
 #include <string.h>
 #ifndef XP_WIN
 #  include <sys/mman.h>
 #  include <unistd.h>
 #endif
 
 #include "jsapi.h"
@@ -2291,18 +2292,18 @@ static const size_t MinCellUpdateBackgro
 static const size_t MaxCellUpdateBackgroundTasks = 8;
 
 static size_t CellUpdateBackgroundTaskCount() {
   if (!CanUseExtraThreads()) {
     return 0;
   }
 
   size_t targetTaskCount = HelperThreadState().cpuCount / 2;
-  return Min(Max(targetTaskCount, MinCellUpdateBackgroundTasks),
-             MaxCellUpdateBackgroundTasks);
+  return std::min(std::max(targetTaskCount, MinCellUpdateBackgroundTasks),
+                  MaxCellUpdateBackgroundTasks);
 }
 
 static bool CanUpdateKindInBackground(AllocKind kind) {
   // We try to update as many GC things in parallel as we can, but there are
   // kinds for which this might not be safe:
   //  - we assume JSObjects that are foreground finalized are not safe to
   //    update in parallel
   //  - updating a shape touches child shapes in fixupShapeTreeAfterMovingGC()
@@ -5905,17 +5906,17 @@ class IncrementalSweepWeakCacheTask
     } while (item_.cache);
   }
 };
 
 static const size_t MaxWeakCacheSweepTasks = 8;
 
 static size_t WeakCacheSweepTaskCount() {
   size_t targetTaskCount = HelperThreadState().cpuCount;
-  return Min(targetTaskCount, MaxWeakCacheSweepTasks);
+  return std::min(targetTaskCount, MaxWeakCacheSweepTasks);
 }
 
 IncrementalProgress GCRuntime::sweepWeakCaches(JSFreeOp* fop,
                                                SliceBudget& budget) {
   WeakCacheSweepIterator work(this);
 
   {
     AutoLockHelperThreadState lock;
--- a/js/src/gc/Marking.cpp
+++ b/js/src/gc/Marking.cpp
@@ -8,16 +8,18 @@
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/IntegerRange.h"
 #include "mozilla/ReentrancyGuard.h"
 #include "mozilla/ScopeExit.h"
 #include "mozilla/TypeTraits.h"
 
+#include <algorithm>
+
 #include "jsfriendapi.h"
 
 #include "builtin/ModuleObject.h"
 #include "debugger/DebugAPI.h"
 #include "gc/GCInternals.h"
 #include "gc/Policy.h"
 #include "jit/IonCode.h"
 #include "js/SliceBudget.h"
@@ -1975,17 +1977,17 @@ MarkStack::SavedValueArray GCMarker::sav
     index = obj->unshiftedIndex(array.start - vp);
     kind = HeapSlot::Element;
   } else {
     HeapSlot* vp = obj->fixedSlots();
     unsigned nfixed = obj->numFixedSlots();
     if (array.start == array.end) {
       index = obj->slotSpan();
     } else if (array.start >= vp && array.start < vp + nfixed) {
-      MOZ_ASSERT(array.end == vp + Min(nfixed, obj->slotSpan()));
+      MOZ_ASSERT(array.end == vp + std::min(nfixed, obj->slotSpan()));
       index = array.start - vp;
     } else {
       MOZ_ASSERT(array.start >= obj->slots_ &&
                  array.end == obj->slots_ + obj->slotSpan() - nfixed);
       index = (array.start - obj->slots_) + nfixed;
     }
     kind = HeapSlot::Slot;
   }
@@ -2019,17 +2021,17 @@ MarkStack::ValueArray GCMarker::restoreV
   } else {
     MOZ_ASSERT(savedArray.kind == HeapSlot::Slot);
     HeapSlot* vp = obj->fixedSlots();
     unsigned nfixed = obj->numFixedSlots();
     unsigned nslots = obj->slotSpan();
     if (index < nslots) {
       if (index < nfixed) {
         start = vp + index;
-        end = vp + Min(nfixed, nslots);
+        end = vp + std::min(nfixed, nslots);
       } else {
         start = obj->slots_ + index - nfixed;
         end = obj->slots_ + nslots - nfixed;
       }
     } else {
       /* The object shrunk, in which case no scanning is needed. */
       start = end = vp;
     }
@@ -2308,17 +2310,17 @@ inline bool MarkStack::ensureSpace(size_
   if ((topIndex_ + count) <= capacity()) {
     return !js::oom::ShouldFailWithOOM();
   }
 
   return enlarge(count);
 }
 
 bool MarkStack::enlarge(size_t count) {
-  size_t newCapacity = Min(maxCapacity_.ref(), capacity() * 2);
+  size_t newCapacity = std::min(maxCapacity_.ref(), capacity() * 2);
   if (newCapacity < capacity() + count) {
     return false;
   }
 
   return resize(newCapacity);
 }
 
 bool MarkStack::resize(size_t newCapacity) {
@@ -2876,28 +2878,28 @@ void js::gc::StoreBuffer::SlotsEdge::tra
 
   MOZ_ASSERT(!IsInsideNursery(obj), "obj shouldn't live in nursery.");
 
   if (kind() == ElementKind) {
     uint32_t initLen = obj->getDenseInitializedLength();
     uint32_t numShifted = obj->getElementsHeader()->numShiftedElements();
     uint32_t clampedStart = start_;
     clampedStart = numShifted < clampedStart ? clampedStart - numShifted : 0;
-    clampedStart = Min(clampedStart, initLen);
+    clampedStart = std::min(clampedStart, initLen);
     uint32_t clampedEnd = start_ + count_;
     clampedEnd = numShifted < clampedEnd ? clampedEnd - numShifted : 0;
-    clampedEnd = Min(clampedEnd, initLen);
+    clampedEnd = std::min(clampedEnd, initLen);
     MOZ_ASSERT(clampedStart <= clampedEnd);
     mover.traceSlots(
         static_cast<HeapSlot*>(obj->getDenseElements() + clampedStart)
             ->unsafeUnbarrieredForTracing(),
         clampedEnd - clampedStart);
   } else {
-    uint32_t start = Min(start_, obj->slotSpan());
-    uint32_t end = Min(start_ + count_, obj->slotSpan());
+    uint32_t start = std::min(start_, obj->slotSpan());
+    uint32_t end = std::min(start_ + count_, obj->slotSpan());
     MOZ_ASSERT(start <= end);
     mover.traceObjectSlots(obj, start, end - start);
   }
 }
 
 static inline void TraceWholeCell(TenuringTracer& mover, JSObject* object) {
   mover.traceObject(object);
 }
--- a/js/src/gc/Nursery.cpp
+++ b/js/src/gc/Nursery.cpp
@@ -7,16 +7,18 @@
 
 #include "gc/Nursery-inl.h"
 
 #include "mozilla/DebugOnly.h"
 #include "mozilla/IntegerPrintfMacros.h"
 #include "mozilla/Move.h"
 #include "mozilla/Unused.h"
 
+#include <algorithm>
+
 #include "jsutil.h"
 
 #include "builtin/MapObject.h"
 #include "debugger/DebugAPI.h"
 #include "gc/FreeOp.h"
 #include "gc/GCInternals.h"
 #include "gc/Memory.h"
 #include "gc/PublicIterators.h"
@@ -1297,27 +1299,27 @@ MOZ_ALWAYS_INLINE void js::Nursery::setC
   position_ = chunk(chunkno).start();
   setCurrentEnd();
 }
 
 void js::Nursery::poisonAndInitCurrentChunk(size_t extent) {
   if (gc->hasZealMode(ZealMode::GenerationalGC) || !isSubChunkMode()) {
     chunk(currentChunk_).poisonAndInit(runtime());
   } else {
-    extent = Min(capacity_, extent);
+    extent = std::min(capacity_, extent);
     MOZ_ASSERT(extent <= NurseryChunkUsableSize);
     chunk(currentChunk_).poisonAndInit(runtime(), extent);
   }
 }
 
 MOZ_ALWAYS_INLINE void js::Nursery::setCurrentEnd() {
   MOZ_ASSERT_IF(isSubChunkMode(),
                 currentChunk_ == 0 && currentEnd_ <= chunk(0).end());
-  currentEnd_ =
-      chunk(currentChunk_).start() + Min(capacity_, NurseryChunkUsableSize);
+  currentEnd_ = chunk(currentChunk_).start() +
+                std::min({capacity_, NurseryChunkUsableSize});
   if (canAllocateStrings_) {
     currentStringEnd_ = currentEnd_;
   }
 }
 
 bool js::Nursery::allocateNextChunk(const unsigned chunkno,
                                     AutoLockGCBgAlloc& lock) {
   const unsigned priorCount = allocatedChunkCount();
@@ -1381,19 +1383,19 @@ void js::Nursery::maybeResizeNursery(JS:
   const size_t minNurseryBytes = roundSize(tunables().gcMinNurseryBytes());
   MOZ_ASSERT(minNurseryBytes >= ArenaSize);
   const size_t maxNurseryBytes = roundSize(tunables().gcMaxNurseryBytes());
   MOZ_ASSERT(maxNurseryBytes >= ArenaSize);
 
   // If one of these conditions is true then we always shrink or grow the
   // nursery. This way the thresholds still have an effect even if the goal
   // seeking says the current size is ideal.
-  size_t lowLimit = Max(minNurseryBytes, capacity() / 2);
+  size_t lowLimit = std::max(minNurseryBytes, capacity() / 2);
   size_t highLimit =
-      Min(maxNurseryBytes, (CheckedInt<size_t>(capacity()) * 2).value());
+      std::min(maxNurseryBytes, (CheckedInt<size_t>(capacity()) * 2).value());
   newCapacity = roundSize(mozilla::Clamp(newCapacity, lowLimit, highLimit));
 
   if (capacity() < maxNurseryBytes && promotionRate > GrowThreshold &&
       newCapacity > capacity()) {
     growAllocableSpace(newCapacity);
   } else if (capacity() >= minNurseryBytes + SubChunkStep &&
              promotionRate < ShrinkThreshold && newCapacity < capacity()) {
     shrinkAllocableSpace(newCapacity);
@@ -1438,18 +1440,18 @@ bool js::Nursery::maybeResizeExact(JS::G
 
   return false;
 }
 
 size_t js::Nursery::roundSize(size_t size) {
   if (size >= ChunkSize) {
     size = Round(size, ChunkSize);
   } else {
-    size = Min(Round(size, SubChunkStep),
-               RoundDown(NurseryChunkUsableSize, SubChunkStep));
+    size = std::min(Round(size, SubChunkStep),
+                    RoundDown(NurseryChunkUsableSize, SubChunkStep));
   }
   MOZ_ASSERT(size >= ArenaSize);
   return size;
 }
 
 void js::Nursery::growAllocableSpace(size_t newCapacity) {
   MOZ_ASSERT_IF(!isSubChunkMode(), newCapacity > currentChunk_ * ChunkSize);
   MOZ_ASSERT(newCapacity <= roundSize(tunables().gcMaxNurseryBytes()));
@@ -1457,25 +1459,27 @@ void js::Nursery::growAllocableSpace(siz
 
   if (isSubChunkMode()) {
     // Avoid growing into an area that's about to be decommitted.
     decommitTask.join();
 
     MOZ_ASSERT(currentChunk_ == 0);
 
     // The remainder of the chunk may have been decommitted.
-    if (!chunk(0).markPagesInUseHard(Min(newCapacity, ChunkSize - ArenaSize))) {
+    if (!chunk(0).markPagesInUseHard(
+            std::min(newCapacity, ChunkSize - ArenaSize))) {
       // The OS won't give us the memory we need, we can't grow.
       return;
     }
 
     // The capacity has changed and since we were in sub-chunk mode we need to
     // update the poison values / asan infomation for the now-valid region of
     // this chunk.
-    size_t poisonSize = Min(newCapacity, NurseryChunkUsableSize) - capacity();
+    size_t poisonSize =
+        std::min({newCapacity, NurseryChunkUsableSize}) - capacity();
     // Don't poison the trailer.
     MOZ_ASSERT(capacity() + poisonSize <= NurseryChunkUsableSize);
     chunk(0).poisonRange(capacity(), poisonSize, JS_FRESH_NURSERY_PATTERN,
                          MemCheckKind::MakeUndefined);
   }
 
   capacity_ = newCapacity;
 
@@ -1535,19 +1539,20 @@ void js::Nursery::shrinkAllocableSpace(s
 
   size_t oldCapacity = capacity_;
   capacity_ = newCapacity;
 
   setCurrentEnd();
 
   if (isSubChunkMode()) {
     MOZ_ASSERT(currentChunk_ == 0);
-    chunk(0).poisonRange(newCapacity,
-                         Min(oldCapacity, NurseryChunkUsableSize) - newCapacity,
-                         JS_SWEPT_NURSERY_PATTERN, MemCheckKind::MakeNoAccess);
+    chunk(0).poisonRange(
+        newCapacity,
+        std::min({oldCapacity, NurseryChunkUsableSize}) - newCapacity,
+        JS_SWEPT_NURSERY_PATTERN, MemCheckKind::MakeNoAccess);
 
     AutoLockHelperThreadState lock;
     decommitTask.queueRange(capacity_, chunk(0), lock);
     decommitTask.startOrRunIfIdle(lock);
   }
 }
 
 void js::Nursery::minimizeAllocableSpace() {
--- a/js/src/gc/Scheduling.cpp
+++ b/js/src/gc/Scheduling.cpp
@@ -4,16 +4,18 @@
  * 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 "gc/Scheduling.h"
 
 #include "mozilla/CheckedInt.h"
 #include "mozilla/TimeStamp.h"
 
+#include <algorithm>
+
 #include "gc/RelocationOverlay.h"
 #include "gc/ZoneAllocator.h"
 #include "vm/MutexIDs.h"
 
 using namespace js;
 using namespace js::gc;
 
 using mozilla::CheckedInt;
@@ -27,18 +29,18 @@ using mozilla::TimeDuration;
 static constexpr float HighFrequencyEagerAllocTriggerFactor = 0.85f;
 static constexpr float LowFrequencyEagerAllocTriggerFactor = 0.9f;
 
 /*
  * Don't allow heap growth factors to be set so low that eager collections could
  * reduce the trigger threshold.
  */
 static constexpr float MinHeapGrowthFactor =
-    1.0f / Min(HighFrequencyEagerAllocTriggerFactor,
-               LowFrequencyEagerAllocTriggerFactor);
+    1.0f / std::min(HighFrequencyEagerAllocTriggerFactor,
+                    LowFrequencyEagerAllocTriggerFactor);
 
 GCSchedulingTunables::GCSchedulingTunables()
     : gcMaxBytes_(0),
       gcMinNurseryBytes_(TuningDefaults::GCMinNurseryBytes),
       gcMaxNurseryBytes_(JS::DefaultNurseryMaxBytes),
       gcZoneAllocThresholdBase_(TuningDefaults::GCZoneAllocThresholdBase),
       nonIncrementalFactor_(TuningDefaults::NonIncrementalFactor),
       avoidInterruptFactor_(TuningDefaults::AvoidInterruptFactor),
@@ -409,21 +411,21 @@ float GCHeapThreshold::computeZoneHeapGr
 
 /* static */
 size_t GCHeapThreshold::computeZoneTriggerBytes(
     float growthFactor, size_t lastBytes, JSGCInvocationKind gckind,
     const GCSchedulingTunables& tunables, const AutoLockGC& lock) {
   size_t baseMin = gckind == GC_SHRINK
                        ? tunables.minEmptyChunkCount(lock) * ChunkSize
                        : tunables.gcZoneAllocThresholdBase();
-  size_t base = Max(lastBytes, baseMin);
+  size_t base = std::max(lastBytes, baseMin);
   float trigger = float(base) * growthFactor;
   float triggerMax =
       float(tunables.gcMaxBytes()) / tunables.nonIncrementalFactor();
-  return size_t(Min(triggerMax, trigger));
+  return size_t(std::min(triggerMax, trigger));
 }
 
 void GCHeapThreshold::updateAfterGC(size_t lastBytes, JSGCInvocationKind gckind,
                                     const GCSchedulingTunables& tunables,
                                     const GCSchedulingState& state,
                                     const AutoLockGC& lock) {
   float growthFactor =
       computeZoneHeapGrowthFactorForHeapSize(lastBytes, tunables, state);
@@ -431,17 +433,17 @@ void GCHeapThreshold::updateAfterGC(size
       computeZoneTriggerBytes(growthFactor, lastBytes, gckind, tunables, lock);
 }
 
 /* static */
 size_t MallocHeapThreshold::computeZoneTriggerBytes(float growthFactor,
                                                     size_t lastBytes,
                                                     size_t baseBytes,
                                                     const AutoLockGC& lock) {
-  return size_t(float(Max(lastBytes, baseBytes)) * growthFactor);
+  return size_t(float(std::max(lastBytes, baseBytes)) * growthFactor);
 }
 
 void MallocHeapThreshold::updateAfterGC(size_t lastBytes, size_t baseBytes,
                                         float growthFactor,
                                         const AutoLockGC& lock) {
   bytes_ = computeZoneTriggerBytes(growthFactor, lastBytes, baseBytes, lock);
 }
 
--- a/js/src/gc/Statistics.cpp
+++ b/js/src/gc/Statistics.cpp
@@ -6,16 +6,17 @@
 
 #include "gc/Statistics.h"
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Sprintf.h"
 #include "mozilla/TimeStamp.h"
 
+#include <algorithm>
 #include <stdarg.h>
 #include <stdio.h>
 #include <type_traits>
 
 #include "jsutil.h"
 
 #include "debugger/DebugAPI.h"
 #include "gc/GC.h"
@@ -220,17 +221,17 @@ void Statistics::gcDuration(TimeDuration
   }
 }
 
 void Statistics::sccDurations(TimeDuration* total,
                               TimeDuration* maxPause) const {
   *total = *maxPause = 0;
   for (size_t i = 0; i < sccTimes.length(); i++) {
     *total += sccTimes[i];
-    *maxPause = Max(*maxPause, sccTimes[i]);
+    *maxPause = std::max(*maxPause, sccTimes[i]);
   }
 }
 
 typedef Vector<UniqueChars, 8, SystemAllocPolicy> FragmentVector;
 
 static UniqueChars Join(const FragmentVector& fragments,
                         const char* separator = "") {
   const size_t separatorLength = strlen(separator);
--- a/js/src/gc/StoreBuffer.h
+++ b/js/src/gc/StoreBuffer.h
@@ -350,18 +350,18 @@ class StoreBuffer {
              (start <= otherEnd && otherEnd <= end);
     }
 
     // Destructively make this SlotsEdge range the union of the other
     // SlotsEdge range and this one. A precondition is that the ranges must
     // overlap.
     void merge(const SlotsEdge& other) {
       MOZ_ASSERT(overlaps(other));
-      uint32_t end = Max(start_ + count_, other.start_ + other.count_);
-      start_ = Min(start_, other.start_);
+      uint32_t end = std::max(start_ + count_, other.start_ + other.count_);
+      start_ = std::min(start_, other.start_);
       count_ = end - start_;
     }
 
     bool maybeInRememberedSet(const Nursery& n) const {
       return !IsInsideNursery(reinterpret_cast<Cell*>(object()));
     }
 
     void trace(TenuringTracer& mover) const;
--- a/js/src/gc/Verifier.h
+++ b/js/src/gc/Verifier.h
@@ -6,16 +6,18 @@
 
 /*
  * Internal header for definitions shared between the verifier and jsapi tests.
  */
 
 #ifndef gc_Verifier_h
 #define gc_Verifier_h
 
+#include <algorithm>
+
 #include "gc/Cell.h"
 
 namespace js {
 namespace gc {
 
 // Like gc::MarkColor but allows the possibility of the cell being
 // unmarked.
 enum class CellColor : uint8_t {
@@ -39,25 +41,25 @@ inline CellColor GetCellColor(Cell* cell
     return CellColor::Gray;
   }
 
   return CellColor::White;
 }
 
 inline CellColor ExpectedWeakMapValueColor(CellColor keyColor,
                                            CellColor mapColor) {
-  return Min(keyColor, mapColor);
+  return std::min(keyColor, mapColor);
 }
 
 inline CellColor ExpectedWeakMapKeyColor(CellColor mapColor,
                                          CellColor delegateColor) {
-  return Min(mapColor, delegateColor);
+  return std::min(mapColor, delegateColor);
 }
 
 inline CellColor ExpectedKeyAndDelegateColor(CellColor keyColor,
                                              CellColor delegateColor) {
-  return Max(keyColor, delegateColor);
+  return std::max(keyColor, delegateColor);
 }
 
 }  // namespace gc
 }  // namespace js
 
 #endif /* gc_Verifier_h */
--- a/js/src/jit/BacktrackingAllocator.cpp
+++ b/js/src/jit/BacktrackingAllocator.cpp
@@ -1,16 +1,18 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jit/BacktrackingAllocator.h"
 
+#include <algorithm>
+
 #include "jit/BitSet.h"
 #include "js/Printf.h"
 
 using namespace js;
 using namespace js::jit;
 
 using mozilla::DebugOnly;
 
@@ -2776,17 +2778,17 @@ size_t BacktrackingAllocator::computeSpi
   size_t lifetimeTotal = computePriority(bundle);
   return lifetimeTotal ? usesTotal / lifetimeTotal : 0;
 }
 
 size_t BacktrackingAllocator::maximumSpillWeight(
     const LiveBundleVector& bundles) {
   size_t maxWeight = 0;
   for (size_t i = 0; i < bundles.length(); i++) {
-    maxWeight = Max(maxWeight, computeSpillWeight(bundles[i]));
+    maxWeight = std::max(maxWeight, computeSpillWeight(bundles[i]));
   }
   return maxWeight;
 }
 
 bool BacktrackingAllocator::trySplitAcrossHotcode(LiveBundle* bundle,
                                                   bool* success) {
   // If this bundle has portions that are hot and portions that are cold,
   // split it at the boundaries between hot and cold code.
--- a/js/src/jit/BaselineFrame.cpp
+++ b/js/src/jit/BaselineFrame.cpp
@@ -1,16 +1,18 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jit/BaselineFrame-inl.h"
 
+#include <algorithm>
+
 #include "debugger/DebugAPI.h"
 #include "jit/BaselineJIT.h"
 #include "jit/Ion.h"
 #include "vm/EnvironmentObject.h"
 
 #include "jit/JitFrames-inl.h"
 #include "vm/Stack-inl.h"
 
@@ -28,17 +30,17 @@ static void TraceLocals(BaselineFrame* f
 
 void BaselineFrame::trace(JSTracer* trc, const JSJitFrameIter& frameIterator) {
   replaceCalleeToken(TraceCalleeToken(trc, calleeToken()));
 
   // Trace |this|, actual and formal args.
   if (isFunctionFrame()) {
     TraceRoot(trc, &thisArgument(), "baseline-this");
 
-    unsigned numArgs = js::Max(numActualArgs(), numFormalArgs());
+    unsigned numArgs = std::max(numActualArgs(), numFormalArgs());
     TraceRootRange(trc, numArgs + isConstructing(), argv(), "baseline-args");
   }
 
   // Trace environment chain, if it exists.
   if (envChain_) {
     TraceRoot(trc, &envChain_, "baseline-envchain");
   }
 
--- a/js/src/jit/BaselineFrame.h
+++ b/js/src/jit/BaselineFrame.h
@@ -2,16 +2,18 @@
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef jit_BaselineFrame_h
 #define jit_BaselineFrame_h
 
+#include <algorithm>
+
 #include "jit/JitFrames.h"
 #include "vm/Stack.h"
 
 namespace js {
 namespace jit {
 
 class ICEntry;
 
@@ -200,17 +202,17 @@ class BaselineFrame {
     }
     MOZ_ASSERT(isFunctionFrame());
     if (callee()->isArrow()) {
       return callee()->getExtendedSlot(FunctionExtended::ARROW_NEWTARGET_SLOT);
     }
     if (isConstructing()) {
       return *(Value*)(reinterpret_cast<const uint8_t*>(this) +
                        BaselineFrame::Size() +
-                       offsetOfArg(Max(numFormalArgs(), numActualArgs())));
+                       offsetOfArg(std::max(numFormalArgs(), numActualArgs())));
     }
     return UndefinedValue();
   }
 
   void prepareForBaselineInterpreterToJitOSR() {
     // Clearing the RUNNING_IN_INTERPRETER flag is sufficient, but we also null
     // out the interpreter fields to ensure we don't use stale values.
     flags_ &= ~RUNNING_IN_INTERPRETER;
--- a/js/src/jit/BaselineFrameInfo.cpp
+++ b/js/src/jit/BaselineFrameInfo.cpp
@@ -1,16 +1,18 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jit/BaselineFrameInfo.h"
 
+#include <algorithm>
+
 #include "jit/BaselineIC.h"
 #ifdef DEBUG
 #  include "jit/BytecodeAnalysis.h"
 #endif
 
 #include "jit/BaselineFrameInfo-inl.h"
 #include "jit/MacroAssembler-inl.h"
 
@@ -18,17 +20,18 @@ using namespace js;
 using namespace js::jit;
 
 bool CompilerFrameInfo::init(TempAllocator& alloc) {
   // An extra slot is needed for global scopes because INITGLEXICAL (stack
   // depth 1) is compiled as a SETPROP (stack depth 2) on the global lexical
   // scope.
   size_t extra = script->isGlobalCode() ? 1 : 0;
   size_t nstack =
-      Max(script->nslots() - script->nfixed(), size_t(MinJITStackSize)) + extra;
+      std::max(script->nslots() - script->nfixed(), size_t(MinJITStackSize)) +
+      extra;
   if (!stack.init(alloc, nstack)) {
     return false;
   }
 
   return true;
 }
 
 void CompilerFrameInfo::sync(StackValue* val) {
--- a/js/src/jit/BaselineJIT.cpp
+++ b/js/src/jit/BaselineJIT.cpp
@@ -5,16 +5,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jit/BaselineJIT.h"
 
 #include "mozilla/BinarySearch.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/MemoryReporting.h"
 
+#include <algorithm>
+
 #include "debugger/DebugAPI.h"
 #include "gc/FreeOp.h"
 #include "jit/BaselineCodeGen.h"
 #include "jit/BaselineIC.h"
 #include "jit/CompileInfo.h"
 #include "jit/IonControlFlow.h"
 #include "jit/JitCommon.h"
 #include "jit/JitSpewer.h"
@@ -151,17 +153,17 @@ JitExecStatus jit::EnterBaselineInterpre
   data.osrNumStackValues =
       fp->script()->nfixed() + cx->interpreterRegs().stackDepth();
 
   RootedValue newTarget(cx);
 
   if (fp->isFunctionFrame()) {
     data.constructing = fp->isConstructing();
     data.numActualArgs = fp->numActualArgs();
-    data.maxArgc = Max(fp->numActualArgs(), fp->numFormalArgs()) +
+    data.maxArgc = std::max(fp->numActualArgs(), fp->numFormalArgs()) +
                    1;               // +1 = include |this|
     data.maxArgv = fp->argv() - 1;  // -1 = include |this|
     data.envChain = nullptr;
     data.calleeToken = CalleeToToken(&fp->callee(), data.constructing);
   } else {
     data.constructing = false;
     data.numActualArgs = 0;
     data.maxArgc = 0;
--- a/js/src/jit/CompileInfo.h
+++ b/js/src/jit/CompileInfo.h
@@ -4,16 +4,18 @@
  * 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 jit_CompileInfo_h
 #define jit_CompileInfo_h
 
 #include "mozilla/Maybe.h"
 
+#include <algorithm>
+
 #include "jit/JitAllocPolicy.h"
 #include "jit/JitFrames.h"
 #include "jit/Registers.h"
 #include "vm/EnvironmentObject.h"
 #include "vm/JSFunction.h"
 
 namespace js {
 namespace jit {
@@ -200,19 +202,19 @@ class CompileInfo {
                  + (fun ? 1 : 0);     /* this */
     nargs_ = fun ? fun->nargs() : 0;
     nlocals_ = script->nfixed();
 
     // An extra slot is needed for global scopes because INITGLEXICAL (stack
     // depth 1) is compiled as a SETPROP (stack depth 2) on the global lexical
     // scope.
     uint32_t extra = script->isGlobalCode() ? 1 : 0;
-    nstack_ =
-        Max<unsigned>(script->nslots() - script->nfixed(), MinJITStackSize) +
-        extra;
+    nstack_ = std::max<unsigned>(script->nslots() - script->nfixed(),
+                                 MinJITStackSize) +
+              extra;
     nslots_ = nimplicit_ + nargs_ + nlocals_ + nstack_;
 
     // For derived class constructors, find and cache the frame slot for
     // the .this binding. This slot is assumed to be always
     // observable. See isObservableFrameSlot.
     if (script->isDerivedClassConstructor()) {
       MOZ_ASSERT(script->functionHasThisBinding());
       for (BindingIter bi(script); bi; bi++) {
--- a/js/src/jit/IonAnalysis.cpp
+++ b/js/src/jit/IonAnalysis.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jit/IonAnalysis.h"
 
+#include <algorithm>
 #include <utility>  // for ::std::pair
 
 #include "jit/AliasAnalysis.h"
 #include "jit/BaselineInspector.h"
 #include "jit/BaselineJIT.h"
 #include "jit/Ion.h"
 #include "jit/IonBuilder.h"
 #include "jit/IonOptimizationLevels.h"
@@ -1235,17 +1236,17 @@ bool jit::EliminateDeadResumePointOperan
           continue;
         }
 
         MDefinition* def = consumer->toDefinition();
         if (def->block() != *block || def->isBox() || def->isPhi()) {
           maxDefinition = UINT32_MAX;
           break;
         }
-        maxDefinition = Max(maxDefinition, def->id());
+        maxDefinition = std::max(maxDefinition, def->id());
       }
       if (maxDefinition == UINT32_MAX) {
         continue;
       }
 
       // Walk the uses a second time, removing any in resume points after
       // the last use in a definition.
       for (MUseIterator uses(ins->usesBegin()); uses != ins->usesEnd();) {
@@ -3654,18 +3655,18 @@ static bool TryEliminateBoundsCheck(Boun
       !SafeAdd(sumB.constant, dominated->minimum(), &minimumB) ||
       !SafeAdd(sumB.constant, dominated->maximum(), &maximumB)) {
     return false;
   }
 
   // Update the dominating check to cover both ranges, denormalizing the
   // result per the constant offset in the index.
   int32_t newMinimum, newMaximum;
-  if (!SafeSub(Min(minimumA, minimumB), sumA.constant, &newMinimum) ||
-      !SafeSub(Max(maximumA, maximumB), sumA.constant, &newMaximum)) {
+  if (!SafeSub(std::min(minimumA, minimumB), sumA.constant, &newMinimum) ||
+      !SafeSub(std::max(maximumA, maximumB), sumA.constant, &newMaximum)) {
     return false;
   }
 
   dominating->setMinimum(newMinimum);
   dominating->setMaximum(newMaximum);
   return true;
 }
 
--- a/js/src/jit/IonBuilder.cpp
+++ b/js/src/jit/IonBuilder.cpp
@@ -4,16 +4,18 @@
  * 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 "jit/IonBuilder.h"
 
 #include "mozilla/DebugOnly.h"
 #include "mozilla/ScopeExit.h"
 
+#include <algorithm>
+
 #include "builtin/Eval.h"
 #include "builtin/TypedObject.h"
 #include "frontend/SourceNotes.h"
 #include "jit/BaselineFrame.h"
 #include "jit/BaselineInspector.h"
 #include "jit/CacheIR.h"
 #include "jit/Ion.h"
 #include "jit/IonControlFlow.h"
@@ -1091,17 +1093,17 @@ AbortReasonOr<Ok> IonBuilder::buildInlin
 
   JitSpew(JitSpew_Inlining, "Initializing %u arg slots", info().nargs());
 
   // NB: Ion does not inline functions which |needsArgsObj|.  So using argSlot()
   // instead of argSlotUnchecked() below is OK
   MOZ_ASSERT(!info().needsArgsObj());
 
   // Initialize actually set arguments.
-  uint32_t existing_args = Min<uint32_t>(callInfo.argc(), info().nargs());
+  uint32_t existing_args = std::min<uint32_t>(callInfo.argc(), info().nargs());
   for (size_t i = 0; i < existing_args; ++i) {
     MDefinition* arg = callInfo.getArg(i);
     current->initSlot(info().argSlot(i), arg);
   }
 
   // Pass Undefined for missing arguments
   for (size_t i = callInfo.argc(); i < info().nargs(); ++i) {
     MConstant* arg = MConstant::New(alloc(), UndefinedValue());
@@ -6202,17 +6204,17 @@ bool IonBuilder::testNeedsArgumentCheck(
     return true;
   }
 
   AutoSweepJitScript sweep(targetScript);
   if (!ArgumentTypesMatch(callInfo.thisArg(),
                           jitScript->thisTypes(sweep, targetScript))) {
     return true;
   }
-  uint32_t expected_args = Min<uint32_t>(callInfo.argc(), target->nargs());
+  uint32_t expected_args = std::min<uint32_t>(callInfo.argc(), target->nargs());
   for (size_t i = 0; i < expected_args; i++) {
     if (!ArgumentTypesMatch(callInfo.getArg(i),
                             jitScript->argTypes(sweep, targetScript, i))) {
       return true;
     }
   }
   for (size_t i = callInfo.argc(); i < target->nargs(); i++) {
     StackTypeSet* types = jitScript->argTypes(sweep, targetScript, i);
@@ -6236,17 +6238,17 @@ AbortReasonOr<MCall*> IonBuilder::makeCa
     target = targets.ref()[0];
   }
 
   uint32_t targetArgs = callInfo.argc();
 
   // Collect number of missing arguments provided that the target is
   // scripted. Native functions are passed an explicit 'argc' parameter.
   if (target && !target->isBuiltinNative()) {
-    targetArgs = Max<uint32_t>(target->nargs(), callInfo.argc());
+    targetArgs = std::max<uint32_t>(target->nargs(), callInfo.argc());
   }
 
   bool isDOMCall = false;
   DOMObjectKind objKind = DOMObjectKind::Unknown;
   if (target && !callInfo.constructing()) {
     // We know we have a single call target.  Check whether the "this" types
     // are DOM types and our function a DOM function, and if so flag the
     // MCall accordingly.
--- a/js/src/jit/IonCacheIRCompiler.cpp
+++ b/js/src/jit/IonCacheIRCompiler.cpp
@@ -3,16 +3,18 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jit/IonCacheIRCompiler.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Maybe.h"
 
+#include <algorithm>
+
 #include "jit/BaselineIC.h"
 #include "jit/CacheIRCompiler.h"
 #include "jit/IonIC.h"
 #include "jit/JSJitFrameIter.h"
 #include "jit/Linker.h"
 #include "jit/SharedICHelpers.h"
 #include "jit/VMFunctions.h"
 #include "proxy/DeadObjectProxy.h"
@@ -1875,17 +1877,17 @@ bool IonCacheIRCompiler::emitCallScripte
       masm.framePushed(), FrameType::IonJS, IonICCallFrameLayout::Size());
   pushStubCodePointer();
   masm.Push(Imm32(descriptor));
   masm.Push(ImmPtr(GetReturnAddressToIonCode(cx_)));
 
   // The JitFrameLayout pushed below will be aligned to JitStackAlignment,
   // so we just have to make sure the stack is aligned after we push the
   // |this| + argument Values.
-  size_t numArgs = Max<size_t>(1, target->nargs());
+  size_t numArgs = std::max<size_t>(1, target->nargs());
   uint32_t argSize = (numArgs + 1) * sizeof(Value);
   uint32_t padding =
       ComputeByteAlignment(masm.framePushed() + argSize, JitStackAlignment);
   MOZ_ASSERT(padding % sizeof(uintptr_t) == 0);
   MOZ_ASSERT(padding < JitStackAlignment);
   masm.reserveStack(padding);
 
   for (size_t i = 1; i < target->nargs(); i++) {
--- a/js/src/jit/JitAllocPolicy.h
+++ b/js/src/jit/JitAllocPolicy.h
@@ -7,16 +7,17 @@
 #ifndef jit_JitAllocPolicy_h
 #define jit_JitAllocPolicy_h
 
 #include "mozilla/Attributes.h"
 #include "mozilla/GuardObjects.h"
 #include "mozilla/OperatorNewExtensions.h"
 #include "mozilla/TypeTraits.h"
 
+#include <algorithm>
 #include <utility>
 
 #include "ds/LifoAlloc.h"
 #include "jit/InlineList.h"
 #include "jit/Ion.h"
 #include "vm/JSContext.h"
 
 namespace js {
@@ -94,17 +95,17 @@ class JitAllocPolicy {
   }
   template <typename T>
   T* maybe_pod_realloc(T* p, size_t oldSize, size_t newSize) {
     T* n = pod_malloc<T>(newSize);
     if (MOZ_UNLIKELY(!n)) {
       return n;
     }
     MOZ_ASSERT(!(oldSize & mozilla::tl::MulOverflowMask<sizeof(T)>::value));
-    memcpy(n, p, Min(oldSize * sizeof(T), newSize * sizeof(T)));
+    memcpy(n, p, std::min(oldSize * sizeof(T), newSize * sizeof(T)));
     return n;
   }
   template <typename T>
   T* pod_malloc(size_t numElems) {
     return maybe_pod_malloc<T>(numElems);
   }
   template <typename T>
   T* pod_calloc(size_t numElems) {
--- a/js/src/jit/JitFrames.cpp
+++ b/js/src/jit/JitFrames.cpp
@@ -3,16 +3,18 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jit/JitFrames-inl.h"
 
 #include "mozilla/ScopeExit.h"
 
+#include <algorithm>
+
 #include "jsutil.h"
 
 #include "gc/Marking.h"
 #include "jit/BaselineDebugModeOSR.h"
 #include "jit/BaselineFrame.h"
 #include "jit/BaselineIC.h"
 #include "jit/BaselineJIT.h"
 #include "jit/Ion.h"
@@ -798,17 +800,17 @@ static void TraceThisAndArguments(JSTrac
 
   JSFunction* fun = CalleeTokenToFunction(layout->calleeToken());
   if (frame.type() != FrameType::JSJitToWasm &&
       !frame.isExitFrameLayout<CalledFromJitExitFrameLayout>() &&
       !fun->nonLazyScript()->mayReadFrameArgsDirectly()) {
     nformals = fun->nargs();
   }
 
-  size_t newTargetOffset = Max(nargs, fun->nargs());
+  size_t newTargetOffset = std::max(nargs, fun->nargs());
 
   Value* argv = layout->argv();
 
   // Trace |this|.
   TraceRoot(trc, argv, "ion-thisv");
 
   // Trace actual arguments beyond the formals. Note + 1 for thisv.
   for (size_t i = nformals + 1; i < nargs + 1; i++) {
--- a/js/src/jit/MIR.h
+++ b/js/src/jit/MIR.h
@@ -12,16 +12,18 @@
 #ifndef jit_MIR_h
 #define jit_MIR_h
 
 #include "mozilla/Alignment.h"
 #include "mozilla/Array.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/MacroForEach.h"
 
+#include <algorithm>
+
 #include "jit/AtomicOp.h"
 #include "jit/BaselineIC.h"
 #include "jit/FixedList.h"
 #include "jit/InlineList.h"
 #include "jit/JitAllocPolicy.h"
 #include "jit/MacroAssembler.h"
 #include "jit/MOpcodes.h"
 #include "jit/TIOracle.h"
@@ -3736,17 +3738,17 @@ class MToDouble : public MToFPInstructio
   TruncateKind operandTruncateKind(size_t index) const override;
 
 #ifdef DEBUG
   bool isConsistentFloat32Use(MUse* use) const override { return true; }
 #endif
 
   TruncateKind truncateKind() const { return implicitTruncate_; }
   void setTruncateKind(TruncateKind kind) {
-    implicitTruncate_ = Max(implicitTruncate_, kind);
+    implicitTruncate_ = std::max(implicitTruncate_, kind);
   }
 
   MOZ_MUST_USE bool writeRecoverData(
       CompactBufferWriter& writer) const override;
   bool canRecoverOnBailout() const override {
     if (input()->type() == MIRType::Value) {
       return false;
     }
@@ -4804,17 +4806,17 @@ class MBinaryArithInstruction : public M
       return AliasSet::Store(AliasSet::Any);
     }
     return AliasSet::None();
   }
 
   bool isTruncated() const { return implicitTruncate_ == Truncate; }
   TruncateKind truncateKind() const { return implicitTruncate_; }
   void setTruncateKind(TruncateKind kind) {
-    implicitTruncate_ = Max(implicitTruncate_, kind);
+    implicitTruncate_ = std::max(implicitTruncate_, kind);
   }
 };
 
 class MMinMax : public MBinaryInstruction, public ArithPolicy::Data {
   bool isMax_;
 
   MMinMax(MDefinition* left, MDefinition* right, MIRType type, bool isMax)
       : MBinaryInstruction(classOpcode, left, right), isMax_(isMax) {
--- a/js/src/jit/MacroAssembler.cpp
+++ b/js/src/jit/MacroAssembler.cpp
@@ -4,16 +4,18 @@
  * 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 "jit/MacroAssembler-inl.h"
 
 #include "mozilla/CheckedInt.h"
 #include "mozilla/MathAlgorithms.h"
 
+#include <algorithm>
+
 #include "jsfriendapi.h"
 
 #include "builtin/TypedObject.h"
 #include "gc/GCTrace.h"
 #include "jit/AtomicOp.h"
 #include "jit/Bailouts.h"
 #include "jit/BaselineFrame.h"
 #include "jit/BaselineIC.h"
@@ -818,17 +820,17 @@ void MacroAssembler::newGCFatInlineStrin
 void MacroAssembler::newGCBigInt(Register result, Register temp, Label* fail) {
   checkAllocatorState(fail);
   freeListAllocate(result, temp, gc::AllocKind::BIGINT, fail);
 }
 
 void MacroAssembler::copySlotsFromTemplate(
     Register obj, const NativeTemplateObject& templateObj, uint32_t start,
     uint32_t end) {
-  uint32_t nfixed = Min(templateObj.numFixedSlots(), end);
+  uint32_t nfixed = std::min(templateObj.numFixedSlots(), end);
   for (unsigned i = start; i < nfixed; i++) {
     // Template objects are not exposed to script and therefore immutable.
     // However, regexp template objects are sometimes used directly (when
     // the cloning is not observable), and therefore we can end up with a
     // non-zero lastIndex. Detect this case here and just substitute 0, to
     // avoid racing with the main thread updating this slot.
     Value v;
     if (templateObj.isRegExpObject() && i == RegExpObject::lastIndexSlot()) {
@@ -1047,17 +1049,17 @@ void MacroAssembler::initGCSlots(Registe
 
   // Copy over any preserved reserved slots.
   copySlotsFromTemplate(obj, templateObj, 0, startOfUninitialized);
 
   // Fill the rest of the fixed slots with undefined and uninitialized.
   if (initContents) {
     size_t offset = NativeObject::getFixedSlotOffset(startOfUninitialized);
     fillSlotsWithUninitialized(Address(obj, offset), temp, startOfUninitialized,
-                               Min(startOfUndefined, nfixed));
+                               std::min(startOfUndefined, nfixed));
 
     offset = NativeObject::getFixedSlotOffset(startOfUndefined);
     fillSlotsWithUndefined(Address(obj, offset), temp, startOfUndefined,
                            nfixed);
   }
 
   if (ndynamic) {
     // We are short one register to do this elegantly. Borrow the obj
@@ -3485,17 +3487,17 @@ void MacroAssembler::iteratorClose(Regis
 
 template <typename T, size_t N, typename P>
 static bool AddPendingReadBarrier(Vector<T*, N, P>& list, T* value) {
   // Check if value is already present in tail of list.
   // TODO: Consider using a hash table here.
   const size_t TailWindow = 4;
 
   size_t len = list.length();
-  for (size_t i = 0; i < Min(len, TailWindow); i++) {
+  for (size_t i = 0; i < std::min(len, TailWindow); i++) {
     if (list[len - i - 1] == value) {
       return true;
     }
   }
 
   return list.append(value);
 }
 
--- a/js/src/jit/RangeAnalysis.cpp
+++ b/js/src/jit/RangeAnalysis.cpp
@@ -4,16 +4,18 @@
  * 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 "jit/RangeAnalysis.h"
 
 #include "mozilla/MathAlgorithms.h"
 #include "mozilla/TemplateLib.h"
 
+#include <algorithm>
+
 #include "jit/Ion.h"
 #include "jit/IonAnalysis.h"
 #include "jit/JitSpewer.h"
 #include "jit/MIR.h"
 #include "jit/MIRGenerator.h"
 #include "jit/MIRGraph.h"
 #include "js/Conversions.h"
 #include "vm/ArgumentsObject.h"
@@ -379,17 +381,17 @@ static bool IsExponentInteresting(const 
   // Otherwise if there's no fractional part, the lower and upper bounds,
   // which are integers, are perfectly precise.
   if (!r->canHaveFractionalPart()) {
     return false;
   }
 
   // Otherwise, if the bounds are conservatively rounded across a power-of-two
   // boundary, the exponent may imply a tighter range.
-  return FloorLog2(Max(Abs(r->lower()), Abs(r->upper()))) > r->exponent();
+  return FloorLog2(std::max(Abs(r->lower()), Abs(r->upper()))) > r->exponent();
 }
 
 void Range::dump(GenericPrinter& out) const {
   assertInvariants();
 
   // Floating-point or Integer subset.
   if (canHaveFractionalPart_) {
     out.printf("F");
@@ -492,18 +494,18 @@ Range* Range::intersect(TempAllocator& a
 
   if (!lhs) {
     return new (alloc) Range(*rhs);
   }
   if (!rhs) {
     return new (alloc) Range(*lhs);
   }
 
-  int32_t newLower = Max(lhs->lower_, rhs->lower_);
-  int32_t newUpper = Min(lhs->upper_, rhs->upper_);
+  int32_t newLower = std::max(lhs->lower_, rhs->lower_);
+  int32_t newUpper = std::min(lhs->upper_, rhs->upper_);
 
   // If upper < lower, then we have conflicting constraints. Consider:
   //
   // if (x < 0) {
   //   if (x > 0) {
   //     [Some code.]
   //   }
   // }
@@ -522,17 +524,17 @@ Range* Range::intersect(TempAllocator& a
   bool newHasInt32UpperBound =
       lhs->hasInt32UpperBound_ || rhs->hasInt32UpperBound_;
 
   FractionalPartFlag newCanHaveFractionalPart = FractionalPartFlag(
       lhs->canHaveFractionalPart_ && rhs->canHaveFractionalPart_);
   NegativeZeroFlag newMayIncludeNegativeZero =
       NegativeZeroFlag(lhs->canBeNegativeZero_ && rhs->canBeNegativeZero_);
 
-  uint16_t newExponent = Min(lhs->max_exponent_, rhs->max_exponent_);
+  uint16_t newExponent = std::min(lhs->max_exponent_, rhs->max_exponent_);
 
   // NaN is a special value which is neither greater than infinity or less than
   // negative infinity. When we intersect two ranges like [?, 0] and [0, ?], we
   // can end up thinking we have both a lower and upper bound, even though NaN
   // is still possible. In this case, just be conservative, since any case where
   // we can have NaN is not especially interesting.
   if (newHasInt32LowerBound && newHasInt32UpperBound &&
       newExponent == IncludesInfinityAndNaN) {
@@ -572,30 +574,30 @@ Range* Range::intersect(TempAllocator& a
   }
 
   return new (alloc)
       Range(newLower, newHasInt32LowerBound, newUpper, newHasInt32UpperBound,
             newCanHaveFractionalPart, newMayIncludeNegativeZero, newExponent);
 }
 
 void Range::unionWith(const Range* other) {
-  int32_t newLower = Min(lower_, other->lower_);
-  int32_t newUpper = Max(upper_, other->upper_);
+  int32_t newLower = std::min(lower_, other->lower_);
+  int32_t newUpper = std::max(upper_, other->upper_);
 
   bool newHasInt32LowerBound =
       hasInt32LowerBound_ && other->hasInt32LowerBound_;
   bool newHasInt32UpperBound =
       hasInt32UpperBound_ && other->hasInt32UpperBound_;
 
   FractionalPartFlag newCanHaveFractionalPart = FractionalPartFlag(
       canHaveFractionalPart_ || other->canHaveFractionalPart_);
   NegativeZeroFlag newMayIncludeNegativeZero =
       NegativeZeroFlag(canBeNegativeZero_ || other->canBeNegativeZero_);
 
-  uint16_t newExponent = Max(max_exponent_, other->max_exponent_);
+  uint16_t newExponent = std::max(max_exponent_, other->max_exponent_);
 
   rawInitialize(newLower, newHasInt32LowerBound, newUpper,
                 newHasInt32UpperBound, newCanHaveFractionalPart,
                 newMayIncludeNegativeZero, newExponent);
 }
 
 Range::Range(const MDefinition* def)
     : symbolicLower_(nullptr), symbolicUpper_(nullptr) {
@@ -662,17 +664,17 @@ static uint16_t ExponentImpliedByDouble(
     return Range::IncludesInfinityAndNaN;
   }
   if (IsInfinite(d)) {
     return Range::IncludesInfinity;
   }
 
   // Otherwise take the exponent part and clamp it at zero, since the Range
   // class doesn't track fractional ranges.
-  return uint16_t(Max(int_fast16_t(0), ExponentComponent(d)));
+  return uint16_t(std::max(int_fast16_t(0), ExponentComponent(d)));
 }
 
 void Range::setDouble(double l, double h) {
   MOZ_ASSERT(!(l > h));
 
   // Infer lower_, upper_, hasInt32LowerBound_, and hasInt32UpperBound_.
   if (l >= INT32_MIN && l <= INT32_MAX) {
     lower_ = int32_t(::floor(l));
@@ -693,26 +695,26 @@ void Range::setDouble(double l, double h
   } else {
     upper_ = INT32_MAX;
     hasInt32UpperBound_ = false;
   }
 
   // Infer max_exponent_.
   uint16_t lExp = ExponentImpliedByDouble(l);
   uint16_t hExp = ExponentImpliedByDouble(h);
-  max_exponent_ = Max(lExp, hExp);
+  max_exponent_ = std::max(lExp, hExp);
 
   canHaveFractionalPart_ = ExcludesFractionalParts;
   canBeNegativeZero_ = ExcludesNegativeZero;
 
   // Infer the canHaveFractionalPart_ setting. We can have a
   // fractional part if the range crosses through the neighborhood of zero. We
   // won't have a fractional value if the value is always beyond the point at
   // which double precision can't represent fractional values.
-  uint16_t minExp = Min(lExp, hExp);
+  uint16_t minExp = std::min(lExp, hExp);
   bool includesNegative = IsNaN(l) || l < 0;
   bool includesPositive = IsNaN(h) || h > 0;
   bool crossesZero = includesNegative && includesPositive;
   if (crossesZero || minExp < MaxTruncatableExponent) {
     canHaveFractionalPart_ = IncludesFractionalParts;
   }
 
   // Infer the canBeNegativeZero_ setting. We can have a negative zero if
@@ -749,17 +751,17 @@ Range* Range::add(TempAllocator& alloc, 
 
   int64_t h = (int64_t)lhs->upper_ + (int64_t)rhs->upper_;
   if (!lhs->hasInt32UpperBound() || !rhs->hasInt32UpperBound()) {
     h = NoInt32UpperBound;
   }
 
   // The exponent is at most one greater than the greater of the operands'
   // exponents, except for NaN and infinity cases.
-  uint16_t e = Max(lhs->max_exponent_, rhs->max_exponent_);
+  uint16_t e = std::max(lhs->max_exponent_, rhs->max_exponent_);
   if (e <= Range::MaxFiniteExponent) {
     ++e;
   }
 
   // Infinity + -Infinity is NaN.
   if (lhs->canBeInfiniteOrNaN() && rhs->canBeInfiniteOrNaN()) {
     e = Range::IncludesInfinityAndNaN;
   }
@@ -780,17 +782,17 @@ Range* Range::sub(TempAllocator& alloc, 
 
   int64_t h = (int64_t)lhs->upper_ - (int64_t)rhs->lower_;
   if (!lhs->hasInt32UpperBound() || !rhs->hasInt32LowerBound()) {
     h = NoInt32UpperBound;
   }
 
   // The exponent is at most one greater than the greater of the operands'
   // exponents, except for NaN and infinity cases.
-  uint16_t e = Max(lhs->max_exponent_, rhs->max_exponent_);
+  uint16_t e = std::max(lhs->max_exponent_, rhs->max_exponent_);
   if (e <= Range::MaxFiniteExponent) {
     ++e;
   }
 
   // Infinity - Infinity is NaN.
   if (lhs->canBeInfiniteOrNaN() && rhs->canBeInfiniteOrNaN()) {
     e = Range::IncludesInfinityAndNaN;
   }
@@ -804,24 +806,24 @@ Range* Range::sub(TempAllocator& alloc, 
 
 Range* Range::and_(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
   MOZ_ASSERT(lhs->isInt32());
   MOZ_ASSERT(rhs->isInt32());
 
   // If both numbers can be negative, result can be negative in the whole range
   if (lhs->lower() < 0 && rhs->lower() < 0) {
     return Range::NewInt32Range(alloc, INT32_MIN,
-                                Max(lhs->upper(), rhs->upper()));
+                                std::max(lhs->upper(), rhs->upper()));
   }
 
   // Only one of both numbers can be negative.
   // - result can't be negative
   // - Upper bound is minimum of both upper range,
   int32_t lower = 0;
-  int32_t upper = Min(lhs->upper(), rhs->upper());
+  int32_t upper = std::min(lhs->upper(), rhs->upper());
 
   // EXCEPT when upper bound of non negative number is max value,
   // because negative value can return the whole max value.
   // -1 & 5 = 5
   if (lhs->lower() < 0) {
     upper = rhs->upper();
   }
   if (rhs->lower() < 0) {
@@ -862,32 +864,32 @@ Range* Range::or_(TempAllocator& alloc, 
   MOZ_ASSERT_IF(lhs->upper() < 0, lhs->lower() != -1);
   MOZ_ASSERT_IF(rhs->upper() < 0, rhs->lower() != -1);
 
   int32_t lower = INT32_MIN;
   int32_t upper = INT32_MAX;
 
   if (lhs->lower() >= 0 && rhs->lower() >= 0) {
     // Both operands are non-negative, so the result won't be less than either.
-    lower = Max(lhs->lower(), rhs->lower());
+    lower = std::max(lhs->lower(), rhs->lower());
     // The result will have leading zeros where both operands have leading
     // zeros. CountLeadingZeroes32 of a non-negative int32 will at least be 1 to
     // account for the bit of sign.
-    upper = int32_t(UINT32_MAX >> Min(CountLeadingZeroes32(lhs->upper()),
-                                      CountLeadingZeroes32(rhs->upper())));
+    upper = int32_t(UINT32_MAX >> std::min(CountLeadingZeroes32(lhs->upper()),
+                                           CountLeadingZeroes32(rhs->upper())));
   } else {
     // The result will have leading ones where either operand has leading ones.
     if (lhs->upper() < 0) {
       unsigned leadingOnes = CountLeadingZeroes32(~lhs->lower());
-      lower = Max(lower, ~int32_t(UINT32_MAX >> leadingOnes));
+      lower = std::max(lower, ~int32_t(UINT32_MAX >> leadingOnes));
       upper = -1;
     }
     if (rhs->upper() < 0) {
       unsigned leadingOnes = CountLeadingZeroes32(~rhs->lower());
-      lower = Max(lower, ~int32_t(UINT32_MAX >> leadingOnes));
+      lower = std::max(lower, ~int32_t(UINT32_MAX >> leadingOnes));
       upper = -1;
     }
   }
 
   return Range::NewInt32Range(alloc, lower, upper);
 }
 
 Range* Range::xor_(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
@@ -932,18 +934,18 @@ Range* Range::xor_(TempAllocator& alloc,
     // Both operands are non-negative. The result will be non-negative.
     lower = 0;
     // To compute the upper value, take each operand's upper value and
     // set all bits that don't correspond to leading zero bits in the
     // other to one. For each one, this gives an upper bound for the
     // result, so we can take the minimum between the two.
     unsigned lhsLeadingZeros = CountLeadingZeroes32(lhsUpper);
     unsigned rhsLeadingZeros = CountLeadingZeroes32(rhsUpper);
-    upper = Min(rhsUpper | int32_t(UINT32_MAX >> lhsLeadingZeros),
-                lhsUpper | int32_t(UINT32_MAX >> rhsLeadingZeros));
+    upper = std::min(rhsUpper | int32_t(UINT32_MAX >> lhsLeadingZeros),
+                     lhsUpper | int32_t(UINT32_MAX >> rhsLeadingZeros));
   }
 
   // If we bitwise-negated one (but not both) of the operands above, apply the
   // bitwise-negate to the result, completing ~((~x)^y) == x^y.
   if (invertAfter) {
     lower = ~lower;
     upper = ~upper;
     Swap(lower, upper);
@@ -987,18 +989,19 @@ Range* Range::mul(TempAllocator& alloc, 
         Range(NoInt32LowerBound, NoInt32UpperBound, newCanHaveFractionalPart,
               newMayIncludeNegativeZero, exponent);
   }
   int64_t a = (int64_t)lhs->lower() * (int64_t)rhs->lower();
   int64_t b = (int64_t)lhs->lower() * (int64_t)rhs->upper();
   int64_t c = (int64_t)lhs->upper() * (int64_t)rhs->lower();
   int64_t d = (int64_t)lhs->upper() * (int64_t)rhs->upper();
   return new (alloc)
-      Range(Min(Min(a, b), Min(c, d)), Max(Max(a, b), Max(c, d)),
-            newCanHaveFractionalPart, newMayIncludeNegativeZero, exponent);
+      Range(std::min(std::min(a, b), std::min(c, d)),
+            std::max(std::max(a, b), std::max(c, d)), newCanHaveFractionalPart,
+            newMayIncludeNegativeZero, exponent);
 }
 
 Range* Range::lsh(TempAllocator& alloc, const Range* lhs, int32_t c) {
   MOZ_ASSERT(lhs->isInt32());
   int32_t shift = c & 0x1f;
 
   // If the shift doesn't loose bits or shift bits into the sign bit, we
   // can simply compute the correct range by shifting.
@@ -1089,59 +1092,59 @@ Range* Range::ursh(TempAllocator& alloc,
 Range* Range::abs(TempAllocator& alloc, const Range* op) {
   int32_t l = op->lower_;
   int32_t u = op->upper_;
   FractionalPartFlag canHaveFractionalPart = op->canHaveFractionalPart_;
 
   // Abs never produces a negative zero.
   NegativeZeroFlag canBeNegativeZero = ExcludesNegativeZero;
 
-  return new (alloc)
-      Range(Max(Max(int32_t(0), l), u == INT32_MIN ? INT32_MAX : -u), true,
-            Max(Max(int32_t(0), u), l == INT32_MIN ? INT32_MAX : -l),
-            op->hasInt32Bounds() && l != INT32_MIN, canHaveFractionalPart,
-            canBeNegativeZero, op->max_exponent_);
+  return new (alloc) Range(
+      std::max(std::max(int32_t(0), l), u == INT32_MIN ? INT32_MAX : -u), true,
+      std::max(std::max(int32_t(0), u), l == INT32_MIN ? INT32_MAX : -l),
+      op->hasInt32Bounds() && l != INT32_MIN, canHaveFractionalPart,
+      canBeNegativeZero, op->max_exponent_);
 }
 
 Range* Range::min(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
   // If either operand is NaN, the result is NaN.
   if (lhs->canBeNaN() || rhs->canBeNaN()) {
     return nullptr;
   }
 
   FractionalPartFlag newCanHaveFractionalPart = FractionalPartFlag(
       lhs->canHaveFractionalPart_ || rhs->canHaveFractionalPart_);
   NegativeZeroFlag newMayIncludeNegativeZero =
       NegativeZeroFlag(lhs->canBeNegativeZero_ || rhs->canBeNegativeZero_);
 
-  return new (alloc) Range(Min(lhs->lower_, rhs->lower_),
+  return new (alloc) Range(std::min(lhs->lower_, rhs->lower_),
                            lhs->hasInt32LowerBound_ && rhs->hasInt32LowerBound_,
-                           Min(lhs->upper_, rhs->upper_),
+                           std::min(lhs->upper_, rhs->upper_),
                            lhs->hasInt32UpperBound_ || rhs->hasInt32UpperBound_,
                            newCanHaveFractionalPart, newMayIncludeNegativeZero,
-                           Max(lhs->max_exponent_, rhs->max_exponent_));
+                           std::max(lhs->max_exponent_, rhs->max_exponent_));
 }
 
 Range* Range::max(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
   // If either operand is NaN, the result is NaN.
   if (lhs->canBeNaN() || rhs->canBeNaN()) {
     return nullptr;
   }
 
   FractionalPartFlag newCanHaveFractionalPart = FractionalPartFlag(
       lhs->canHaveFractionalPart_ || rhs->canHaveFractionalPart_);
   NegativeZeroFlag newMayIncludeNegativeZero =
       NegativeZeroFlag(lhs->canBeNegativeZero_ || rhs->canBeNegativeZero_);
 
-  return new (alloc) Range(Max(lhs->lower_, rhs->lower_),
+  return new (alloc) Range(std::max(lhs->lower_, rhs->lower_),
                            lhs->hasInt32LowerBound_ || rhs->hasInt32LowerBound_,
-                           Max(lhs->upper_, rhs->upper_),
+                           std::max(lhs->upper_, rhs->upper_),
                            lhs->hasInt32UpperBound_ && rhs->hasInt32UpperBound_,
                            newCanHaveFractionalPart, newMayIncludeNegativeZero,
-                           Max(lhs->max_exponent_, rhs->max_exponent_));
+                           std::max(lhs->max_exponent_, rhs->max_exponent_));
 }
 
 Range* Range::floor(TempAllocator& alloc, const Range* op) {
   Range* copy = new (alloc) Range(*op);
   // Decrement lower bound of copy range if op have a factional part and lower
   // bound is Int32 defined. Also we avoid to decrement when op have a
   // fractional part but lower_ >= JSVAL_INT_MAX.
   if (op->canHaveFractionalPart() && op->hasInt32LowerBound()) {
@@ -1181,20 +1184,20 @@ Range* Range::ceil(TempAllocator& alloc,
   return copy;
 }
 
 Range* Range::sign(TempAllocator& alloc, const Range* op) {
   if (op->canBeNaN()) {
     return nullptr;
   }
 
-  return new (alloc)
-      Range(Max(Min(op->lower_, 1), -1), Max(Min(op->upper_, 1), -1),
-            Range::ExcludesFractionalParts,
-            NegativeZeroFlag(op->canBeNegativeZero()), 0);
+  return new (alloc) Range(std::max(std::min(op->lower_, 1), -1),
+                           std::max(std::min(op->upper_, 1), -1),
+                           Range::ExcludesFractionalParts,
+                           NegativeZeroFlag(op->canBeNegativeZero()), 0);
 }
 
 Range* Range::NaNToZero(TempAllocator& alloc, const Range* op) {
   Range* copy = new (alloc) Range(*op);
   if (copy->canBeNaN()) {
     copy->max_exponent_ = Range::IncludesInfinity;
     if (!copy->canBeZero()) {
       Range zero;
@@ -1564,18 +1567,18 @@ void MMod::computeRange(TempAllocator& a
     }
   }
 
   // For unsigned mod, we have to convert both operands to unsigned.
   // Note that we handled the case of a zero rhs above.
   if (unsigned_) {
     // The result of an unsigned mod will never be unsigned-greater than
     // either operand.
-    uint32_t lhsBound = Max<uint32_t>(lhs.lower(), lhs.upper());
-    uint32_t rhsBound = Max<uint32_t>(rhs.lower(), rhs.upper());
+    uint32_t lhsBound = std::max<uint32_t>(lhs.lower(), lhs.upper());
+    uint32_t rhsBound = std::max<uint32_t>(rhs.lower(), rhs.upper());
 
     // If either range crosses through -1 as a signed value, it could be
     // the maximum unsigned value when interpreted as unsigned. If the range
     // doesn't include -1, then the simple max value we computed above is
     // correct.
     if (lhs.lower() <= -1 && lhs.upper() >= -1) {
       lhsBound = UINT32_MAX;
     }
@@ -1584,44 +1587,44 @@ void MMod::computeRange(TempAllocator& a
     }
 
     // The result will never be equal to the rhs, and we shouldn't have
     // any rounding to worry about.
     MOZ_ASSERT(!lhs.canHaveFractionalPart() && !rhs.canHaveFractionalPart());
     --rhsBound;
 
     // This gives us two upper bounds, so we can take the best one.
-    setRange(Range::NewUInt32Range(alloc, 0, Min(lhsBound, rhsBound)));
+    setRange(Range::NewUInt32Range(alloc, 0, std::min(lhsBound, rhsBound)));
     return;
   }
 
   // Math.abs(lhs % rhs) == Math.abs(lhs) % Math.abs(rhs).
   // First, the absolute value of the result will always be less than the
   // absolute value of rhs. (And if rhs is zero, the result is NaN).
   int64_t a = Abs<int64_t>(rhs.lower());
   int64_t b = Abs<int64_t>(rhs.upper());
   if (a == 0 && b == 0) {
     return;
   }
-  int64_t rhsAbsBound = Max(a, b);
+  int64_t rhsAbsBound = std::max(a, b);
 
   // If the value is known to be integer, less-than abs(rhs) is equivalent
   // to less-than-or-equal abs(rhs)-1. This is important for being able to
   // say that the result of x%256 is an 8-bit unsigned number.
   if (!lhs.canHaveFractionalPart() && !rhs.canHaveFractionalPart()) {
     --rhsAbsBound;
   }
 
   // Next, the absolute value of the result will never be greater than the
   // absolute value of lhs.
   int64_t lhsAbsBound =
-      Max(Abs<int64_t>(lhs.lower()), Abs<int64_t>(lhs.upper()));
+      std::max(Abs<int64_t>(lhs.lower()), Abs<int64_t>(lhs.upper()));
 
   // This gives us two upper bounds, so we can take the best one.
-  int64_t absBound = Min(lhsAbsBound, rhsAbsBound);
+  int64_t absBound = std::min(lhsAbsBound, rhsAbsBound);
 
   // Now consider the sign of the result.
   // If lhs is non-negative, the result will be non-negative.
   // If lhs is non-positive, the result will be non-positive.
   int64_t lower = lhs.lower() >= 0 ? 0 : -absBound;
   int64_t upper = lhs.upper() <= 0 ? 0 : absBound;
 
   Range::FractionalPartFlag newCanHaveFractionalPart =
@@ -1630,17 +1633,17 @@ void MMod::computeRange(TempAllocator& a
 
   // If the lhs can have the sign bit set and we can return a zero, it'll be a
   // negative zero.
   Range::NegativeZeroFlag newMayIncludeNegativeZero =
       Range::NegativeZeroFlag(lhs.canHaveSignBitSet());
 
   setRange(new (alloc) Range(lower, upper, newCanHaveFractionalPart,
                              newMayIncludeNegativeZero,
-                             Min(lhs.exponent(), rhs.exponent())));
+                             std::min(lhs.exponent(), rhs.exponent())));
 }
 
 void MDiv::computeRange(TempAllocator& alloc) {
   if (specialization() != MIRType::Int32 &&
       specialization() != MIRType::Double) {
     return;
   }
   Range lhs(getOperand(0));
@@ -2716,33 +2719,33 @@ MDefinition::TruncateKind MTruncateToInt
 MDefinition::TruncateKind MBinaryBitwiseInstruction::operandTruncateKind(
     size_t index) const {
   // The bitwise operators truncate to int32.
   return Truncate;
 }
 
 MDefinition::TruncateKind MLimitedTruncate::operandTruncateKind(
     size_t index) const {
-  return Min(truncateKind(), truncateLimit_);
+  return std::min(truncateKind(), truncateLimit_);
 }
 
 MDefinition::TruncateKind MAdd::operandTruncateKind(size_t index) const {
   // This operator is doing some arithmetic. If its result is truncated,
   // it's an indirect truncate for its operands.
-  return Min(truncateKind(), IndirectTruncate);
+  return std::min(truncateKind(), IndirectTruncate);
 }
 
 MDefinition::TruncateKind MSub::operandTruncateKind(size_t index) const {
   // See the comment in MAdd::operandTruncateKind.
-  return Min(truncateKind(), IndirectTruncate);
+  return std::min(truncateKind(), IndirectTruncate);
 }
 
 MDefinition::TruncateKind MMul::operandTruncateKind(size_t index) const {
   // See the comment in MAdd::operandTruncateKind.
-  return Min(truncateKind(), IndirectTruncate);
+  return std::min(truncateKind(), IndirectTruncate);
 }
 
 MDefinition::TruncateKind MToDouble::operandTruncateKind(size_t index) const {
   // MToDouble propagates its truncate kind to its operand.
   return truncateKind();
 }
 
 MDefinition::TruncateKind MStoreUnboxedScalar::operandTruncateKind(
@@ -2755,21 +2758,21 @@ MDefinition::TruncateKind MStoreUnboxedS
 
 MDefinition::TruncateKind MStoreTypedArrayElementHole::operandTruncateKind(
     size_t index) const {
   // An integer store truncates the stored value.
   return index == 3 && isIntegerWrite() ? Truncate : NoTruncate;
 }
 
 MDefinition::TruncateKind MDiv::operandTruncateKind(size_t index) const {
-  return Min(truncateKind(), TruncateAfterBailouts);
+  return std::min(truncateKind(), TruncateAfterBailouts);
 }
 
 MDefinition::TruncateKind MMod::operandTruncateKind(size_t index) const {
-  return Min(truncateKind(), TruncateAfterBailouts);
+  return std::min(truncateKind(), TruncateAfterBailouts);
 }
 
 MDefinition::TruncateKind MCompare::operandTruncateKind(size_t index) const {
   // If we're doing an int32 comparison on operands which were previously
   // floating-point, convert them!
   MOZ_ASSERT_IF(truncateOperands_, isInt32Comparison());
   return truncateOperands_ ? TruncateAfterBailouts : NoTruncate;
 }
@@ -2911,25 +2914,25 @@ static MDefinition::TruncateKind Compute
     if (consumer->isRecoveredOnBailout()) {
       isCapturedResult = true;
       hasUseRemoved = hasUseRemoved || consumer->isUseRemoved();
       continue;
     }
 
     MDefinition::TruncateKind consumerKind =
         consumer->operandTruncateKind(consumer->indexOf(*use));
-    kind = Min(kind, consumerKind);
+    kind = std::min(kind, consumerKind);
     if (kind == MDefinition::NoTruncate) {
       break;
     }
   }
 
   // We cannot do full trunction on guarded instructions.
   if (candidate->isGuard() || candidate->isGuardRangeBailouts()) {
-    kind = Min(kind, MDefinition::TruncateAfterBailouts);
+    kind = std::min(kind, MDefinition::TruncateAfterBailouts);
   }
 
   // If the value naturally produces an int32 value (before bailout checks)
   // that needs no conversion, we don't have to worry about resume points
   // seeing truncated values.
   bool needsConversion = !candidate->range() || !candidate->range()->isInt32();
 
   // If the instruction is explicitly truncated (not indirectly) by all its
@@ -2953,17 +2956,17 @@ static MDefinition::TruncateKind Compute
     // recovered on bailout, then we can clone it and use the cloned
     // instruction to encode the recover instruction.  Otherwise, we should
     // keep the original result and bailout if the value is not in the int32
     // range.
     if (!JitOptions.disableRecoverIns && isRecoverableResult &&
         candidate->canRecoverOnBailout()) {
       *shouldClone = true;
     } else {
-      kind = Min(kind, MDefinition::TruncateAfterBailouts);
+      kind = std::min(kind, MDefinition::TruncateAfterBailouts);
     }
   }
 
   return kind;
 }
 
 static MDefinition::TruncateKind ComputeTruncateKind(MDefinition* candidate,
                                                      bool* shouldClone) {
--- a/js/src/jit/RangeAnalysis.h
+++ b/js/src/jit/RangeAnalysis.h
@@ -5,16 +5,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef jit_RangeAnalysis_h
 #define jit_RangeAnalysis_h
 
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/MathAlgorithms.h"
 
+#include <algorithm>
+
 #include "jit/IonAnalysis.h"
 #include "jit/MIR.h"
 
 namespace js {
 namespace jit {
 
 class MBasicBlock;
 class MIRGraph;
@@ -278,17 +280,17 @@ class Range : public TempObject {
   // Compute the least exponent value that would be compatible with the
   // values of lower() and upper().
   //
   // Note:
   //     exponent of JSVAL_INT_MIN == 31
   //     exponent of JSVAL_INT_MAX == 30
   uint16_t exponentImpliedByInt32Bounds() const {
     // The number of bits needed to encode |max| is the power of 2 plus one.
-    uint32_t max = Max(mozilla::Abs(lower()), mozilla::Abs(upper()));
+    uint32_t max = std::max(mozilla::Abs(lower()), mozilla::Abs(upper()));
     uint16_t result = mozilla::FloorLog2(max);
     MOZ_ASSERT(result ==
                (max == 0 ? 0 : mozilla::ExponentComponent(double(max))));
     return result;
   }
 
   // When converting a range which contains fractional values to a range
   // containing only integers, the old max_exponent_ value may imply a better
@@ -299,18 +301,18 @@ class Range : public TempObject {
   // Given an exponent value and pointers to the lower and upper bound values,
   // this function refines the lower and upper bound values to the tighest
   // bound for integer values implied by the exponent.
   static void refineInt32BoundsByExponent(uint16_t e, int32_t* l, bool* lb,
                                           int32_t* h, bool* hb) {
     if (e < MaxInt32Exponent) {
       // pow(2, max_exponent_+1)-1 to compute a maximum absolute value.
       int32_t limit = (uint32_t(1) << (e + 1)) - 1;
-      *h = Min(*h, limit);
-      *l = Max(*l, -limit);
+      *h = std::min(*h, limit);
+      *l = std::max(*l, -limit);
       *hb = true;
       *lb = true;
     }
   }
 
   // If the value of any of the fields implies a stronger possible value for
   // any other field, update that field to the stronger value. The range must
   // be completely valid before and it is guaranteed to be kept valid.
@@ -567,25 +569,25 @@ class Range : public TempObject {
     return !hasInt32LowerBound() || canBeFiniteNegative() ||
            canBeNegativeZero();
   }
 
   // Set this range to have a lower bound not less than x.
   void refineLower(int32_t x) {
     assertInvariants();
     hasInt32LowerBound_ = true;
-    lower_ = Max(lower_, x);
+    lower_ = std::max(lower_, x);
     optimize();
   }
 
   // Set this range to have an upper bound not greater than x.
   void refineUpper(int32_t x) {
     assertInvariants();
     hasInt32UpperBound_ = true;
-    upper_ = Min(upper_, x);
+    upper_ = std::min(upper_, x);
     optimize();
   }
 
   // Set this range to exclude negative zero.
   void refineToExcludeNegativeZero() {
     assertInvariants();
     canBeNegativeZero_ = ExcludesNegativeZero;
     optimize();
--- a/js/src/jit/RematerializedFrame.cpp
+++ b/js/src/jit/RematerializedFrame.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jit/RematerializedFrame.h"
 
+#include <algorithm>
 #include <utility>
 
 #include "debugger/DebugAPI.h"
 #include "jit/JitFrames.h"
 #include "vm/ArgumentsObject.h"
 
 #include "jit/JitFrames-inl.h"
 #include "vm/EnvironmentObject-inl.h"
@@ -56,17 +57,17 @@ RematerializedFrame::RematerializedFrame
 }
 
 /* static */
 RematerializedFrame* RematerializedFrame::New(JSContext* cx, uint8_t* top,
                                               InlineFrameIterator& iter,
                                               MaybeReadFallback& fallback) {
   unsigned numFormals =
       iter.isFunctionFrame() ? iter.calleeTemplate()->nargs() : 0;
-  unsigned argSlots = Max(numFormals, iter.numActualArgs());
+  unsigned argSlots = std::max(numFormals, iter.numActualArgs());
   unsigned extraSlots = argSlots + iter.script()->nfixed();
 
   // One Value slot is included in sizeof(RematerializedFrame), so we can
   // reduce the extra slot count by one.  However, if there are zero slot
   // allocations total, then reducing the slots by one will lead to
   // the memory allocation being smaller  than sizeof(RematerializedFrame).
   if (extraSlots > 0) {
     extraSlots -= 1;
--- a/js/src/jit/arm/Assembler-arm.h
+++ b/js/src/jit/arm/Assembler-arm.h
@@ -6,16 +6,18 @@
 
 #ifndef jit_arm_Assembler_arm_h
 #define jit_arm_Assembler_arm_h
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/MathAlgorithms.h"
 
+#include <algorithm>
+
 #include "jit/arm/Architecture-arm.h"
 #include "jit/arm/disasm/Disasm-arm.h"
 #include "jit/CompactBuffer.h"
 #include "jit/IonCode.h"
 #include "jit/JitRealm.h"
 #include "jit/shared/Assembler-shared.h"
 #include "jit/shared/Disassembler-shared.h"
 #include "jit/shared/IonAssemblerBufferWithConstantPools.h"
@@ -1759,30 +1761,30 @@ class Assembler : public AssemblerShared
   }
   void finishFloatTransfer() {
     MOZ_ASSERT(dtmActive);
     dtmActive = false;
     MOZ_ASSERT(dtmLastReg != -1);
     dtmDelta = dtmDelta ? dtmDelta : 1;
     // The operand for the vstr/vldr instruction is the lowest register in the
     // range.
-    int low = Min(dtmLastReg, vdtmFirstReg);
-    int high = Max(dtmLastReg, vdtmFirstReg);
+    int low = std::min(dtmLastReg, vdtmFirstReg);
+    int high = std::max(dtmLastReg, vdtmFirstReg);
     // Fencepost problem.
     int len = high - low + 1;
     // vdtm can only transfer 16 registers at once.  If we need to transfer
     // more, then either hoops are necessary, or we need to be updating the
     // register.
     MOZ_ASSERT_IF(len > 16, dtmUpdate == WriteBack);
 
     int adjustLow = dtmLoadStore == IsStore ? 0 : 1;
     int adjustHigh = dtmLoadStore == IsStore ? -1 : 0;
     while (len > 0) {
       // Limit the instruction to 16 registers.
-      int curLen = Min(len, 16);
+      int curLen = std::min(len, 16);
       // If it is a store, we want to start at the high end and move down
       // (e.g. vpush d16-d31; vpush d0-d15).
       int curStart = (dtmLoadStore == IsStore) ? high - curLen + 1 : low;
       as_vdtm(dtmLoadStore, dtmBase,
               VFPRegister(FloatRegister::FromCode(curStart)), curLen, dtmCond);
       // Update the bounds.
       low += adjustLow * curLen;
       high += adjustHigh * curLen;
@@ -2224,17 +2226,17 @@ static inline bool GetDoubleArgReg(uint3
 }
 
 static inline uint32_t GetIntArgStackDisp(uint32_t usedIntArgs,
                                           uint32_t usedFloatArgs,
                                           uint32_t* padding) {
   MOZ_ASSERT(UseHardFpABI());
   MOZ_ASSERT(usedIntArgs >= NumIntArgRegs);
   uint32_t doubleSlots =
-      Max(0, (int32_t)usedFloatArgs - (int32_t)NumFloatArgRegs);
+      std::max(0, (int32_t)usedFloatArgs - (int32_t)NumFloatArgRegs);
   doubleSlots *= 2;
   int intSlots = usedIntArgs - NumIntArgRegs;
   return (intSlots + doubleSlots + *padding) * sizeof(intptr_t);
 }
 
 static inline uint32_t GetFloat32ArgStackDisp(uint32_t usedIntArgs,
                                               uint32_t usedFloatArgs,
                                               uint32_t* padding) {
--- a/js/src/jit/shared/IonAssemblerBuffer.h
+++ b/js/src/jit/shared/IonAssemblerBuffer.h
@@ -5,16 +5,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef jit_shared_IonAssemblerBuffer_h
 #define jit_shared_IonAssemblerBuffer_h
 
 #include "mozilla/Assertions.h"
 #include "mozilla/MathAlgorithms.h"
 
+#include <algorithm>
+
 #include "jit/shared/Assembler-shared.h"
 
 namespace js {
 namespace jit {
 
 // The offset into a buffer, in bytes.
 class BufferOffset {
   int offset;
@@ -385,17 +387,17 @@ class AssemblerBuffer {
     if (offset >= int(bufferSize)) {
       return (Inst*)&tail->instructions[offset - bufferSize];
     }
 
     // How close is this offset to the previous one we looked up?
     // If it is sufficiently far from the start and end of the buffer,
     // use the finger to start midway through the list.
     int finger_dist = abs(offset - finger_offset);
-    if (finger_dist < Min(offset, int(bufferSize - offset))) {
+    if (finger_dist < std::min(offset, int(bufferSize - offset))) {
       if (finger_offset < offset) {
         return getInstForwards(off, finger, finger_offset, true);
       }
       return getInstBackwards(off, finger, finger_offset, true);
     }
 
     // Is the instruction closer to the start or to the end?
     if (offset < int(bufferSize - offset)) {
--- a/js/src/jit/x86-shared/Assembler-x86-shared.cpp
+++ b/js/src/jit/x86-shared/Assembler-x86-shared.cpp
@@ -1,16 +1,18 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/Maybe.h"
 
+#include <algorithm>
+
 #include "gc/Marking.h"
 #include "jit/JitRealm.h"
 #if defined(JS_CODEGEN_X86)
 #  include "jit/x86/MacroAssembler-x86.h"
 #elif defined(JS_CODEGEN_X64)
 #  include "jit/x64/MacroAssembler-x64.h"
 #else
 #  error "Wrong architecture. Only x86 and x64 should build this file!"
@@ -322,17 +324,17 @@ void CPUInfo::SetSSEVersion() {
     maxSSEVersion = SSE2;
   } else if (flagsEdx & SSEBit) {
     maxSSEVersion = SSE;
   } else {
     maxSSEVersion = NoSSE;
   }
 
   if (maxEnabledSSEVersion != UnknownSSE) {
-    maxSSEVersion = Min(maxSSEVersion, maxEnabledSSEVersion);
+    maxSSEVersion = std::min(maxSSEVersion, maxEnabledSSEVersion);
   }
 
   static constexpr int AVXBit = 1 << 28;
   static constexpr int XSAVEBit = 1 << 27;
   avxPresent = (flagsEcx & AVXBit) && (flagsEcx & XSAVEBit) && avxEnabled;
 
   // If the hardware supports AVX, check whether the OS supports it too.
   if (avxPresent) {
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -10,16 +10,17 @@
 
 #include "jsapi.h"
 
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/PodOperations.h"
 #include "mozilla/Sprintf.h"
 
+#include <algorithm>
 #ifdef __linux__
 #  include <dlfcn.h>
 #endif
 #include <stdarg.h>
 #include <string.h>
 
 #include "jsdate.h"
 #include "jsexn.h"
@@ -4571,17 +4572,17 @@ JS_PUBLIC_API bool JS_EncodeStringToBuff
   CHECK_THREAD(cx);
 
   JSLinearString* linear = str->ensureLinear(cx);
   if (!linear) {
     return false;
   }
 
   JS::AutoCheckCannotGC nogc;
-  size_t writeLength = Min(linear->length(), length);
+  size_t writeLength = std::min(linear->length(), length);
   if (linear->hasLatin1Chars()) {
     mozilla::PodCopy(reinterpret_cast<Latin1Char*>(buffer),
                      linear->latin1Chars(nogc), writeLength);
   } else {
     const char16_t* src = linear->twoByteChars(nogc);
     for (size_t i = 0; i < writeLength; i++) {
       buffer[i] = char(src[i]);
     }
--- a/js/src/jsdate.cpp
+++ b/js/src/jsdate.cpp
@@ -19,16 +19,17 @@
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/Atomics.h"
 #include "mozilla/Casting.h"
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/Sprintf.h"
 #include "mozilla/TextUtils.h"
 
+#include <algorithm>
 #include <math.h>
 #include <string.h>
 
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "jsnum.h"
 #include "jstypes.h"
 #include "jsutil.h"
@@ -794,17 +795,17 @@ static bool ParseFractional(double* resu
  * Succeed if exactly n digits are converted. Advance *i only
  * on success.
  */
 template <typename CharT>
 static bool ParseDigitsN(size_t n, size_t* result, const CharT* s, size_t* i,
                          size_t limit) {
   size_t init = *i;
 
-  if (ParseDigits(result, s, i, Min(limit, init + n))) {
+  if (ParseDigits(result, s, i, std::min(limit, init + n))) {
     return (*i - init) == n;
   }
 
   *i = init;
   return false;
 }
 
 /*
@@ -814,17 +815,17 @@ static bool ParseDigitsN(size_t n, size_
  * Succeed only if greater than zero but less than or equal to n digits are
  * converted. Advance *i only on success.
  */
 template <typename CharT>
 static bool ParseDigitsNOrLess(size_t n, size_t* result, const CharT* s,
                                size_t* i, size_t limit) {
   size_t init = *i;
 
-  if (ParseDigits(result, s, i, Min(limit, init + n))) {
+  if (ParseDigits(result, s, i, std::min(limit, init + n))) {
     return ((*i - init) > 0) && ((*i - init) <= n);
   }
 
   *i = init;
   return false;
 }
 
 static int DaysInMonth(int year, int month) {
--- a/js/src/jsutil.h
+++ b/js/src/jsutil.h
@@ -11,23 +11,9 @@
 #ifndef jsutil_h
 #define jsutil_h
 
 #include "util/BitArray.h"
 #include "util/DiagnosticAssertions.h"
 #include "util/Memory.h"
 #include "util/Poison.h"
 
-namespace js {
-
-template <class T>
-static constexpr inline T Min(T t1, T t2) {
-  return t1 < t2 ? t1 : t2;
-}
-
-template <class T>
-static constexpr inline T Max(T t1, T t2) {
-  return t1 > t2 ? t1 : t2;
-}
-
-} /* namespace js */
-
 #endif /* jsutil_h */
--- a/js/src/shell/js.cpp
+++ b/js/src/shell/js.cpp
@@ -17,16 +17,17 @@
 #include "mozilla/ScopeExit.h"
 #include "mozilla/Sprintf.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/UniquePtrExtensions.h"  // UniqueFreePtr
 #include "mozilla/Unused.h"
 #include "mozilla/Utf8.h"
 #include "mozilla/Variant.h"
 
+#include <algorithm>
 #include <chrono>
 #ifdef XP_WIN
 #  include <direct.h>
 #  include <process.h>
 #endif
 #include <errno.h>
 #include <fcntl.h>
 #if defined(XP_WIN)
@@ -4279,17 +4280,17 @@ static bool Sleep_fn(JSContext* cx, unsi
     if (!ToNumber(cx, args[0], &t_secs)) {
       return false;
     }
     if (mozilla::IsNaN(t_secs)) {
       JS_ReportErrorASCII(cx, "sleep interval is not a number");
       return false;
     }
 
-    duration = TimeDuration::FromSeconds(Max(0.0, t_secs));
+    duration = TimeDuration::FromSeconds(std::max(0.0, t_secs));
     const TimeDuration MAX_TIMEOUT_INTERVAL =
         TimeDuration::FromSeconds(MAX_TIMEOUT_SECONDS);
     if (duration > MAX_TIMEOUT_INTERVAL) {
       JS_ReportErrorASCII(cx, "Excessive sleep interval");
       return false;
     }
   }
   {
@@ -7292,17 +7293,17 @@ static void BufferStreamMain(BufferStrea
 
     if (shutdown) {
       job->consumer->streamError(JSMSG_STREAM_CONSUME_ERROR);
       break;
     }
 
     std::this_thread::sleep_for(std::chrono::milliseconds(delayMillis));
 
-    chunkSize = Min(chunkSize, byteLength - byteOffset);
+    chunkSize = std::min(chunkSize, byteLength - byteOffset);
 
     if (!job->consumer->consumeChunk(bytes + byteOffset, chunkSize)) {
       break;
     }
 
     byteOffset += chunkSize;
   }
 
--- a/js/src/shell/jsoptparse.cpp
+++ b/js/src/shell/jsoptparse.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "shell/jsoptparse.h"
 
+#include <algorithm>
 #include <stdarg.h>
 
 #include "jsutil.h"
 
 #include "util/Unicode.h"
 
 using namespace js;
 using namespace js::cli;
@@ -171,17 +172,17 @@ OptionParser::Result OptionParser::print
 
   if (!arguments.empty()) {
     printf("Arguments:\n");
 
     static const char fmt[] = "  %s ";
     size_t fmtChars = sizeof(fmt) - 2;
     size_t lhsLen = 0;
     for (Option* arg : arguments) {
-      lhsLen = Max(lhsLen, strlen(arg->longflag) + fmtChars);
+      lhsLen = std::max(lhsLen, strlen(arg->longflag) + fmtChars);
     }
 
     for (Option* arg : arguments) {
       size_t chars = printf(fmt, arg->longflag);
       for (; chars < lhsLen; ++chars) {
         putchar(' ');
       }
       PrintParagraph(arg->help, lhsLen, helpWidth, false);
@@ -200,17 +201,17 @@ OptionParser::Result OptionParser::print
 
       size_t fmtLen;
       OptionFlagsToFormatInfo(opt->shortflag, opt->isValued(), &fmtLen);
 
       size_t len = fmtLen + longflagLen;
       if (opt->isValued()) {
         len += strlen(opt->asValued()->metavar);
       }
-      lhsLen = Max(lhsLen, len);
+      lhsLen = std::max(lhsLen, len);
     }
 
     /* Print option help text. */
     for (Option* opt : options) {
       size_t fmtLen;
       const char* fmt =
           OptionFlagsToFormatInfo(opt->shortflag, opt->isValued(), &fmtLen);
       size_t chars;
--- a/js/src/util/StringBuffer.cpp
+++ b/js/src/util/StringBuffer.cpp
@@ -5,16 +5,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "util/StringBuffer.h"
 
 #include "mozilla/Latin1.h"
 #include "mozilla/Range.h"
 #include "mozilla/Unused.h"
 
+#include <algorithm>
+
 #include "vm/JSObject-inl.h"
 #include "vm/StringType-inl.h"
 
 using namespace js;
 
 template <typename CharT, class Buffer>
 static CharT* ExtractWellSized(Buffer& cb) {
   size_t capacity = cb.capacity();
@@ -53,17 +55,17 @@ bool StringBuffer::inflateChars() {
 
   TwoByteCharBuffer twoByte(StringBufferAllocPolicy{cx_, arenaId_});
 
   /*
    * Note: we don't use Vector::capacity() because it always returns a
    * value >= sInlineCapacity. Since Latin1CharBuffer::sInlineCapacity >
    * TwoByteCharBuffer::sInlineCapacitychars, we'd always malloc here.
    */
-  size_t capacity = Max(reserved_, latin1Chars().length());
+  size_t capacity = std::max(reserved_, latin1Chars().length());
   if (!twoByte.reserve(capacity)) {
     return false;
   }
 
   twoByte.infallibleGrowByUninitialized(latin1Chars().length());
 
   mozilla::ConvertLatin1toUtf16(mozilla::AsChars(latin1Chars()), twoByte);
 
--- a/js/src/util/Text.h
+++ b/js/src/util/Text.h
@@ -9,16 +9,17 @@
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/Assertions.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/Latin1.h"
 #include "mozilla/TextUtils.h"
 #include "mozilla/Utf8.h"
 
+#include <algorithm>
 #include <stddef.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <string>
 #include <type_traits>
 
 #include "jsutil.h"
 #include "NamespaceImports.h"
@@ -72,17 +73,17 @@ inline bool EqualChars(const Char1* s1, 
   return mozilla::ArrayEqual(s1, s2, len);
 }
 
 // Return less than, equal to, or greater than zero depending on whether
 // s1 is less than, equal to, or greater than s2.
 template <typename Char1, typename Char2>
 inline int32_t CompareChars(const Char1* s1, size_t len1, const Char2* s2,
                             size_t len2) {
-  size_t n = Min(len1, len2);
+  size_t n = std::min(len1, len2);
   for (size_t i = 0; i < n; i++) {
     if (int32_t cmp = s1[i] - s2[i]) {
       return cmp;
     }
   }
 
   return int32_t(len1 - len2);
 }
--- a/js/src/vm/ArgumentsObject.cpp
+++ b/js/src/vm/ArgumentsObject.cpp
@@ -3,16 +3,18 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "vm/ArgumentsObject-inl.h"
 
 #include "mozilla/PodOperations.h"
 
+#include <algorithm>
+
 #include "gc/FreeOp.h"
 #include "jit/JitFrames.h"
 #include "js/StableStringChars.h"
 #include "vm/AsyncFunction.h"
 #include "vm/GlobalObject.h"
 #include "vm/Stack.h"
 
 #include "gc/Nursery-inl.h"
@@ -69,17 +71,18 @@ bool ArgumentsObject::markElementDeleted
   return true;
 }
 
 static void CopyStackFrameArguments(const AbstractFramePtr frame,
                                     GCPtrValue* dst, unsigned totalArgs) {
   MOZ_ASSERT_IF(frame.isInterpreterFrame(),
                 !frame.asInterpreterFrame()->runningInJit());
 
-  MOZ_ASSERT(Max(frame.numActualArgs(), frame.numFormalArgs()) == totalArgs);
+  MOZ_ASSERT(std::max(frame.numActualArgs(), frame.numFormalArgs()) ==
+             totalArgs);
 
   /* Copy arguments. */
   Value* src = frame.argv();
   Value* end = src + totalArgs;
   while (src != end) {
     (dst++)->init(*src++);
   }
 }
@@ -143,17 +146,17 @@ struct CopyJitFrameArgs {
       : frame_(frame), callObj_(callObj) {}
 
   void copyArgs(JSContext*, GCPtrValue* dstBase, unsigned totalArgs) const {
     unsigned numActuals = frame_->numActualArgs();
     unsigned numFormals =
         jit::CalleeTokenToFunction(frame_->calleeToken())->nargs();
     MOZ_ASSERT(numActuals <= totalArgs);
     MOZ_ASSERT(numFormals <= totalArgs);
-    MOZ_ASSERT(Max(numActuals, numFormals) == totalArgs);
+    MOZ_ASSERT(std::max(numActuals, numFormals) == totalArgs);
 
     /* Copy all arguments. */
     Value* src = frame_->argv() + 1; /* +1 to skip this. */
     Value* end = src + numActuals;
     GCPtrValue* dst = dstBase;
     while (src != end) {
       (dst++)->init(*src++);
     }
@@ -184,17 +187,17 @@ struct CopyScriptFrameIterArgs {
     /* Copy actual arguments. */
     iter_.unaliasedForEachActual(cx, CopyToHeap(dstBase));
 
     /* Define formals which are not part of the actuals. */
     unsigned numActuals = iter_.numActualArgs();
     unsigned numFormals = iter_.calleeTemplate()->nargs();
     MOZ_ASSERT(numActuals <= totalArgs);
     MOZ_ASSERT(numFormals <= totalArgs);
-    MOZ_ASSERT(Max(numActuals, numFormals) == totalArgs);
+    MOZ_ASSERT(std::max(numActuals, numFormals) == totalArgs);
 
     if (numActuals < numFormals) {
       GCPtrValue* dst = dstBase + numActuals;
       GCPtrValue* dstEnd = dstBase + totalArgs;
       while (dst != dstEnd) {
         (dst++)->init(UndefinedValue());
       }
     }
@@ -280,17 +283,17 @@ ArgumentsObject* ArgumentsObject::create
   if (!templateObj) {
     return nullptr;
   }
 
   RootedShape shape(cx, templateObj->lastProperty());
   RootedObjectGroup group(cx, templateObj->group());
 
   unsigned numFormals = callee->nargs();
-  unsigned numArgs = Max(numActuals, numFormals);
+  unsigned numArgs = std::max(numActuals, numFormals);
   unsigned numBytes = ArgumentsData::bytesRequired(numArgs);
 
   Rooted<ArgumentsObject*> obj(cx);
   ArgumentsData* data = nullptr;
   {
     // The copyArgs call below can allocate objects, so add this block scope
     // to make sure we set the metadata for this arguments object first.
     AutoSetNewObjectMetadata metadata(cx);
@@ -385,17 +388,17 @@ ArgumentsObject* ArgumentsObject::finish
   AutoUnsafeCallWithABI unsafe;
 
   JSFunction* callee = jit::CalleeTokenToFunction(frame->calleeToken());
   RootedObject callObj(cx, scopeChain->is<CallObject>() ? scopeChain : nullptr);
   CopyJitFrameArgs copy(frame, callObj);
 
   unsigned numActuals = frame->numActualArgs();
   unsigned numFormals = callee->nargs();
-  unsigned numArgs = Max(numActuals, numFormals);
+  unsigned numArgs = std::max(numActuals, numFormals);
   unsigned numBytes = ArgumentsData::bytesRequired(numArgs);
 
   ArgumentsData* data = reinterpret_cast<ArgumentsData*>(
       AllocateObjectBuffer<uint8_t>(cx, obj, numBytes));
   if (!data) {
     // Make the object safe for GC. Don't report OOM, the slow path will
     // retry the allocation.
     cx->recoverFromOutOfMemory();
--- a/js/src/vm/ArgumentsObject.h
+++ b/js/src/vm/ArgumentsObject.h
@@ -53,17 +53,17 @@ class RareArgumentsData {
 };
 
 // ArgumentsData stores the initial indexed arguments provided to a function
 // call. It is used to store arguments[i] -- up until the corresponding
 // property is modified, when the relevant value is flagged to memorialize the
 // modification.
 struct ArgumentsData {
   /*
-   * numArgs = Max(numFormalArgs, numActualArgs)
+   * numArgs = std::max(numFormalArgs, numActualArgs)
    * The array 'args' has numArgs elements.
    */
   uint32_t numArgs;
 
   RareArgumentsData* rareData;
 
   /*
    * This array holds either the current argument value or the magic
--- a/js/src/vm/ArrayBufferObject.cpp
+++ b/js/src/vm/ArrayBufferObject.cpp
@@ -12,16 +12,17 @@
 #include "mozilla/Attributes.h"
 #include "mozilla/CheckedInt.h"
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/Likely.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/PodOperations.h"
 #include "mozilla/TaggedAnonymousMemory.h"
 
+#include <algorithm>
 #include <string.h>
 #ifndef XP_WIN
 #  include <sys/mman.h>
 #endif
 #ifdef MOZ_VALGRIND
 #  include <valgrind/memcheck.h>
 #endif
 
@@ -717,18 +718,18 @@ static bool CreateSpecificWasmBuffer(
 #else
     static_assert(sizeof(uintptr_t) == 4, "assuming not 64 bit implies 32 bit");
 
     // On 32-bit platforms, prevent applications specifying a large max
     // (like UINT32_MAX) from unintentially OOMing the browser: they just
     // want "a lot of memory". Maintain the invariant that
     // initialSize <= clampedMaxSize.
     static const uint32_t OneGiB = 1 << 30;
-    uint32_t clamp = Max(OneGiB, initialSize);
-    clampedMaxSize = Some(Min(clamp, *clampedMaxSize));
+    uint32_t clamp = std::max(OneGiB, initialSize);
+    clampedMaxSize = Some(std::min(clamp, *clampedMaxSize));
 #endif
   }
 
   Maybe<size_t> mappedSize;
 
 #ifdef WASM_SUPPORTS_HUGE_MEMORY
   if (useHugeMemory) {
     mappedSize = Some(wasm::HugeMappedSize);
--- a/js/src/vm/DateTime.cpp
+++ b/js/src/vm/DateTime.cpp
@@ -306,17 +306,17 @@ int32_t js::DateTimeInfo::getOrComputeVa
   }
 
   range.oldOffsetMilliseconds = range.offsetMilliseconds;
   range.oldStartSeconds = range.startSeconds;
   range.oldEndSeconds = range.endSeconds;
 
   if (range.startSeconds <= seconds) {
     int64_t newEndSeconds =
-        Min(range.endSeconds + RangeExpansionAmount, MaxTimeT);
+        std::min({range.endSeconds + RangeExpansionAmount, MaxTimeT});
     if (newEndSeconds >= seconds) {
       int32_t endOffsetMilliseconds = (this->*compute)(newEndSeconds);
       if (endOffsetMilliseconds == range.offsetMilliseconds) {
         range.endSeconds = newEndSeconds;
         return range.offsetMilliseconds;
       }
 
       range.offsetMilliseconds = (this->*compute)(seconds);
@@ -330,17 +330,17 @@ int32_t js::DateTimeInfo::getOrComputeVa
     }
 
     range.offsetMilliseconds = (this->*compute)(seconds);
     range.startSeconds = range.endSeconds = seconds;
     return range.offsetMilliseconds;
   }
 
   int64_t newStartSeconds =
-      Max<int64_t>(range.startSeconds - RangeExpansionAmount, MinTimeT);
+      std::max<int64_t>({range.startSeconds - RangeExpansionAmount, MinTimeT});
   if (newStartSeconds <= seconds) {
     int32_t startOffsetMilliseconds = (this->*compute)(newStartSeconds);
     if (startOffsetMilliseconds == range.offsetMilliseconds) {
       range.startSeconds = newStartSeconds;
       return range.offsetMilliseconds;
     }
 
     range.offsetMilliseconds = (this->*compute)(seconds);
--- a/js/src/vm/HelperThreads.cpp
+++ b/js/src/vm/HelperThreads.cpp
@@ -6,16 +6,18 @@
 
 #include "vm/HelperThreads.h"
 
 #include "mozilla/Maybe.h"
 #include "mozilla/ScopeExit.h"
 #include "mozilla/Unused.h"
 #include "mozilla/Utf8.h"  // mozilla::Utf8Unit
 
+#include <algorithm>
+
 #include "builtin/Promise.h"
 #include "frontend/BytecodeCompilation.h"
 #include "jit/IonBuilder.h"
 #include "js/ContextOptions.h"  // JS::ContextOptions
 #include "js/SourceText.h"
 #include "js/UniquePtr.h"
 #include "js/Utility.h"
 #include "threading/CpuCount.h"
@@ -94,24 +96,24 @@ bool js::EnsureHelperThreadsInitialized(
 }
 
 static size_t ClampDefaultCPUCount(size_t cpuCount) {
   // It's extremely rare for SpiderMonkey to have more than a few cores worth
   // of work. At higher core counts, performance can even decrease due to NUMA
   // (and SpiderMonkey's lack of NUMA-awareness), contention, and general lack
   // of optimization for high core counts. So to avoid wasting thread stack
   // resources (and cluttering gdb and core dumps), clamp to 8 cores for now.
-  return Min<size_t>(cpuCount, 8);
+  return std::min<size_t>(cpuCount, 8);
 }
 
 static size_t ThreadCountForCPUCount(size_t cpuCount) {
   // We need at least two threads for tier-2 wasm compilations, because
   // there's a master task that holds a thread while other threads do the
   // compilation.
-  return Max<size_t>(cpuCount, 2);
+  return std::max<size_t>(cpuCount, 2);
 }
 
 bool js::SetFakeCPUCount(size_t count) {
   // This must be called before the threads have been initialized.
   MOZ_ASSERT(!HelperThreadState().threads);
 
   HelperThreadState().cpuCount = count;
   HelperThreadState().threadCount = ThreadCountForCPUCount(count);
--- a/js/src/vm/JSFunction.cpp
+++ b/js/src/vm/JSFunction.cpp
@@ -11,16 +11,17 @@
 #include "vm/JSFunction-inl.h"
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/CheckedInt.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/Range.h"
 #include "mozilla/Utf8.h"
 
+#include <algorithm>
 #include <string.h>
 
 #include "jsapi.h"
 #include "jstypes.h"
 
 #include "builtin/Array.h"
 #include "builtin/BigInt.h"
 #include "builtin/Eval.h"
@@ -1440,34 +1441,35 @@ bool JSFunction::finishBoundFunctionInit
   if (targetObj->is<JSFunction>() &&
       !targetObj->as<JSFunction>().hasResolvedLength()) {
     RootedValue targetLength(cx);
     if (!JSFunction::getUnresolvedLength(cx, targetObj.as<JSFunction>(),
                                          &targetLength)) {
       return false;
     }
 
-    length = Max(0.0, targetLength.toNumber() - argCount);
+    length = std::max(0.0, targetLength.toNumber() - argCount);
   } else {
     // 19.2.3.2 Function.prototype.bind, step 5.
     bool hasLength;
     RootedId idRoot(cx, NameToId(cx->names().length));
     if (!HasOwnProperty(cx, targetObj, idRoot, &hasLength)) {
       return false;
     }
 
     // 19.2.3.2 Function.prototype.bind, step 6.
     if (hasLength) {
       RootedValue targetLength(cx);
       if (!GetProperty(cx, targetObj, targetObj, idRoot, &targetLength)) {
         return false;
       }
 
       if (targetLength.isNumber()) {
-        length = Max(0.0, JS::ToInteger(targetLength.toNumber()) - argCount);
+        length =
+            std::max(0.0, JS::ToInteger(targetLength.toNumber()) - argCount);
       }
     }
 
     // 19.2.3.2 Function.prototype.bind, step 7 (implicit).
   }
 
   // 19.2.3.2 Function.prototype.bind, step 8.
   bound->setExtendedSlot(BOUND_FUN_LENGTH_SLOT, NumberValue(length));
--- a/js/src/vm/JSScript.cpp
+++ b/js/src/vm/JSScript.cpp
@@ -2864,18 +2864,18 @@ struct UnretrievableSourceDecoder {
   UnretrievableSourceDecoder(XDRState<XDR_DECODE>* xdr,
                              ScriptSource* scriptSource,
                              uint32_t uncompressedLength)
       : xdr_(xdr),
         scriptSource_(scriptSource),
         uncompressedLength_(uncompressedLength) {}
 
   XDRResult decode() {
-    auto sourceUnits =
-        xdr_->cx()->make_pod_array<Unit>(Max<size_t>(uncompressedLength_, 1));
+    auto sourceUnits = xdr_->cx()->make_pod_array<Unit>(
+        std::max<size_t>(uncompressedLength_, 1));
     if (!sourceUnits) {
       return xdr_->fail(JS::TranscodeResult_Throw);
     }
 
     MOZ_TRY(xdr_->codeChars(sourceUnits.get(), uncompressedLength_));
 
     if (!scriptSource_->initializeUnretrievableUncompressedSource(
             xdr_->cx(), std::move(sourceUnits), uncompressedLength_)) {
@@ -3050,18 +3050,18 @@ XDRResult ScriptSource::codeBinASTData(X
   if (mode == XDR_ENCODE) {
     binASTLength = ss->data.as<BinAST>().string.length();
   }
   MOZ_TRY(xdr->codeUint32(&binASTLength));
 
   // XDR the BinAST data.
   Maybe<SharedImmutableString> binASTData;
   if (mode == XDR_DECODE) {
-    auto bytes =
-        xdr->cx()->template make_pod_array<char>(Max<size_t>(binASTLength, 1));
+    auto bytes = xdr->cx()->template make_pod_array<char>(
+        std::max<size_t>(binASTLength, 1));
     if (!bytes) {
       return xdr->fail(JS::TranscodeResult_Throw);
     }
     MOZ_TRY(xdr->codeBytes(bytes.get(), binASTLength));
 
     auto& cache =
         xdr->cx()->zone()->runtimeFromAnyThread()->sharedImmutableStrings();
     binASTData = cache.getOrCreate(std::move(bytes), binASTLength);
--- a/js/src/vm/MemoryMetrics.cpp
+++ b/js/src/vm/MemoryMetrics.cpp
@@ -1,16 +1,18 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "js/MemoryMetrics.h"
 
+#include <algorithm>
+
 #include "gc/GC.h"
 #include "gc/Heap.h"
 #include "gc/Nursery.h"
 #include "gc/PublicIterators.h"
 #include "jit/BaselineJIT.h"
 #include "jit/Ion.h"
 #include "util/Text.h"
 #include "vm/ArrayObject.h"
@@ -129,17 +131,17 @@ static void StoreStringChars(char* buffe
   // We might truncate |str| even if it's much shorter than 1024 chars, if
   // |str| contains unicode chars.  Since this is just for a memory reporter,
   // we don't care.
   PutEscapedString(buffer, bufferSize, chars, str->length(), /* quote */ 0);
 }
 
 NotableStringInfo::NotableStringInfo(JSString* str, const StringInfo& info)
     : StringInfo(info), length(str->length()) {
-  size_t bufferSize = Min(str->length() + 1, size_t(MAX_SAVED_CHARS));
+  size_t bufferSize = std::min(str->length() + 1, size_t(MAX_SAVED_CHARS));
   buffer.reset(js_pod_malloc<char>(bufferSize));
   if (!buffer) {
     MOZ_CRASH("oom");
   }
 
   if (str->hasLatin1Chars()) {
     StoreStringChars<Latin1Char>(buffer.get(), bufferSize, str);
   } else {
--- a/js/src/vm/NativeObject.cpp
+++ b/js/src/vm/NativeObject.cpp
@@ -7,16 +7,18 @@
 #include "vm/NativeObject-inl.h"
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/Casting.h"
 #include "mozilla/CheckedInt.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Maybe.h"
 
+#include <algorithm>
+
 #include "debugger/DebugAPI.h"
 #include "gc/Marking.h"
 #include "jit/BaselineIC.h"
 #include "js/CharacterEncoding.h"
 #include "js/Result.h"
 #include "js/Value.h"
 #include "vm/EqualityOperations.h"  // js::SameValue
 #include "vm/TypedArrayObject.h"
@@ -529,17 +531,17 @@ DenseElementResult NativeObject::maybeDe
 
   RootedShape shape(cx, obj->lastProperty());
   while (!shape->isEmptyShape()) {
     uint32_t index;
     if (IdIsIndex(shape->propid(), &index)) {
       if (shape->attributes() == JSPROP_ENUMERATE &&
           shape->hasDefaultGetter() && shape->hasDefaultSetter()) {
         numDenseElements++;
-        newInitializedLength = Max(newInitializedLength, index + 1);
+        newInitializedLength = std::max(newInitializedLength, index + 1);
       } else {
         /*
          * For simplicity, only densify the object if all indexed
          * properties can be converted to dense elements.
          */
         return DenseElementResult::Incomplete;
       }
     }
@@ -695,17 +697,17 @@ bool NativeObject::tryUnshiftDenseElemen
 
     // Give up if we need to allocate more elements.
     if (toShift > unusedCapacity) {
       return false;
     }
 
     // Move more elements than we need, so that other unshift calls will be
     // fast. We just have to make sure we don't exceed unusedCapacity.
-    toShift = Min(toShift + unusedCapacity / 2, unusedCapacity);
+    toShift = std::min(toShift + unusedCapacity / 2, unusedCapacity);
 
     // Ensure |numShifted + toShift| does not exceed MaxShiftedElements.
     if (numShifted + toShift > ObjectElements::MaxShiftedElements) {
       toShift = ObjectElements::MaxShiftedElements - numShifted;
     }
 
     MOZ_ASSERT(count <= numShifted + toShift);
     MOZ_ASSERT(numShifted + toShift <= ObjectElements::MaxShiftedElements);
--- a/js/src/vm/NativeObject.h
+++ b/js/src/vm/NativeObject.h
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef vm_NativeObject_h
 #define vm_NativeObject_h
 
 #include "mozilla/Assertions.h"
 #include "mozilla/Attributes.h"
 
+#include <algorithm>
 #include <stdint.h>
 
 #include "jsfriendapi.h"
 #include "NamespaceImports.h"
 
 #include "gc/Barrier.h"
 #include "gc/Heap.h"
 #include "gc/Marking.h"
@@ -726,17 +727,17 @@ class NativeObject : public JSObject {
   // Get the number of fixed slots when the shape pointer may have been
   // forwarded by a moving GC. You need to use this rather that
   // numFixedSlots() in a trace hook if you access an object that is not the
   // object being traced, since it may have a stale shape pointer.
   inline uint32_t numFixedSlotsMaybeForwarded() const;
 
   uint32_t numUsedFixedSlots() const {
     uint32_t nslots = lastProperty()->slotSpan(getClass());
-    return Min(nslots, numFixedSlots());
+    return std::min(nslots, numFixedSlots());
   }
 
   uint32_t slotSpan() const {
     if (inDictionaryMode()) {
       return lastProperty()->base()->slotSpan();
     }
     return lastProperty()->slotSpan();
   }
--- a/js/src/vm/RegExpObject.cpp
+++ b/js/src/vm/RegExpObject.cpp
@@ -4,16 +4,18 @@
  * 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 "vm/RegExpObject.h"
 
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/PodOperations.h"
 
+#include <algorithm>
+
 #ifdef DEBUG
 #  include "jsutil.h"
 #endif
 
 #include "builtin/RegExp.h"
 #include "builtin/SelfHostingDefines.h"  // REGEXP_*_FLAG
 #include "frontend/TokenStream.h"
 #include "gc/HashUtil.h"
@@ -583,31 +585,31 @@ bool RegExpShared::dumpBytecode(JSContex
   };
 
 #  define BYTECODE(NAME)      \
     case irregexp::BC_##NAME: \
       DumpLower(#NAME);
 #  define ADVANCE(NAME)                 \
     fprintf(stderr, "\n");              \
     pc += irregexp::BC_##NAME##_LENGTH; \
-    maxPc = js::Max(maxPc, pc);         \
+    maxPc = std::max(maxPc, pc);        \
     break;
 #  define STOP(NAME)                    \
     fprintf(stderr, "\n");              \
     pc += irregexp::BC_##NAME##_LENGTH; \
     break;
-#  define JUMP(NAME, OFFSET)                   \
-    fprintf(stderr, "\n");                     \
-    maxPc = js::Max(maxPc, byteCode + OFFSET); \
-    pc += irregexp::BC_##NAME##_LENGTH;        \
+#  define JUMP(NAME, OFFSET)                    \
+    fprintf(stderr, "\n");                      \
+    maxPc = std::max(maxPc, byteCode + OFFSET); \
+    pc += irregexp::BC_##NAME##_LENGTH;         \
     break;
-#  define BRANCH(NAME, OFFSET)                              \
-    fprintf(stderr, "\n");                                  \
-    pc += irregexp::BC_##NAME##_LENGTH;                     \
-    maxPc = js::Max(maxPc, js::Max(pc, byteCode + OFFSET)); \
+#  define BRANCH(NAME, OFFSET)                                \
+    fprintf(stderr, "\n");                                    \
+    pc += irregexp::BC_##NAME##_LENGTH;                       \
+    maxPc = std::max(maxPc, std::max(pc, byteCode + OFFSET)); \
     break;
 
   // Bytecode has no end marker, we need to calculate the bytecode length by
   // tracing jumps and branches.
   const uint8_t* maxPc = pc;
   while (pc <= maxPc) {
     fprintf(stderr, "%05d:  ", int32_t(pc - byteCode));
     int32_t insn = Load32Aligned(pc);
--- a/js/src/vm/RegExpObject.h
+++ b/js/src/vm/RegExpObject.h
@@ -45,16 +45,26 @@ namespace frontend {
 class TokenStreamAnyChars;
 }
 
 // Temporary definitions until irregexp is updated from upstream.
 namespace irregexp {
 constexpr size_t JS_HOWMANY(size_t x, size_t y) { return (x + y - 1) / y; }
 
 constexpr size_t JS_ROUNDUP(size_t x, size_t y) { return JS_HOWMANY(x, y) * y; }
+
+template <class T>
+static constexpr inline T Min(T t1, T t2) {
+  return t1 < t2 ? t1 : t2;
+}
+
+template <class T>
+static constexpr inline T Max(T t1, T t2) {
+  return t1 > t2 ? t1 : t2;
+}
 }  // namespace irregexp
 
 extern RegExpObject* RegExpAlloc(JSContext* cx, NewObjectKind newKind,
                                  HandleObject proto = nullptr);
 
 extern JSObject* CloneRegExpObject(JSContext* cx, Handle<RegExpObject*> regex);
 
 class RegExpObject : public NativeObject {
--- a/js/src/vm/Shape.h
+++ b/js/src/vm/Shape.h
@@ -10,16 +10,18 @@
 #include "mozilla/Attributes.h"
 #include "mozilla/GuardObjects.h"
 #include "mozilla/HashFunctions.h"
 #include "mozilla/MathAlgorithms.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/TemplateLib.h"
 
+#include <algorithm>
+
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "jstypes.h"
 #include "NamespaceImports.h"
 
 #include "gc/Barrier.h"
 #include "gc/FreeOp.h"
 #include "gc/Heap.h"
@@ -1233,17 +1235,17 @@ class Shape : public gc::TenuredCell {
   }
 
   uint32_t slotSpan(const JSClass* clasp) const {
     MOZ_ASSERT(!inDictionary());
     // Proxy classes have reserved slots, but proxies manage their own slot
     // layout. This means all non-native object shapes have nfixed == 0 and
     // slotSpan == 0.
     uint32_t free = clasp->isProxy() ? 0 : JSSLOT_FREE(clasp);
-    return hasMissingSlot() ? free : Max(free, maybeSlot() + 1);
+    return hasMissingSlot() ? free : std::max(free, maybeSlot() + 1);
   }
 
   uint32_t slotSpan() const { return slotSpan(getObjectClass()); }
 
   void setSlot(uint32_t slot) {
     MOZ_ASSERT(slot <= SHAPE_INVALID_SLOT);
     immutableFlags = (immutableFlags & ~Shape::SLOT_MASK) | slot;
   }
--- a/js/src/vm/Stack.cpp
+++ b/js/src/vm/Stack.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "vm/Stack-inl.h"
 
+#include <algorithm>
 #include <utility>
 
 #include "debugger/DebugAPI.h"
 #include "gc/Marking.h"
 #include "jit/BaselineFrame.h"
 #include "jit/JitcodeMap.h"
 #include "jit/JitRealm.h"
 #include "jit/shared/CodeGenerator-shared.h"
@@ -340,17 +341,17 @@ void InterpreterFrame::trace(JSTracer* t
 
   if (hasArgs()) {
     // Trace the callee and |this|. When we're doing a moving GC, we
     // need to fix up the callee pointer before we use it below, under
     // numFormalArgs() and script().
     TraceRootRange(trc, 2, argv_ - 2, "fp callee and this");
 
     // Trace arguments.
-    unsigned argc = Max(numActualArgs(), numFormalArgs());
+    unsigned argc = std::max(numActualArgs(), numFormalArgs());
     TraceRootRange(trc, argc + isConstructing(), argv_, "fp argv");
   } else {
     // Trace newTarget.
     TraceRoot(trc, ((Value*)this) - 1, "stack newTarget");
   }
 
   JSScript* script = this->script();
   size_t nfixed = script->nfixed();
--- a/js/src/vm/Stack.h
+++ b/js/src/vm/Stack.h
@@ -9,16 +9,18 @@
 
 #include "mozilla/Atomics.h"
 #include "mozilla/HashFunctions.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/MaybeOneOf.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/Variant.h"
 
+#include <algorithm>
+
 #include "jsutil.h"
 
 #include "gc/Rooting.h"
 #ifdef CHECK_OSIPOINT_REGISTERS
 #  include "jit/Registers.h"  // for RegisterDump
 #endif
 #include "jit/JSJitFrameIter.h"
 #include "js/RootingAPI.h"
@@ -644,17 +646,17 @@ class InterpreterFrame {
 
     MOZ_ASSERT(isFunctionFrame());
 
     if (callee().isArrow()) {
       return callee().getExtendedSlot(FunctionExtended::ARROW_NEWTARGET_SLOT);
     }
 
     if (isConstructing()) {
-      unsigned pushedArgs = Max(numFormalArgs(), numActualArgs());
+      unsigned pushedArgs = std::max(numFormalArgs(), numActualArgs());
       return argv()[pushedArgs];
     }
     return UndefinedValue();
   }
 
   /* Profiler flags */
 
   bool hasPushedGeckoProfilerFrame() {
--- a/js/src/vm/StructuredClone.cpp
+++ b/js/src/vm/StructuredClone.cpp
@@ -1162,17 +1162,17 @@ bool JSStructuredCloneWriter::writeBigIn
   return out.writeArray(bi->digits().data(), length);
 }
 
 inline void JSStructuredCloneWriter::checkStack() {
 #ifdef DEBUG
   // To avoid making serialization O(n^2), limit stack-checking at 10.
   const size_t MAX = 10;
 
-  size_t limit = Min(counts.length(), MAX);
+  size_t limit = std::min(counts.length(), MAX);
   MOZ_ASSERT(objs.length() == counts.length());
   size_t total = 0;
   for (size_t i = 0; i < limit; i++) {
     MOZ_ASSERT(total + counts[i] >= total);
     total += counts[i];
   }
   if (counts.length() <= MAX) {
     MOZ_ASSERT(total == objectEntries.length() + otherEntries.length());
--- a/js/src/vm/Time.cpp
+++ b/js/src/vm/Time.cpp
@@ -9,16 +9,17 @@
 #include "vm/Time.h"
 
 #include "mozilla/DebugOnly.h"
 #include "mozilla/MathAlgorithms.h"
 
 #ifdef SOLARIS
 #  define _REENTRANT 1
 #endif
+#include <algorithm>
 #include <string.h>
 #include <time.h>
 
 #include "jstypes.h"
 #include "jsutil.h"
 
 #ifdef XP_WIN
 #  include <windef.h>
@@ -45,17 +46,17 @@ static int64_t PRMJ_NowImpl();
 
 int64_t PRMJ_Now() {
   if (mozilla::TimeStamp::GetFuzzyfoxEnabled()) {
     return mozilla::TimeStamp::NowFuzzyTime();
   }
 
   // We check the FuzzyFox clock in case it was recently disabled, to prevent
   // time from going backwards.
-  return js::Max(PRMJ_NowImpl(), mozilla::TimeStamp::NowFuzzyTime());
+  return std::max(PRMJ_NowImpl(), mozilla::TimeStamp::NowFuzzyTime());
 }
 
 #if defined(XP_UNIX)
 static int64_t PRMJ_NowImpl() {
   struct timeval tv;
 
 #  ifdef _SVID_GETTOD /* Defined only on Solaris, see Solaris <sys/types.h> */
   gettimeofday(&tv);
--- a/js/src/vm/TypeInference.cpp
+++ b/js/src/vm/TypeInference.cpp
@@ -9,16 +9,17 @@
 #include "mozilla/DebugOnly.h"
 #include "mozilla/IntegerPrintfMacros.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/Move.h"
 #include "mozilla/PodOperations.h"
 #include "mozilla/ScopeExit.h"
 #include "mozilla/Sprintf.h"
 
+#include <algorithm>
 #include <new>
 
 #include "jsapi.h"
 
 #include "gc/HashUtil.h"
 #include "jit/BaselineIC.h"
 #include "jit/BaselineJIT.h"
 #include "jit/CompileInfo.h"
@@ -3813,17 +3814,17 @@ bool TypeNewScript::maybeAnalyze(JSConte
     // For now, we require all preliminary objects to have only simple
     // lineages of plain data properties.
     Shape* shape = obj->lastProperty();
     if (shape->inDictionary() || !OnlyHasDataProperties(shape) ||
         shape->getObjectFlags() != 0) {
       return true;
     }
 
-    maxSlotSpan = Max<size_t>(maxSlotSpan, obj->slotSpan());
+    maxSlotSpan = std::max<size_t>(maxSlotSpan, obj->slotSpan());
 
     if (prefixShape) {
       MOZ_ASSERT(shape->numFixedSlots() == prefixShape->numFixedSlots());
       prefixShape = CommonPrefix(prefixShape, shape);
     } else {
       prefixShape = shape;
     }
     if (prefixShape->isEmptyShape()) {
--- a/js/src/vm/TypedArrayObject-inl.h
+++ b/js/src/vm/TypedArrayObject-inl.h
@@ -411,17 +411,17 @@ class ElementSpecific {
     MOZ_ASSERT(!source->is<TypedArrayObject>(),
                "use setFromTypedArray instead of this method");
 
     uint32_t i = 0;
     if (source->isNative()) {
       // Attempt fast-path infallible conversion of dense elements up to
       // the first potentially side-effectful lookup or conversion.
       uint32_t bound =
-          Min(source->as<NativeObject>().getDenseInitializedLength(), len);
+          std::min(source->as<NativeObject>().getDenseInitializedLength(), len);
 
       SharedMem<T*> dest =
           target->dataPointerEither().template cast<T*>() + offset;
 
       MOZ_ASSERT(!canConvertInfallibly(MagicValue(JS_ELEMENTS_HOLE)),
                  "the following loop must abort on holes");
 
       const Value* srcValues = source->as<NativeObject>().getDenseElements();
@@ -443,17 +443,17 @@ class ElementSpecific {
         return false;
       }
 
       T n;
       if (!valueToNative(cx, v, &n)) {
         return false;
       }
 
-      len = Min(len, target->length());
+      len = std::min(len, target->length());
       if (i >= len) {
         break;
       }
 
       // Compute every iteration in case getElement/valueToNative
       // detaches the underlying array buffer or GC moves the data.
       SharedMem<T*> dest =
           target->dataPointerEither().template cast<T*>() + offset + i;
--- a/js/src/wasm/AsmJS.cpp
+++ b/js/src/wasm/AsmJS.cpp
@@ -23,16 +23,17 @@
 #include "mozilla/Compression.h"
 #include "mozilla/MathAlgorithms.h"
 #include "mozilla/ScopeExit.h"
 #include "mozilla/Sprintf.h"  // SprintfLiteral
 #include "mozilla/Unused.h"
 #include "mozilla/Utf8.h"  // mozilla::Utf8Unit
 #include "mozilla/Variant.h"
 
+#include <algorithm>
 #include <new>
 
 #include "jsmath.h"
 #include "jsutil.h"
 
 #include "frontend/ParseNode.h"
 #include "frontend/Parser.h"
 #include "gc/Policy.h"
@@ -5669,18 +5670,18 @@ static bool CheckSwitchRange(FunctionVal
   ParseNode* initialStmt = stmt;
   for (stmt = NextNode(stmt); stmt && !IsDefaultCase(stmt);
        stmt = NextNode(stmt)) {
     int32_t i = 0;
     if (!CheckCaseExpr(f, CaseExpr(stmt), &i)) {
       return false;
     }
 
-    *low = Min(*low, i);
-    *high = Max(*high, i);
+    *low = std::min(*low, i);
+    *high = std::max(*high, i);
   }
 
   int64_t i64 = (int64_t(*high) - int64_t(*low)) + 1;
   if (i64 > MaxBrTableElems) {
     return f.fail(
         initialStmt,
         "all switch statements generate tables; this table would be too big");
   }
--- a/js/src/wasm/WasmBaselineCompile.cpp
+++ b/js/src/wasm/WasmBaselineCompile.cpp
@@ -106,16 +106,17 @@
  *   to memory by the pre-block sync() call.)
  */
 
 #include "wasm/WasmBaselineCompile.h"
 
 #include "mozilla/MathAlgorithms.h"
 #include "mozilla/Maybe.h"
 
+#include <algorithm>
 #include <utility>
 
 #include "jit/AtomicOp.h"
 #include "jit/IonTypes.h"
 #include "jit/JitAllocPolicy.h"
 #include "jit/Label.h"
 #include "jit/MacroAssembler.h"
 #include "jit/MIR.h"
@@ -1665,43 +1666,43 @@ class BaseStackFrame final : public Base
   uint32_t pushPtr(Register r) {
     DebugOnly<uint32_t> stackBefore = currentStackHeight();
 #ifdef RABALDR_CHUNKY_STACK
     pushChunkyBytes(StackSizeOfPtr);
     masm.storePtr(r, Address(sp_, stackOffset(currentStackHeight())));
 #else
     masm.Push(r);
 #endif
-    maxFramePushed_ = Max(maxFramePushed_, masm.framePushed());
+    maxFramePushed_ = std::max(maxFramePushed_, masm.framePushed());
     MOZ_ASSERT(stackBefore + StackSizeOfPtr == currentStackHeight());
     return currentStackHeight();
   }
 
   uint32_t pushFloat32(FloatRegister r) {
     DebugOnly<uint32_t> stackBefore = currentStackHeight();
 #ifdef RABALDR_CHUNKY_STACK
     pushChunkyBytes(StackSizeOfFloat);
     masm.storeFloat32(r, Address(sp_, stackOffset(currentStackHeight())));
 #else
     masm.Push(r);
 #endif
-    maxFramePushed_ = Max(maxFramePushed_, masm.framePushed());
+    maxFramePushed_ = std::max(maxFramePushed_, masm.framePushed());
     MOZ_ASSERT(stackBefore + StackSizeOfFloat == currentStackHeight());
     return currentStackHeight();
   }
 
   uint32_t pushDouble(FloatRegister r) {
     DebugOnly<uint32_t> stackBefore = currentStackHeight();
 #ifdef RABALDR_CHUNKY_STACK
     pushChunkyBytes(StackSizeOfDouble);
     masm.storeDouble(r, Address(sp_, stackOffset(currentStackHeight())));
 #else
     masm.Push(r);
 #endif
-    maxFramePushed_ = Max(maxFramePushed_, masm.framePushed());
+    maxFramePushed_ = std::max(maxFramePushed_, masm.framePushed());
     MOZ_ASSERT(stackBefore + StackSizeOfDouble == currentStackHeight());
     return currentStackHeight();
   }
 
   void popPtr(Register r) {
     DebugOnly<uint32_t> stackBefore = currentStackHeight();
 #ifdef RABALDR_CHUNKY_STACK
     masm.loadPtr(Address(sp_, stackOffset(currentStackHeight())), r);
@@ -1782,17 +1783,17 @@ class BaseStackFrame final : public Base
     uint32_t end = computeHeightWithStackResults(stackBase, stackResultBytes);
     if (currentStackHeight() < end) {
       uint32_t bytes = end - currentStackHeight();
 #ifdef RABALDR_CHUNKY_STACK
       pushChunkyBytes(bytes);
 #else
       masm.reserveStack(bytes);
 #endif
-      maxFramePushed_ = Max(maxFramePushed_, masm.framePushed());
+      maxFramePushed_ = std::max(maxFramePushed_, masm.framePushed());
     }
     return end;
   }
 
   void finishStackResultArea(StackHeight stackBase, uint32_t stackResultBytes) {
     uint32_t end = computeHeightWithStackResults(stackBase, stackResultBytes);
     MOZ_ASSERT(currentStackHeight() >= end);
     popBytes(currentStackHeight() - end);
--- a/js/src/wasm/WasmCode.cpp
+++ b/js/src/wasm/WasmCode.cpp
@@ -16,16 +16,18 @@
  * limitations under the License.
  */
 
 #include "wasm/WasmCode.h"
 
 #include "mozilla/BinarySearch.h"
 #include "mozilla/EnumeratedRange.h"
 
+#include <algorithm>
+
 #include "jit/ExecutableAllocator.h"
 #ifdef JS_ION_PERF
 #  include "jit/PerfSpewer.h"
 #endif
 #ifdef MOZ_VTUNE
 #  include "vtune/VTuneWrapper.h"
 #endif
 #include "wasm/WasmModule.h"
@@ -689,17 +691,17 @@ bool LazyStubTier::createMany(const Uint
   if (masm.oom()) {
     return false;
   }
 
   size_t codeLength = LazyStubSegment::AlignBytesNeeded(masm.bytesNeeded());
 
   if (!stubSegments_.length() ||
       !stubSegments_[lastStubSegmentIndex_]->hasSpace(codeLength)) {
-    size_t newSegmentSize = Max(codeLength, ExecutableCodePageSize);
+    size_t newSegmentSize = std::max(codeLength, ExecutableCodePageSize);
     UniqueLazyStubSegment newSegment =
         LazyStubSegment::create(codeTier, newSegmentSize);
     if (!newSegment) {
       return false;
     }
     lastStubSegmentIndex_ = stubSegments_.length();
     if (!stubSegments_.emplaceBack(std::move(newSegment))) {
       return false;
--- a/js/src/wasm/WasmCompile.cpp
+++ b/js/src/wasm/WasmCompile.cpp
@@ -16,16 +16,18 @@
  * limitations under the License.
  */
 
 #include "wasm/WasmCompile.h"
 
 #include "mozilla/Maybe.h"
 #include "mozilla/Unused.h"
 
+#include <algorithm>
+
 #include "jit/ProcessExecutableMemory.h"
 #include "util/Text.h"
 #include "wasm/WasmBaselineCompile.h"
 #include "wasm/WasmCraneliftCompile.h"
 #include "wasm/WasmGenerator.h"
 #include "wasm/WasmIonCompile.h"
 #include "wasm/WasmOpIter.h"
 #include "wasm/WasmProcess.h"
@@ -382,17 +384,17 @@ static bool TieringBeneficial(uint32_t c
   // Compute the max number of threads available to do actual background
   // compilation work.
 
   uint32_t workers = HelperThreadState().maxWasmCompilationThreads();
 
   // The number of cores we will use is bounded both by the CPU count and the
   // worker count.
 
-  uint32_t cores = Min(cpuCount, workers);
+  uint32_t cores = std::min(cpuCount, workers);
 
   SystemClass cls = ClassifySystem();
 
   // Ion compilation on available cores must take long enough to be worth the
   // bother.
 
   double cutoffSize = CodesizeCutoff(cls);
   double effectiveCores = EffectiveCores(cores);
@@ -659,17 +661,17 @@ class StreamingDecoder {
 
   bool fail(const char* msg) { return d_.fail(msg); }
 
   bool done() const { return d_.done(); }
 
   size_t currentOffset() const { return d_.currentOffset(); }
 
   bool waitForBytes(size_t numBytes) {
-    numBytes = Min(numBytes, d_.bytesRemain());
+    numBytes = std::min(numBytes, d_.bytesRemain());
     const uint8_t* requiredEnd = d_.currentPosition() + numBytes;
     auto codeBytesEnd = codeBytesEnd_.lock();
     while (codeBytesEnd < requiredEnd) {
       if (cancelled_) {
         return false;
       }
       codeBytesEnd.wait();
     }
--- a/js/src/wasm/WasmGenerator.cpp
+++ b/js/src/wasm/WasmGenerator.cpp
@@ -214,17 +214,17 @@ bool ModuleGenerator::init(Metadata* may
   // extra conservative. Since large over-reservations may fail when the
   // actual allocations will succeed, ignore OOM failures. Note,
   // podResizeToFit calls at the end will trim off unneeded capacity.
 
   size_t codeSectionSize = env_->codeSection ? env_->codeSection->size : 0;
 
   size_t estimatedCodeSize =
       1.2 * EstimateCompiledCodeSize(tier(), codeSectionSize);
-  Unused << masm_.reserve(Min(estimatedCodeSize, MaxCodeBytesPerProcess));
+  Unused << masm_.reserve(std::min(estimatedCodeSize, MaxCodeBytesPerProcess));
 
   Unused << metadataTier_->codeRanges.reserve(2 * env_->numFuncDefs());
 
   const size_t ByteCodesPerCallSite = 50;
   Unused << metadataTier_->callSites.reserve(codeSectionSize /
                                              ByteCodesPerCallSite);
 
   const size_t ByteCodesPerOOBTrap = 10;
@@ -465,17 +465,17 @@ const CodeRange& ModuleGenerator::funcCo
   return cr;
 }
 
 static bool InRange(uint32_t caller, uint32_t callee) {
   // We assume JumpImmediateRange is defined conservatively enough that the
   // slight difference between 'caller' (which is really the return address
   // offset) and the actual base of the relative displacement computation
   // isn't significant.
-  uint32_t range = Min(JitOptions.jumpThreshold, JumpImmediateRange);
+  uint32_t range = std::min(JitOptions.jumpThreshold, JumpImmediateRange);
   if (caller < callee) {
     return callee - caller < range;
   }
   return caller - callee < range;
 }
 
 typedef HashMap<uint32_t, uint32_t, DefaultHasher<uint32_t>, SystemAllocPolicy>
     OffsetMap;
--- a/js/src/wasm/WasmInstance.cpp
+++ b/js/src/wasm/WasmInstance.cpp
@@ -13,16 +13,18 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 #include "wasm/WasmInstance.h"
 
+#include <algorithm>
+
 #include "jit/AtomicOperations.h"
 #include "jit/Disassemble.h"
 #include "jit/InlinableNatives.h"
 #include "jit/JitCommon.h"
 #include "jit/JitRealm.h"
 #include "jit/JitScript.h"
 #include "util/StringBuffer.h"
 #include "util/Text.h"
@@ -194,17 +196,17 @@ bool Instance::callImport(JSContext* cx,
 
   // Functions with anyref in signature don't have a jit exit at the moment.
   if (fi.funcType().temporarilyUnsupportedAnyRef()) {
     return true;
   }
 
   const ValTypeVector& importArgs = fi.funcType().args();
 
-  size_t numKnownArgs = Min(importArgs.length(), importFun->nargs());
+  size_t numKnownArgs = std::min(importArgs.length(), importFun->nargs());
   for (uint32_t i = 0; i < numKnownArgs; i++) {
     TypeSet::Type type = TypeSet::UnknownType();
     switch (importArgs[i].code()) {
       case ValType::I32:
         type = TypeSet::Int32Type();
         break;
       case ValType::F32:
         type = TypeSet::DoubleType();
@@ -1641,17 +1643,17 @@ bool Instance::callExport(JSContext* cx,
   // array of 16-byte values where each value contains either a coerced int32
   // (in the low word), or a double value (in the low dword) value, with the
   // coercions specified by the wasm signature. The external entry point
   // unpacks this array into the system-ABI-specified registers and stack
   // memory and then calls into the internal entry point. The return value is
   // stored in the first element of the array (which, therefore, must have
   // length >= 1).
   Vector<ExportArg, 8> exportArgs(cx);
-  if (!exportArgs.resize(Max<size_t>(1, funcType->args().length()))) {
+  if (!exportArgs.resize(std::max<size_t>(1, funcType->args().length()))) {
     return false;
   }
 
   ASSERT_ANYREF_IS_JSOBJECT;
   Rooted<GCVector<JSObject*, 8, SystemAllocPolicy>> refs(cx);
 
   DebugCodegen(DebugChannel::Function, "wasm-function[%d]; arguments ",
                funcIndex);
--- a/js/src/wasm/WasmIonCompile.cpp
+++ b/js/src/wasm/WasmIonCompile.cpp
@@ -15,16 +15,18 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 #include "wasm/WasmIonCompile.h"
 
 #include "mozilla/MathAlgorithms.h"
 
+#include <algorithm>
+
 #include "jit/CodeGenerator.h"
 
 #include "wasm/WasmBaselineCompile.h"
 #include "wasm/WasmBuiltins.h"
 #include "wasm/WasmGC.h"
 #include "wasm/WasmGenerator.h"
 #include "wasm/WasmOpIter.h"
 #include "wasm/WasmSignalHandlers.h"
@@ -1010,17 +1012,17 @@ class FunctionCompiler {
 
     if (!call->regArgs_.append(
             MWasmCall::Arg(AnyRegister(WasmTlsReg), tlsPointer_))) {
       return false;
     }
 
     uint32_t stackBytes = call->abi_.stackBytesConsumedSoFar();
 
-    maxStackArgBytes_ = Max(maxStackArgBytes_, stackBytes);
+    maxStackArgBytes_ = std::max(maxStackArgBytes_, stackBytes);
     return true;
   }
 
   // Wrappers for creating various kinds of calls.
 
   bool callDirect(const FuncType& funcType, uint32_t funcIndex,
                   uint32_t lineOrBytecode, const CallCompileState& call,
                   MDefinition** def) {
--- a/js/src/wasm/WasmJS.cpp
+++ b/js/src/wasm/WasmJS.cpp
@@ -18,16 +18,18 @@
 
 #include "wasm/WasmJS.h"
 
 #include "mozilla/CheckedInt.h"
 #include "mozilla/EndianUtils.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/RangedPtr.h"
 
+#include <algorithm>
+
 #include "builtin/Promise.h"
 #include "builtin/TypedObject.h"
 #include "gc/FreeOp.h"
 #include "jit/AtomicOperations.h"
 #include "jit/JitOptions.h"
 #include "jit/Simulator.h"
 #include "js/Printf.h"
 #include "js/PropertySpec.h"  // JS_{PS,FN}{,_END}
@@ -1117,17 +1119,17 @@ static SharedCompileArgs InitCompileArgs
   }
 
   return CompileArgs::build(cx, std::move(scriptedCaller));
 }
 
 static bool ReportCompileWarnings(JSContext* cx,
                                   const UniqueCharsVector& warnings) {
   // Avoid spamming the console.
-  size_t numWarnings = Min<size_t>(warnings.length(), 3);
+  size_t numWarnings = std::min<size_t>(warnings.length(), 3);
 
   for (size_t i = 0; i < numWarnings; i++) {
     if (!JS_ReportErrorFlagsAndNumberASCII(
             cx, JSREPORT_WARNING, GetErrorMessage, nullptr,
             JSMSG_WASM_COMPILE_WARNING, warnings[i].get()))
       return false;
   }
 
@@ -3309,17 +3311,17 @@ class CompileStreamTask : public Promise
         if (extraBytes) {
           return consumeChunk(begin + length - extraBytes, extraBytes);
         }
 
         return true;
       }
       case Code: {
         size_t copyLength =
-            Min<size_t>(length, codeBytes_.end() - codeBytesEnd_);
+            std::min<size_t>(length, codeBytes_.end() - codeBytesEnd_);
         memcpy(codeBytesEnd_, begin, copyLength);
         codeBytesEnd_ += copyLength;
 
         {
           auto codeStreamEnd = exclusiveCodeBytesEnd_.lock();
           codeStreamEnd.get() = codeBytesEnd_;
           codeStreamEnd.notify_one();
         }
--- a/js/src/wasm/WasmStubs.cpp
+++ b/js/src/wasm/WasmStubs.cpp
@@ -15,16 +15,18 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 #include "wasm/WasmStubs.h"
 
 #include "mozilla/ArrayUtils.h"
 
+#include <algorithm>
+
 #include "jit/JitScript.h"
 #include "jit/RegisterAllocator.h"
 #include "js/Printf.h"
 #include "wasm/WasmCode.h"
 #include "wasm/WasmGenerator.h"
 #include "wasm/WasmInstance.h"
 
 #include "jit/MacroAssembler-inl.h"
@@ -747,17 +749,17 @@ static bool GenerateJitEntry(MacroAssemb
   unsigned normalBytesNeeded = StackArgBytes(fe.funcType().args());
 
   MIRTypeVector coerceArgTypes;
   MOZ_ALWAYS_TRUE(coerceArgTypes.append(MIRType::Int32));
   MOZ_ALWAYS_TRUE(coerceArgTypes.append(MIRType::Pointer));
   MOZ_ALWAYS_TRUE(coerceArgTypes.append(MIRType::Pointer));
   unsigned oolBytesNeeded = StackArgBytes(coerceArgTypes);
 
-  unsigned bytesNeeded = Max(normalBytesNeeded, oolBytesNeeded);
+  unsigned bytesNeeded = std::max(normalBytesNeeded, oolBytesNeeded);
 
   // Note the jit caller ensures the stack is aligned *after* the call
   // instruction.
   unsigned frameSize = StackDecrementForCall(WasmStackAlignment,
                                              masm.framePushed(), bytesNeeded);
 
   // Reserve stack space for wasm ABI arguments, set up like this:
   // <-- ABI args | padding
@@ -1539,17 +1541,17 @@ static bool GenerateImportInterpExit(Mac
 
   // At the point of the call, the stack layout shall be (sp grows to the left):
   //  | stack args | padding | argv[] | padding | retaddr | caller stack args |
   // The padding between stack args and argv ensures that argv is aligned. The
   // padding between argv and retaddr ensures that sp is aligned.
   unsigned argOffset =
       AlignBytes(StackArgBytes(invokeArgTypes), sizeof(double));
   unsigned argBytes =
-      Max<size_t>(1, fi.funcType().args().length()) * sizeof(Value);
+      std::max<size_t>(1, fi.funcType().args().length()) * sizeof(Value);
   unsigned framePushed =
       StackDecrementForCall(ABIStackAlignment,
                             sizeof(Frame),  // pushed by prologue
                             argOffset + argBytes);
 
   GenerateExitPrologue(masm, framePushed, ExitReason::Fixed::ImportInterp,
                        offsets);