Bug 1445302 - Replace TArray.RemoveElementAt(TArray.Length() - 1) pattern with TArray.RemoveLastElement() or TArray.PopLastElement() r=froydnj
authorMiko Mynttinen <mikokm@gmail.com>
Tue, 13 Mar 2018 14:51:33 +0100
changeset 409230 bceb565cfe14de56a10472e4965b4e9283b24307
parent 409229 bb4716acbe83e17359f97ad7f84bc89a42263759
child 409231 39cbb31ba54c27f3eed3dddc4385dfaee9a9af02
push id33680
push useraiakab@mozilla.com
push dateWed, 21 Mar 2018 19:11:51 +0000
treeherdermozilla-central@2e420fc68049 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersfroydnj
bugs1445302
milestone61.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 1445302 - Replace TArray.RemoveElementAt(TArray.Length() - 1) pattern with TArray.RemoveLastElement() or TArray.PopLastElement() r=froydnj MozReview-Commit-ID: rGjabnP2iz
accessible/base/TreeWalker.cpp
dom/animation/KeyframeUtils.cpp
dom/base/TimeoutManager.cpp
dom/base/nsDocumentEncoder.cpp
dom/base/nsFrameMessageManager.cpp
dom/base/nsHTMLContentSerializer.cpp
dom/base/nsXHTMLContentSerializer.cpp
dom/canvas/CanvasRenderingContext2D.cpp
dom/media/webrtc/MediaTrackConstraints.cpp
dom/workers/WorkerLoadInfo.cpp
dom/xbl/nsBindingManager.cpp
dom/xslt/base/txNamespaceMap.cpp
dom/xslt/xslt/txExecutionState.cpp
extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
gfx/gl/GLTextureImage.cpp
gfx/thebes/gfxContext.cpp
gfx/vr/gfxVRPuppet.cpp
image/DecodePool.cpp
image/imgLoader.cpp
ipc/mscom/Utils.cpp
layout/base/PresShell.cpp
layout/base/nsLayoutUtils.cpp
layout/base/nsStyleChangeList.h
layout/generic/ReflowInput.cpp
layout/generic/TextDrawTarget.h
layout/generic/nsFrame.cpp
layout/painting/RetainedDisplayListBuilder.cpp
layout/painting/nsDisplayList.h
layout/style/FontFaceSet.cpp
layout/style/nsFontFaceUtils.cpp
netwerk/cache2/CacheIndexIterator.cpp
netwerk/protocol/http/nsHttpChannel.cpp
parser/html/nsHtml5Highlighter.cpp
toolkit/components/places/History.cpp
widget/cocoa/TextInputHandler.h
widget/windows/TSFTextStore.cpp
xpcom/threads/DeadlockDetector.h
xpcom/threads/ThreadEventQueue.cpp
xpcom/threads/TimerThread.cpp
--- a/accessible/base/TreeWalker.cpp
+++ b/accessible/base/TreeWalker.cpp
@@ -340,12 +340,11 @@ TreeWalker::AccessibleFor(nsIContent* aN
   }
 
   return nullptr;
 }
 
 dom::AllChildrenIterator*
 TreeWalker::PopState()
 {
-  size_t length = mStateStack.Length();
-  mStateStack.RemoveElementAt(length - 1);
+  mStateStack.RemoveLastElement();
   return mStateStack.IsEmpty() ? nullptr : &mStateStack.LastElement();
 }
--- a/dom/animation/KeyframeUtils.cpp
+++ b/dom/animation/KeyframeUtils.cpp
@@ -1183,17 +1183,17 @@ HandleMissingFinalKeyframe(nsTArray<Anim
 
   // If the preference of the core Web Animations API is not enabled, don't fill
   // in the missing keyframe since the missing keyframe requires support for
   // additive animation which is guarded by this pref.
   if (!nsContentUtils::AnimationsAPICoreEnabled()) {
     // If we have already appended a new entry for the property so we have to
     // remove it.
     if (aCurrentAnimationProperty) {
-      aResult.RemoveElementAt(aResult.Length() - 1);
+      aResult.RemoveLastElement();
     }
     return;
   }
 
   // If |aCurrentAnimationProperty| is nullptr, that means this is the first
   // entry for the property, we have to append a new AnimationProperty for this
   // property.
   if (!aCurrentAnimationProperty) {
--- a/dom/base/TimeoutManager.cpp
+++ b/dom/base/TimeoutManager.cpp
@@ -151,17 +151,17 @@ TimeoutManager::CreateFiringId()
   return id;
 }
 
 void
 TimeoutManager::DestroyFiringId(uint32_t aFiringId)
 {
   MOZ_DIAGNOSTIC_ASSERT(!mFiringIdStack.IsEmpty());
   MOZ_DIAGNOSTIC_ASSERT(mFiringIdStack.LastElement() == aFiringId);
-  mFiringIdStack.RemoveElementAt(mFiringIdStack.Length() - 1);
+  mFiringIdStack.RemoveLastElement();
 }
 
 bool
 TimeoutManager::IsValidFiringId(uint32_t aFiringId) const
 {
   return !IsInvalidFiringId(aFiringId);
 }
 
--- a/dom/base/nsDocumentEncoder.cpp
+++ b/dom/base/nsDocumentEncoder.cpp
@@ -818,17 +818,17 @@ nsDocumentEncoder::SerializeRangeContext
   nsresult rv = NS_OK;
   for (nsINode* node : Reversed(serializedContext)) {
     rv = SerializeNodeEnd(node, aString);
 
     if (NS_FAILED(rv))
       break;
   }
 
-  mRangeContexts.RemoveElementAt(mRangeContexts.Length() - 1);
+  mRangeContexts.RemoveLastElement();
   return rv;
 }
 
 nsresult
 nsDocumentEncoder::SerializeRangeToString(nsRange *aRange,
                                           nsAString& aOutputString)
 {
   if (!aRange || aRange->Collapsed())
--- a/dom/base/nsFrameMessageManager.cpp
+++ b/dom/base/nsFrameMessageManager.cpp
@@ -1100,17 +1100,17 @@ nsFrameMessageManager::ReceiveMessage(ns
                                   JS::HandleValueArray(argv), &rval)) {
           continue;
         }
         if (aRetVal) {
           ErrorResult rv;
           StructuredCloneData* data = aRetVal->AppendElement();
           data->Write(cx, rval, rv);
           if (NS_WARN_IF(rv.Failed())) {
-            aRetVal->RemoveElementAt(aRetVal->Length() - 1);
+            aRetVal->RemoveLastElement();
             nsString msg = aMessage + NS_LITERAL_STRING(": message reply cannot be cloned. Are you trying to send an XPCOM object?");
 
             nsCOMPtr<nsIConsoleService> console(do_GetService(NS_CONSOLESERVICE_CONTRACTID));
             if (console) {
               nsCOMPtr<nsIScriptError> error(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
               error->Init(msg, EmptyString(), EmptyString(),
                           0, 0, nsIScriptError::warningFlag, "chrome javascript",
                           false /* from private window */);
--- a/dom/base/nsHTMLContentSerializer.cpp
+++ b/dom/base/nsHTMLContentSerializer.cpp
@@ -323,17 +323,17 @@ nsHTMLContentSerializer::AppendElementEn
       return NS_OK;
     }
   }
   else if (mIsCopying && name == nsGkAtoms::ol && ns == kNameSpaceID_XHTML) {
     NS_ASSERTION((!mOLStateStack.IsEmpty()), "Cannot have an empty OL Stack");
     /* Though at this point we must always have an state to be deleted as all
     the OL opening tags are supposed to push an olState object to the stack*/
     if (!mOLStateStack.IsEmpty()) {
-      mOLStateStack.RemoveElementAt(mOLStateStack.Length() -1);
+      mOLStateStack.RemoveLastElement();
     }
   }
 
   if (ns == kNameSpaceID_XHTML) {
     bool isContainer =
       nsHTMLElement::IsContainer(nsHTMLTags::CaseSensitiveAtomTagToId(name));
     if (!isContainer) {
       // Keep this in sync with the cleanup at the end of this method.
--- a/dom/base/nsXHTMLContentSerializer.cpp
+++ b/dom/base/nsXHTMLContentSerializer.cpp
@@ -450,17 +450,17 @@ nsXHTMLContentSerializer::CheckElementEn
   aForceFormat = !(mFlags & nsIDocumentEncoder::OutputIgnoreMozDirty) &&
                  aElement->HasAttr(kNameSpaceID_None, nsGkAtoms::mozdirty);
 
   if (mIsCopying && aElement->IsHTMLElement(nsGkAtoms::ol)) {
     NS_ASSERTION((!mOLStateStack.IsEmpty()), "Cannot have an empty OL Stack");
     /* Though at this point we must always have an state to be deleted as all
        the OL opening tags are supposed to push an olState object to the stack*/
     if (!mOLStateStack.IsEmpty()) {
-        mOLStateStack.RemoveElementAt(mOLStateStack.Length() -1);
+      mOLStateStack.RemoveLastElement();
     }
   }
 
   bool dummyFormat;
   return nsXMLContentSerializer::CheckElementEnd(aElement, dummyFormat, aStr);
 }
 
 bool
--- a/dom/canvas/CanvasRenderingContext2D.cpp
+++ b/dom/canvas/CanvasRenderingContext2D.cpp
@@ -2235,17 +2235,17 @@ CanvasRenderingContext2D::Restore()
   }
 
   for (const auto& clipOrTransform : CurrentState().clipsAndTransforms) {
     if (clipOrTransform.IsClip()) {
       mTarget->PopClip();
     }
   }
 
-  mStyleStack.RemoveElementAt(mStyleStack.Length() - 1);
+  mStyleStack.RemoveLastElement();
 
   mTarget->SetTransform(CurrentState().transform);
 }
 
 //
 // transformations
 //
 
--- a/dom/media/webrtc/MediaTrackConstraints.cpp
+++ b/dom/media/webrtc/MediaTrackConstraints.cpp
@@ -526,17 +526,17 @@ MediaConstraintsHelper::SelectSettings(
         rejects.AppendElement(Move(aDevices[j]));
         aDevices.RemoveElementAt(j);
       } else {
         ++j;
       }
     }
     if (aDevices.IsEmpty()) {
       aDevices.AppendElements(Move(rejects));
-      aggregateConstraints.RemoveElementAt(aggregateConstraints.Length() - 1);
+      aggregateConstraints.RemoveLastElement();
     }
   }
   return nullptr;
 }
 
 /* static */ const char*
 MediaConstraintsHelper::FindBadConstraint(
     const NormalizedConstraints& aConstraints,
--- a/dom/workers/WorkerLoadInfo.cpp
+++ b/dom/workers/WorkerLoadInfo.cpp
@@ -524,17 +524,17 @@ InterfaceRequestor::GetAnyLiveTabChild()
 
     // Does this tab child still exist?  If so, return it.  We are done.  If the
     // PBrowser actor is no longer useful, don't bother returning this tab.
     if (tabChild && !static_cast<TabChild*>(tabChild.get())->IsDestroyed()) {
       return tabChild.forget();
     }
 
     // Otherwise remove the stale weak reference and check the next one
-    mTabChildList.RemoveElementAt(mTabChildList.Length() - 1);
+    mTabChildList.RemoveLastElement();
   }
 
   return nullptr;
 }
 
 NS_IMPL_ADDREF(WorkerLoadInfo::InterfaceRequestor)
 NS_IMPL_RELEASE(WorkerLoadInfo::InterfaceRequestor)
 NS_IMPL_QUERY_INTERFACE(WorkerLoadInfo::InterfaceRequestor,
--- a/dom/xbl/nsBindingManager.cpp
+++ b/dom/xbl/nsBindingManager.cpp
@@ -457,17 +457,17 @@ nsBindingManager::ExecuteDetachedHandler
 
   nsCOMArray<nsIContent> boundElements;
   nsBindingList bindings;
 
   for (auto iter = mBoundContentSet->Iter(); !iter.Done(); iter.Next()) {
     nsXBLBinding* binding = iter.Get()->GetKey()->GetXBLBinding();
     if (binding && bindings.AppendElement(binding)) {
       if (!boundElements.AppendObject(binding->GetBoundElement())) {
-        bindings.RemoveElementAt(bindings.Length() - 1);
+        bindings.RemoveLastElement();
       }
     }
   }
 
   uint32_t i, count = bindings.Length();
   for (i = 0; i < count; ++i) {
     bindings[i]->ExecuteDetachedHandler();
   }
--- a/dom/xslt/base/txNamespaceMap.cpp
+++ b/dom/xslt/base/txNamespaceMap.cpp
@@ -52,17 +52,17 @@ txNamespaceMap::mapNamespace(nsAtom* aPr
     }
 
     // New mapping
     if (!mPrefixes.AppendElement(prefix)) {
         return NS_ERROR_OUT_OF_MEMORY;
     }
 
     if (mNamespaces.AppendElement(nsId) == nullptr) {
-        mPrefixes.RemoveElementAt(mPrefixes.Length() - 1);
+        mPrefixes.RemoveLastElement();
 
         return NS_ERROR_OUT_OF_MEMORY;
     }
 
     return NS_OK;
 }
 
 int32_t
--- a/dom/xslt/xslt/txExecutionState.cpp
+++ b/dom/xslt/xslt/txExecutionState.cpp
@@ -391,17 +391,17 @@ txExecutionState::pushTemplateRule(txSty
     rule->mModeLocalName = aMode.mLocalName;
     rule->mParams = aParams;
 }
 
 void
 txExecutionState::popTemplateRule()
 {
     NS_PRECONDITION(!mTemplateRules.IsEmpty(), "No rules to pop");
-    mTemplateRules.RemoveElementAt(mTemplateRules.Length() - 1);
+    mTemplateRules.RemoveLastElement();
 }
 
 txIEvalContext*
 txExecutionState::getEvalContext()
 {
     return mEvalContext;
 }
 
@@ -529,13 +529,12 @@ txExecutionState::pushParamMap(txParamet
     mParamStack.AppendElement(mTemplateParams.forget());
     mTemplateParams = aParams;
 }
 
 already_AddRefed<txParameterMap>
 txExecutionState::popParamMap()
 {
     RefPtr<txParameterMap> oldParams = mTemplateParams.forget();
-    mTemplateParams = mParamStack.LastElement();
-    mParamStack.RemoveElementAt(mParamStack.Length() - 1);
+    mTemplateParams = mParamStack.PopLastElement();
 
     return oldParams.forget();
 }
--- a/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
+++ b/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
@@ -840,17 +840,17 @@ mozInlineSpellWordUtil::BuildSoftText()
         int32_t len = lastOffsetInNode - firstOffsetInNode;
         mSoftTextDOMMapping.AppendElement(
           DOMTextMapping(NodeOffset(node, firstOffsetInNode), mSoftText.Length(), len));
 
         bool ok = textFragment->AppendTo(mSoftText, firstOffsetInNode, len,
                                          mozilla::fallible);
         if (!ok) {
             // probably out of memory, remove from mSoftTextDOMMapping
-            mSoftTextDOMMapping.RemoveElementAt(mSoftTextDOMMapping.Length() - 1);
+            mSoftTextDOMMapping.RemoveLastElement();
             exit = true;
         }
       }
 
       firstOffsetInNode = 0;
     }
 
     if (exit)
--- a/gfx/gl/GLTextureImage.cpp
+++ b/gfx/gl/GLTextureImage.cpp
@@ -455,17 +455,17 @@ void TiledTextureImage::Resize(const gfx
                 mImages.RemoveElementAt(i);
             }
         }
     }
 
     // Prune any unused tiles at the end of the store.
     unsigned int length = mImages.Length();
     for (; i < length; i++)
-      mImages.RemoveElementAt(mImages.Length()-1);
+      mImages.RemoveLastElement();
 
     // Reset tile-store properties.
     mRows = rows;
     mColumns = columns;
     mSize = aSize;
     mTextureState = Allocated;
     mCurrentImage = 0;
 }
--- a/gfx/thebes/gfxContext.cpp
+++ b/gfx/thebes/gfxContext.cpp
@@ -165,17 +165,17 @@ gfxContext::Restore()
                "Save() been called. you may consider to remove this pair of "
                "gfxContext::Save/Restore.");
 #endif
 
   for (unsigned int c = 0; c < CurrentState().pushedClips.Length(); c++) {
     mDT->PopClip();
   }
 
-  mStateStack.RemoveElementAt(mStateStack.Length() - 1);
+  mStateStack.RemoveLastElement();
 
   mDT = CurrentState().drawTarget;
 
   ChangeTransform(CurrentState().transform, false);
 }
 
 // drawing
 void
@@ -604,17 +604,17 @@ gfxContext::Clip()
   }
 }
 
 void
 gfxContext::PopClip()
 {
   MOZ_ASSERT(CurrentState().pushedClips.Length() > 0);
 
-  CurrentState().pushedClips.RemoveElementAt(CurrentState().pushedClips.Length() - 1);
+  CurrentState().pushedClips.RemoveLastElement();
   mDT->PopClip();
 }
 
 gfxRect
 gfxContext::GetClipExtents(ClipExtentsSpace aSpace) const
 {
   Rect rect = GetAzureDeviceSpaceClipBounds();
 
--- a/gfx/vr/gfxVRPuppet.cpp
+++ b/gfx/vr/gfxVRPuppet.cpp
@@ -743,17 +743,17 @@ VRSystemManagerPuppet::Enumerate()
   while (mPuppetHMDs.Length() < mPuppetDisplayCount) {
     VRDisplayPuppet* puppetDisplay = new VRDisplayPuppet();
     uint32_t deviceID = mPuppetHMDs.Length();
     puppetDisplay->SetDisplayInfo(mPuppetDisplayInfo[deviceID]);
     puppetDisplay->SetSensorState(mPuppetDisplaySensorState[deviceID]);
     mPuppetHMDs.AppendElement(puppetDisplay);
   }
   while (mPuppetHMDs.Length() > mPuppetDisplayCount) {
-    mPuppetHMDs.RemoveElementAt(mPuppetHMDs.Length() - 1);
+    mPuppetHMDs.RemoveLastElement();
   }
 }
 
 void
 VRSystemManagerPuppet::SetPuppetDisplayInfo(const uint32_t& aDeviceID,
                                             const VRDisplayInfo& aDisplayInfo)
 {
   if (aDeviceID >= mPuppetDisplayCount) {
--- a/image/DecodePool.cpp
+++ b/image/DecodePool.cpp
@@ -222,18 +222,17 @@ private:
   ~DecodePoolImpl() { }
 
   bool CreateThread();
 
   Work PopWorkFromQueue(nsTArray<RefPtr<IDecodingTask>>& aQueue)
   {
     Work work;
     work.mType = Work::Type::TASK;
-    work.mTask = aQueue.LastElement().forget();
-    aQueue.RemoveElementAt(aQueue.Length() - 1);
+    work.mTask = aQueue.PopLastElement();
 
     return work;
   }
 
   Work CreateShutdownWork() const
   {
     Work work;
     work.mType = Work::Type::SHUTDOWN;
--- a/image/imgLoader.cpp
+++ b/image/imgLoader.cpp
@@ -1020,17 +1020,17 @@ imgCacheQueue::Remove(imgCacheEntry* ent
   mSize -= mQueue[index]->GetDataSize();
 
   // If the queue is clean and this is the first entry,
   // then we can efficiently remove the entry without
   // dirtying the sort order.
   if (!IsDirty() && index == 0) {
     std::pop_heap(mQueue.begin(), mQueue.end(),
                   imgLoader::CompareCacheEntries);
-    mQueue.RemoveElementAt(mQueue.Length() - 1);
+    mQueue.RemoveLastElement();
     return;
   }
 
   // Remove from the middle of the list.  This potentially
   // breaks the binary heap sort order.
   mQueue.RemoveElementAt(index);
 
   // If we only have one entry or the queue is empty, though,
@@ -1066,18 +1066,17 @@ imgCacheQueue::Pop()
   if (mQueue.IsEmpty()) {
     return nullptr;
   }
   if (IsDirty()) {
     Refresh();
   }
 
   std::pop_heap(mQueue.begin(), mQueue.end(), imgLoader::CompareCacheEntries);
-  RefPtr<imgCacheEntry> entry = Move(mQueue.LastElement());
-  mQueue.RemoveElementAt(mQueue.Length() - 1);
+  RefPtr<imgCacheEntry> entry = mQueue.PopLastElement();
 
   mSize -= entry->GetDataSize();
   return entry.forget();
 }
 
 void
 imgCacheQueue::Refresh()
 {
--- a/ipc/mscom/Utils.cpp
+++ b/ipc/mscom/Utils.cpp
@@ -335,18 +335,17 @@ IsInterfaceEqualToOrInheritedFrom(REFIID
     typeInfos.AppendElement(Move(typeInfo));
   }
 
   /**
    * The main loop of this function searches the hierarchy of aInterface's
    * parent interfaces, searching for aFrom.
    */
   while (!typeInfos.IsEmpty()) {
-    RefPtr<ITypeInfo> curTypeInfo(Move(typeInfos.LastElement()));
-    typeInfos.RemoveElementAt(typeInfos.Length() - 1);
+    RefPtr<ITypeInfo> curTypeInfo(typeInfos.PopLastElement());
 
     TYPEATTR* typeAttr = nullptr;
     HRESULT hr = curTypeInfo->GetTypeAttr(&typeAttr);
     if (FAILED(hr)) {
       break;
     }
 
     bool isFromParentVtable = IsVtableIndexFromParentInterface(typeAttr,
--- a/layout/base/PresShell.cpp
+++ b/layout/base/PresShell.cpp
@@ -2734,18 +2734,17 @@ PresShell::FrameNeedsReflow(nsIFrame *aF
     }
   }
 #endif
 
   AutoTArray<nsIFrame*, 4> subtrees;
   subtrees.AppendElement(aFrame);
 
   do {
-    nsIFrame *subtreeRoot = subtrees.ElementAt(subtrees.Length() - 1);
-    subtrees.RemoveElementAt(subtrees.Length() - 1);
+    nsIFrame *subtreeRoot = subtrees.PopLastElement();
 
     // Grab |wasDirty| now so we can go ahead and update the bits on
     // subtreeRoot.
     bool wasDirty = NS_SUBTREE_DIRTY(subtreeRoot);
     subtreeRoot->AddStateBits(aBitToAdd);
 
     // Determine whether we need to keep looking for the next ancestor
     // reflow root if subtreeRoot itself is a reflow root.
@@ -2785,18 +2784,17 @@ PresShell::FrameNeedsReflow(nsIFrame *aF
       // Mark all descendants dirty (using an nsTArray stack rather than
       // recursion).
       // Note that ReflowInput::InitResizeFlags has some similar
       // code; see comments there for how and why it differs.
       AutoTArray<nsIFrame*, 32> stack;
       stack.AppendElement(subtreeRoot);
 
       do {
-        nsIFrame *f = stack.ElementAt(stack.Length() - 1);
-        stack.RemoveElementAt(stack.Length() - 1);
+        nsIFrame *f = stack.PopLastElement();
 
         if (f->IsPlaceholderFrame()) {
           nsIFrame *oof = nsPlaceholderFrame::GetRealFrameForPlaceholder(f);
           if (!nsLayoutUtils::IsProperAncestorFrame(subtreeRoot, oof)) {
             // We have another distinct subtree we need to mark.
             subtrees.AppendElement(oof);
           }
         }
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -3270,17 +3270,17 @@ static bool gDumpEventList = false;
 // maintaining a single paint count, we need a stack.
 StaticAutoPtr<nsTArray<int>> gPaintCountStack;
 
 struct AutoNestedPaintCount {
   AutoNestedPaintCount() {
     gPaintCountStack->AppendElement(0);
   }
   ~AutoNestedPaintCount() {
-    gPaintCountStack->RemoveElementAt(gPaintCountStack->Length() - 1);
+    gPaintCountStack->RemoveLastElement();
   }
 };
 
 #endif
 
 nsIFrame*
 nsLayoutUtils::GetFrameForPoint(nsIFrame* aFrame, nsPoint aPt, uint32_t aFlags)
 {
@@ -5823,29 +5823,27 @@ nsLayoutUtils::ComputeBSizeDependentValu
 nsLayoutUtils::MarkDescendantsDirty(nsIFrame *aSubtreeRoot)
 {
   AutoTArray<nsIFrame*, 4> subtrees;
   subtrees.AppendElement(aSubtreeRoot);
 
   // dirty descendants, iterating over subtrees that may include
   // additional subtrees associated with placeholders
   do {
-    nsIFrame *subtreeRoot = subtrees.ElementAt(subtrees.Length() - 1);
-    subtrees.RemoveElementAt(subtrees.Length() - 1);
+    nsIFrame *subtreeRoot = subtrees.PopLastElement();
 
     // Mark all descendants dirty (using an nsTArray stack rather than
     // recursion).
     // Note that ReflowInput::InitResizeFlags has some similar
     // code; see comments there for how and why it differs.
     AutoTArray<nsIFrame*, 32> stack;
     stack.AppendElement(subtreeRoot);
 
     do {
-      nsIFrame *f = stack.ElementAt(stack.Length() - 1);
-      stack.RemoveElementAt(stack.Length() - 1);
+      nsIFrame *f = stack.PopLastElement();
 
       f->MarkIntrinsicISizesDirty();
 
       if (f->IsPlaceholderFrame()) {
         nsIFrame *oof = nsPlaceholderFrame::GetRealFrameForPlaceholder(f);
         if (!nsLayoutUtils::IsProperAncestorFrame(subtreeRoot, oof)) {
           // We have another distinct subtree we need to mark.
           subtrees.AppendElement(oof);
@@ -5867,18 +5865,17 @@ nsLayoutUtils::MarkDescendantsDirty(nsIF
 /* static */
 void
 nsLayoutUtils::MarkIntrinsicISizesDirtyIfDependentOnBSize(nsIFrame* aFrame)
 {
   AutoTArray<nsIFrame*, 32> stack;
   stack.AppendElement(aFrame);
 
   do {
-    nsIFrame* f = stack.ElementAt(stack.Length() - 1);
-    stack.RemoveElementAt(stack.Length() - 1);
+    nsIFrame* f = stack.PopLastElement();
 
     if (!f->HasAnyStateBits(
         NS_FRAME_DESCENDANT_INTRINSIC_ISIZE_DEPENDS_ON_BSIZE)) {
       continue;
     }
     f->MarkIntrinsicISizesDirty();
 
     for (nsIFrame::ChildListIterator lists(f); !lists.IsDone(); lists.Next()) {
--- a/layout/base/nsStyleChangeList.h
+++ b/layout/base/nsStyleChangeList.h
@@ -46,17 +46,17 @@ public:
   ~nsStyleChangeList() { MOZ_COUNT_DTOR(nsStyleChangeList); }
   void AppendChange(nsIFrame* aFrame, nsIContent* aContent, nsChangeHint aHint);
 
   // Starting from the end of the list, removes all changes until the list is
   // empty or an element with |mContent != aContent| is found.
   void PopChangesForContent(nsIContent* aContent)
   {
     while (!IsEmpty() && LastElement().mContent == aContent) {
-      RemoveElementAt(Length() - 1);
+      RemoveLastElement();
     }
   }
 
   bool IsGecko() const { return mType == mozilla::StyleBackendType::Gecko; }
   bool IsServo() const { return mType == mozilla::StyleBackendType::Servo; }
 
 private:
   mozilla::StyleBackendType mType;
--- a/layout/generic/ReflowInput.cpp
+++ b/layout/generic/ReflowInput.cpp
@@ -647,18 +647,17 @@ ReflowInput::InitResizeFlags(nsPresConte
       // need to because we're actually doing something that cares about
       // frame tree geometry (the width on an ancestor) rather than
       // style.
 
       AutoTArray<nsIFrame*, 32> stack;
       stack.AppendElement(mFrame);
 
       do {
-        nsIFrame *f = stack.ElementAt(stack.Length() - 1);
-        stack.RemoveElementAt(stack.Length() - 1);
+        nsIFrame *f = stack.PopLastElement();
 
         nsIFrame::ChildListIterator lists(f);
         for (; !lists.IsDone(); lists.Next()) {
           nsFrameList::Enumerator childFrames(lists.CurrentList());
           for (; !childFrames.AtEnd(); childFrames.Next()) {
             nsIFrame* kid = childFrames.get();
             kid->MarkIntrinsicISizesDirty();
             stack.AppendElement(kid);
--- a/layout/generic/TextDrawTarget.h
+++ b/layout/generic/TextDrawTarget.h
@@ -180,17 +180,17 @@ public:
   PushClipRect(const Rect &aRect) override {
     LayoutDeviceRect rect = LayoutDeviceRect::FromUnknownRect(aRect);
     rect = rect.Intersect(mClipStack.LastElement());
     mClipStack.AppendElement(rect);
   }
 
   void
   PopClip() override {
-    mClipStack.RemoveElementAt(mClipStack.Length() - 1);
+    mClipStack.RemoveLastElement();
   }
 
   void
   AppendShadow(const wr::Shadow& aShadow)
   {
     mBuilder.PushShadow(mBoundsRect, ClipRect(), mBackfaceVisible, aShadow);
     mHasShadows = true;
   }
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -12195,17 +12195,17 @@ DR_FrameTreeNode* DR_State::CreateTreeNo
   FindMatchingRule(*newNode);
 
   newNode->mIndent = mIndent;
   if (newNode->mDisplay || mIndentUndisplayedFrames) {
     ++mIndent;
   }
 
   if (lastLeaf && (lastLeaf == parentNode)) {
-    mFrameTreeLeaves.RemoveElementAt(mFrameTreeLeaves.Length() - 1);
+    mFrameTreeLeaves.RemoveLastElement();
   }
   mFrameTreeLeaves.AppendElement(newNode);
   mCount++;
 
   return newNode;
 }
 
 void DR_State::PrettyUC(nscoord aSize,
--- a/layout/painting/RetainedDisplayListBuilder.cpp
+++ b/layout/painting/RetainedDisplayListBuilder.cpp
@@ -194,17 +194,17 @@ template<typename T>
 void SwapAndRemove(nsTArray<T>& aArray, uint32_t aIndex)
 {
   if (aIndex != (aArray.Length() - 1)) {
     T last = aArray.LastElement();
     aArray.LastElement() = aArray[aIndex];
     aArray[aIndex] = last;
   }
 
-  aArray.RemoveElementAt(aArray.Length() - 1);
+  aArray.RemoveLastElement();
 }
 
 static bool
 MergeFrameRects(nsDisplayLayerEventRegions* aOldItem,
                 nsDisplayLayerEventRegions* aNewItem,
                 nsDisplayLayerEventRegions::FrameRects nsDisplayLayerEventRegions::*aRectList,
                 nsTArray<nsIFrame*>& aAddedFrames)
 {
--- a/layout/painting/nsDisplayList.h
+++ b/layout/painting/nsDisplayList.h
@@ -6779,18 +6779,17 @@ private:
   void ResolveFlattening()
   {
     // Handle the case where we reach the end of a nested list, or the current
     // item should start a new nested list. Repeat this until we find an actual
     // item, or the very end of the outer list.
     while (AtEndOfNestedList() || ShouldFlattenNextItem()) {
       if (AtEndOfNestedList()) {
         // Pop the last item off the stack.
-        mNext = mStack.LastElement();
-        mStack.RemoveElementAt(mStack.Length() - 1);
+        mNext = mStack.PopLastElement();
         // We stored the item that was flattened, so advance to the next.
         mNext = mNext->GetAbove();
       } else {
         // This item wants to be flattened. Store the current item on the stack,
         // and use the first item in the child list instead.
         mStack.AppendElement(mNext);
         nsDisplayList* childItems = mNext->GetSameCoordinateSystemChildren();
         mNext = childItems->GetBottom();
--- a/layout/style/FontFaceSet.cpp
+++ b/layout/style/FontFaceSet.cpp
@@ -1224,17 +1224,17 @@ FontFaceSet::FindOrCreateUserFontEntryFr
               // unknown format specified, mark to distinguish from the
               // case where no format hints are specified
               face->mFormatFlags |= gfxUserFontSet::FLAG_FORMAT_UNKNOWN;
             }
             i++;
           }
           if (!face->mURI) {
             // if URI not valid, omit from src array
-            srcArray.RemoveElementAt(srcArray.Length() - 1);
+            srcArray.RemoveLastElement();
             NS_WARNING("null url in @font-face rule");
             continue;
           }
           break;
         }
         default:
           NS_ASSERTION(unit == eCSSUnit_Local_Font || unit == eCSSUnit_URL,
                        "strange unit type in font-face src array");
--- a/layout/style/nsFontFaceUtils.cpp
+++ b/layout/style/nsFontFaceUtils.cpp
@@ -110,26 +110,24 @@ nsFontFaceUtils::MarkDirtyForFontChange(
   AutoTArray<nsIFrame*, 4> subtrees;
   subtrees.AppendElement(aSubtreeRoot);
 
   nsIPresShell* ps = aSubtreeRoot->PresShell();
 
   // check descendants, iterating over subtrees that may include
   // additional subtrees associated with placeholders
   do {
-    nsIFrame* subtreeRoot = subtrees.ElementAt(subtrees.Length() - 1);
-    subtrees.RemoveElementAt(subtrees.Length() - 1);
+    nsIFrame* subtreeRoot = subtrees.PopLastElement();
 
     // Check all descendants to see if they use the font
     AutoTArray<nsIFrame*, 32> stack;
     stack.AppendElement(subtreeRoot);
 
     do {
-      nsIFrame* f = stack.ElementAt(stack.Length() - 1);
-      stack.RemoveElementAt(stack.Length() - 1);
+      nsIFrame* f = stack.PopLastElement();
 
       // if this frame uses the font, mark its descendants dirty
       // and skip checking its children
       if (FrameUsesFont(f, aFont)) {
         ScheduleReflow(ps, f);
       } else {
         if (f->IsPlaceholderFrame()) {
           nsIFrame* oof = nsPlaceholderFrame::GetRealFrameForPlaceholder(f);
--- a/netwerk/cache2/CacheIndexIterator.cpp
+++ b/netwerk/cache2/CacheIndexIterator.cpp
@@ -39,17 +39,17 @@ CacheIndexIterator::GetNextHash(SHA1Sum:
   }
 
   if (!mRecords.Length()) {
     CloseInternal(NS_ERROR_NOT_AVAILABLE);
     return mStatus;
   }
 
   memcpy(aHash, mRecords[mRecords.Length() - 1]->mHash, sizeof(SHA1Sum::Hash));
-  mRecords.RemoveElementAt(mRecords.Length() - 1);
+  mRecords.RemoveLastElement();
 
   return NS_OK;
 }
 
 nsresult
 CacheIndexIterator::Close()
 {
   LOG(("CacheIndexIterator::Close() [this=%p]", this));
--- a/netwerk/protocol/http/nsHttpChannel.cpp
+++ b/netwerk/protocol/http/nsHttpChannel.cpp
@@ -8277,18 +8277,17 @@ nsHttpChannel::OnRedirectVerifyCallback(
     mWaitingForRedirectCallback = false;
 
     if (mCanceled && NS_SUCCEEDED(result))
         result = NS_BINDING_ABORTED;
 
     for (uint32_t i = mRedirectFuncStack.Length(); i > 0;) {
         --i;
         // Pop the last function pushed to the stack
-        nsContinueRedirectionFunc func = mRedirectFuncStack[i];
-        mRedirectFuncStack.RemoveElementAt(mRedirectFuncStack.Length() - 1);
+        nsContinueRedirectionFunc func = mRedirectFuncStack.PopLastElement();
 
         // Call it with the result we got from the callback or the deeper
         // function call.
         result = (this->*func)(result);
 
         // If a new function has been pushed to the stack and placed us in the
         // waiting state, we need to break the chain and wait for the callback
         // again.
--- a/parser/html/nsHtml5Highlighter.cpp
+++ b/parser/html/nsHtml5Highlighter.cpp
@@ -709,17 +709,17 @@ nsHtml5Highlighter::Push(nsAtom* aName,
   mOpQueue.AppendElement()->Init(eTreeOpAppend, elt, CurrentNode());
   mStack.AppendElement(elt);
 }
 
 void
 nsHtml5Highlighter::Pop()
 {
   NS_PRECONDITION(mStack.Length() >= 2, "Popping when stack too short.");
-  mStack.RemoveElementAt(mStack.Length() - 1);
+  mStack.RemoveLastElement();
 }
 
 void
 nsHtml5Highlighter::AppendCharacters(const char16_t* aBuffer,
                                      int32_t aStart,
                                      int32_t aLength)
 {
   NS_PRECONDITION(aBuffer, "Null buffer");
--- a/toolkit/components/places/History.cpp
+++ b/toolkit/components/places/History.cpp
@@ -3243,17 +3243,17 @@ History::UpdatePlaces(JS::Handle<JS::Val
                           nsINavHistoryService::TRANSITION_RELOAD);
       data.SetTransitionType(transitionType);
       data.hidden = GetHiddenState(false, transitionType);
 
       // If the visit is an embed visit, we do not actually add it to the
       // database.
       if (transitionType == nsINavHistoryService::TRANSITION_EMBED) {
         StoreAndNotifyEmbedVisit(data, aCallback);
-        visitData.RemoveElementAt(visitData.Length() - 1);
+        visitData.RemoveLastElement();
         initialUpdatedCount++;
         continue;
       }
 
       // The referrer is optional.
       nsCOMPtr<nsIURI> referrer = GetURIFromJSObject(aCtx, visit,
                                                      "referrerURI");
       if (referrer) {
--- a/widget/cocoa/TextInputHandler.h
+++ b/widget/cocoa/TextInputHandler.h
@@ -874,18 +874,17 @@ protected:
   /**
    * RemoveCurrentKeyEvent() removes the current key event from
    * mCurrentKeyEvents.
    */
   void RemoveCurrentKeyEvent()
   {
     NS_ASSERTION(mCurrentKeyEvents.Length() > 0,
                  "RemoveCurrentKeyEvent() is called unexpectedly");
-    KeyEventState* keyEvent = GetCurrentKeyEvent();
-    mCurrentKeyEvents.RemoveElementAt(mCurrentKeyEvents.Length() - 1);
+    KeyEventState* keyEvent = mCurrentKeyEvents.PopLastElement();
     if (keyEvent == &mFirstKeyEvent) {
       keyEvent->Clear();
     } else {
       delete keyEvent;
     }
   }
 
   /**
--- a/widget/windows/TSFTextStore.cpp
+++ b/widget/windows/TSFTextStore.cpp
@@ -5126,17 +5126,17 @@ TSFTextStore::RecordCompositionStartActi
   // compositionend and start composition normally.
   if (!aPreserveSelection &&
       WasTextInsertedWithoutCompositionAt(aStart, aLength)) {
     const PendingAction& pendingCompositionEnd = mPendingActions.LastElement();
     const PendingAction& pendingCompositionStart =
       mPendingActions[mPendingActions.Length() - 2];
     contentForTSF.RestoreCommittedComposition(
       aComposition, pendingCompositionStart, pendingCompositionEnd);
-    mPendingActions.RemoveElementAt(mPendingActions.Length() - 1);
+    mPendingActions.RemoveLastElement();
     MOZ_LOG(sTextStoreLog, LogLevel::Info,
       ("0x%p   TSFTextStore::RecordCompositionStartAction() "
        "succeeded: restoring the committed string as composing string, "
        "mComposition={ mStart=%ld, mString.Length()=%ld, "
        "mSelectionForTSF={ acpStart=%ld, acpEnd=%ld, style.ase=%s, "
        "style.fInterimChar=%s } }",
        this, mComposition.mStart, mComposition.mString.Length(),
        mSelectionForTSF.StartOffset(), mSelectionForTSF.EndOffset(),
--- a/xpcom/threads/DeadlockDetector.h
+++ b/xpcom/threads/DeadlockDetector.h
@@ -342,17 +342,17 @@ public:
 
     index_type i = 0;
     size_type len = aStart->mOrderedLT.Length();
     for (auto it = aStart->mOrderedLT.Elements(); i < len; ++i, ++it) {
       aChain->AppendElement((*it)->mResource);
       if (GetDeductionChain_Helper(*it, aTarget, aChain)) {
         return true;
       }
-      aChain->RemoveElementAt(aChain->Length() - 1);
+      aChain->RemoveLastElement();
     }
     return false;
   }
 
   /**
    * The partial order on resource acquisitions used by the deadlock
    * detector.
    */
--- a/xpcom/threads/ThreadEventQueue.cpp
+++ b/xpcom/threads/ThreadEventQueue.cpp
@@ -252,17 +252,17 @@ ThreadEventQueue<InnerQueueT>::PopEventQ
 
   // Move events from the old queue to the new one.
   nsCOMPtr<nsIRunnable> event;
   EventPriority prio;
   while ((event = item.mQueue->GetEvent(&prio, lock))) {
     prevQueue->PutEvent(event.forget(), prio, lock);
   }
 
-  mNestedQueues.RemoveElementAt(mNestedQueues.Length() - 1);
+  mNestedQueues.RemoveLastElement();
 }
 
 template<class InnerQueueT>
 already_AddRefed<nsIThreadObserver>
 ThreadEventQueue<InnerQueueT>::GetObserver()
 {
   MutexAutoLock lock(mLock);
   return do_AddRef(mObserver);
--- a/xpcom/threads/TimerThread.cpp
+++ b/xpcom/threads/TimerThread.cpp
@@ -734,17 +734,17 @@ TimerThread::RemoveLeadingCanceledTimers
 }
 
 void
 TimerThread::RemoveFirstTimerInternal()
 {
   mMonitor.AssertCurrentThreadOwns();
   MOZ_ASSERT(!mTimers.IsEmpty());
   std::pop_heap(mTimers.begin(), mTimers.end(), Entry::UniquePtrLessThan);
-  mTimers.RemoveElementAt(mTimers.Length() - 1);
+  mTimers.RemoveLastElement();
 }
 
 already_AddRefed<nsTimerImpl>
 TimerThread::PostTimerEvent(already_AddRefed<nsTimerImpl> aTimerRef)
 {
   mMonitor.AssertCurrentThreadOwns();
 
   RefPtr<nsTimerImpl> timer(aTimerRef);