merge mozilla-inbound to mozilla-central a=merge
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Tue, 01 Jul 2014 14:01:21 +0200
changeset 191651 4a9353b5762da2da730c40daf75f0436f6998740
parent 191585 83e0a29d43f6a4be60113e9038c6832d18e1a4dd (current diff)
parent 191650 881e7b3d101f626beafc3545e1e40bc075e7ae2e (diff)
child 191664 f207bcb19c2d3c3c4963bc3e17e2284d5f595d51
push id27055
push usercbook@mozilla.com
push dateTue, 01 Jul 2014 12:01:46 +0000
treeherdermozilla-central@4a9353b5762d [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone33.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
merge mozilla-inbound to mozilla-central a=merge
content/media/webspeech/recognition/nsIDOMSpeechRecognitionEvent.idl
content/media/webspeech/synth/nsIDOMSpeechSynthesisEvent.idl
dom/interfaces/apps/nsIDOMMozApplicationEvent.idl
dom/interfaces/devicestorage/nsIDOMDeviceStorageChangeEvent.idl
dom/interfaces/events/nsIDOMCloseEvent.idl
dom/interfaces/events/nsIDOMDOMTransactionEvent.idl
dom/interfaces/events/nsIDOMDeviceOrientationEvent.idl
dom/interfaces/events/nsIDOMElementReplaceEvent.idl
dom/interfaces/events/nsIDOMHashChangeEvent.idl
dom/interfaces/events/nsIDOMPageTransitionEvent.idl
dom/interfaces/events/nsIDOMPopStateEvent.idl
dom/interfaces/events/nsIDOMPopupBlockedEvent.idl
dom/interfaces/events/nsIDOMRecordErrorEvent.idl
dom/interfaces/events/nsIDOMSmartCardEvent.idl
dom/interfaces/events/nsIDOMStyleRuleChangeEvent.idl
dom/interfaces/events/nsIDOMStyleSheetApplicableStateChangeEvent.idl
dom/interfaces/events/nsIDOMStyleSheetChangeEvent.idl
dom/interfaces/settings/nsIDOMMozSettingsEvent.idl
dom/webidl/ElementReplaceEvent.webidl
js/src/assembler/TestMain.cpp
js/src/assembler/assembler/ARMAssembler.cpp
js/src/assembler/assembler/ARMAssembler.h
js/src/assembler/assembler/ARMv7Assembler.h
js/src/assembler/assembler/AbstractMacroAssembler.h
js/src/assembler/assembler/AssemblerBufferWithConstantPool.h
js/src/assembler/assembler/CodeLocation.h
js/src/assembler/assembler/LinkBuffer.h
js/src/assembler/assembler/MIPSAssembler.h
js/src/assembler/assembler/MacroAssemblerCodeRef.h
js/src/assembler/assembler/RepatchBuffer.h
js/src/assembler/assembler/SparcAssembler.h
js/src/assembler/moco/MocoStubs.h
js/src/assembler/wtf/SegmentedVector.h
js/xpconnect/src/event_impl_gen.conf.in
js/xpconnect/src/event_impl_gen.py
modules/libpref/src/init/all.js
--- a/config/check_spidermonkey_style.py
+++ b/config/check_spidermonkey_style.py
@@ -477,19 +477,19 @@ def do_file(filename, inclname, file_kin
 
         section1 = include1.section(inclname)
         section2 = include2.section(inclname)
         if (section1 > section2) or \
            ((section1 == section2) and (include1.inclname.lower() > include2.inclname.lower())):
             error(filename, str(include1.linenum) + ':' + str(include2.linenum),
                   include1.quote() + ' should be included after ' + include2.quote())
 
-    # The #include statements in the files in assembler/ and yarr/ have all manner of implicit
+    # The #include statements in the files in assembler/ have all manner of implicit
     # ordering requirements.  Boo.  Ignore them.
-    skip_order_checking = inclname.startswith(('assembler/', 'yarr/'))
+    skip_order_checking = inclname.startswith('assembler/')
 
     # Check the extracted #include statements, both individually, and the ordering of
     # adjacent pairs that live in the same block.
     def pair_traverse(prev, this):
         if this.isLeaf():
             check_include_statement(this)
             if prev is not None and prev.isLeaf() and not skip_order_checking:
                 check_includes_order(prev, this)
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -1397,32 +1397,32 @@ public:
 
   virtual void UnblockDOMContentLoaded() = 0;
 
   /**
    * Notification that the page has been shown, for documents which are loaded
    * into a DOM window.  This corresponds to the completion of document load,
    * or to the page's presentation being restored into an existing DOM window.
    * This notification fires applicable DOM events to the content window.  See
-   * nsIDOMPageTransitionEvent.idl for a description of the |aPersisted|
+   * PageTransitionEvent.webidl for a description of the |aPersisted|
    * parameter. If aDispatchStartTarget is null, the pageshow event is
    * dispatched on the ScriptGlobalObject for this document, otherwise it's
    * dispatched on aDispatchStartTarget.
    * Note: if aDispatchStartTarget isn't null, the showing state of the
    * document won't be altered.
    */
   virtual void OnPageShow(bool aPersisted,
                           mozilla::dom::EventTarget* aDispatchStartTarget) = 0;
 
   /**
    * Notification that the page has been hidden, for documents which are loaded
    * into a DOM window.  This corresponds to the unloading of the document, or
    * to the document's presentation being saved but removed from an existing
    * DOM window.  This notification fires applicable DOM events to the content
-   * window.  See nsIDOMPageTransitionEvent.idl for a description of the
+   * window.  See PageTransitionEvent.webidl for a description of the
    * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
    * event is dispatched on the ScriptGlobalObject for this document,
    * otherwise it's dispatched on aDispatchStartTarget.
    * Note: if aDispatchStartTarget isn't null, the showing state of the
    * document won't be altered.
    */
   virtual void OnPageHide(bool aPersisted,
                           mozilla::dom::EventTarget* aDispatchStartTarget) = 0;
--- a/content/base/src/ImportManager.cpp
+++ b/content/base/src/ImportManager.cpp
@@ -19,33 +19,35 @@
 #include "nsIDOMEvent.h"
 #include "nsIPrincipal.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsScriptLoader.h"
 #include "nsNetUtil.h"
 
 class AutoError {
 public:
-  AutoError(mozilla::dom::ImportLoader* loader)
+  AutoError(mozilla::dom::ImportLoader* loader, bool scriptsBlocked = true)
     : mLoader(loader)
     , mPassed(false)
+    , mScriptsBlocked(scriptsBlocked)
   {}
 
   ~AutoError()
   {
     if (!mPassed) {
-      mLoader->Error();
+      mLoader->Error(mScriptsBlocked);
     }
   }
 
   void Pass() { mPassed = true; }
 
 private:
   mozilla::dom::ImportLoader* mLoader;
   bool mPassed;
+  bool mScriptsBlocked;
 };
 
 namespace mozilla {
 namespace dom {
 
 NS_INTERFACE_MAP_BEGIN(ImportLoader)
   NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
   NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
@@ -159,41 +161,44 @@ ImportLoader::Done()
   for (uint32_t i = 0; i < count; i++) {
     DispatchLoadEvent(mLinks[i]);
   }
   UnblockScripts();
   ReleaseResources();
 }
 
 void
-ImportLoader::Error()
+ImportLoader::Error(bool aUnblockScripts)
 {
   mDocument = nullptr;
   mStopped = true;
   uint32_t count = mLinks.Count();
   for (uint32_t i = 0; i < count; i++) {
     DispatchErrorEvent(mLinks[i]);
   }
-  UnblockScripts();
+  if (aUnblockScripts) {
+    UnblockScripts();
+  }
+
   ReleaseResources();
 }
 
 // Release all the resources we don't need after there is no more
 // data available on the channel, and the parser is done.
 void ImportLoader::ReleaseResources()
 {
   mParserStreamListener = nullptr;
   mChannel = nullptr;
   mImportParent = nullptr;
 }
 
 void
 ImportLoader::Open()
 {
-  AutoError ae(this);
+  AutoError ae(this, false);
   // Imports should obey to the master documents CSP.
   nsCOMPtr<nsIDocument> master = mImportParent->MasterDocument();
   nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(master);
   nsCOMPtr<nsIPrincipal> principal = sop->GetPrincipal();
   int16_t shouldLoad = nsIContentPolicy::ACCEPT;
   nsresult rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_SCRIPT,
                                           mURI,
                                           principal,
--- a/content/base/src/ImportManager.h
+++ b/content/base/src/ImportManager.h
@@ -95,17 +95,17 @@ private:
   // the right event.
   void DispatchEventIfFinished(nsINode* aNode);
 
   // Dispatch event for a single referrer LinkElement.
   void DispatchErrorEvent(nsINode* aNode);
   void DispatchLoadEvent(nsINode* aNode);
 
   // Must be called when an error has occured during load.
-  void Error();
+  void Error(bool aUnblockScripts);
 
   // Must be called when the import document has been loaded successfully.
   void Done();
 
   // When the reading from the channel and the parsing
   // of the document is done, we can release the resources
   // that we don't need any longer to hold on.
   void ReleaseResources();
--- a/content/base/src/WebSocket.cpp
+++ b/content/base/src/WebSocket.cpp
@@ -24,30 +24,29 @@
 #include "nsIUnicodeEncoder.h"
 #include "nsThreadUtils.h"
 #include "nsIDOMMessageEvent.h"
 #include "nsIPromptFactory.h"
 #include "nsIWindowWatcher.h"
 #include "nsIPrompt.h"
 #include "nsIStringBundle.h"
 #include "nsIConsoleService.h"
-#include "nsIDOMCloseEvent.h"
+#include "mozilla/dom/CloseEvent.h"
 #include "nsICryptoHash.h"
 #include "nsJSUtils.h"
 #include "nsIScriptError.h"
 #include "nsNetUtil.h"
 #include "nsILoadGroup.h"
 #include "mozilla/Preferences.h"
 #include "xpcpublic.h"
 #include "nsContentPolicyUtils.h"
 #include "nsDOMFile.h"
 #include "nsWrapperCacheInlines.h"
 #include "nsIObserverService.h"
 #include "nsIWebSocketChannel.h"
-#include "GeneratedEvents.h"
 
 namespace mozilla {
 namespace dom {
 
 #define UTF_8_REPLACEMENT_CHAR    static_cast<char16_t>(0xFFFD)
 
 class CallDispatchConnectionCloseEvents: public nsRunnable
 {
@@ -923,29 +922,25 @@ WebSocket::CreateAndDispatchCloseEvent(b
 {
   NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread");
 
   nsresult rv = CheckInnerWindowCorrectness();
   if (NS_FAILED(rv)) {
     return NS_OK;
   }
 
-  // create an event that uses the CloseEvent interface,
-  // which does not bubble, is not cancelable, and has no default action
-
-  nsCOMPtr<nsIDOMEvent> event;
-  rv = NS_NewDOMCloseEvent(getter_AddRefs(event), this, nullptr, nullptr);
-  NS_ENSURE_SUCCESS(rv, rv);
+  CloseEventInit init;
+  init.mBubbles = false;
+  init.mCancelable = false;
+  init.mWasClean = aWasClean;
+  init.mCode = aCode;
+  init.mReason = aReason;
 
-  nsCOMPtr<nsIDOMCloseEvent> closeEvent = do_QueryInterface(event);
-  rv = closeEvent->InitCloseEvent(NS_LITERAL_STRING("close"),
-                                  false, false,
-                                  aWasClean, aCode, aReason);
-  NS_ENSURE_SUCCESS(rv, rv);
-
+  nsRefPtr<CloseEvent> event =
+    CloseEvent::Constructor(this, NS_LITERAL_STRING("close"), init);
   event->SetTrusted(true);
 
   return DispatchDOMEvent(nullptr, event, nullptr, nullptr);
 }
 
 bool
 WebSocket::PrefEnabled(JSContext* aCx, JSObject* aGlobal)
 {
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -133,26 +133,25 @@
 #include "nsICategoryManager.h"
 #include "nsIDocumentLoaderFactory.h"
 #include "nsIDocumentLoader.h"
 #include "nsIContentViewer.h"
 #include "nsIXMLContentSink.h"
 #include "nsIXULDocument.h"
 #include "nsIPrompt.h"
 #include "nsIPropertyBag2.h"
-#include "nsIDOMPageTransitionEvent.h"
-#include "nsIDOMStyleRuleChangeEvent.h"
-#include "nsIDOMStyleSheetChangeEvent.h"
-#include "nsIDOMStyleSheetApplicableStateChangeEvent.h"
+#include "mozilla/dom/PageTransitionEvent.h"
+#include "mozilla/dom/StyleRuleChangeEvent.h"
+#include "mozilla/dom/StyleSheetChangeEvent.h"
+#include "mozilla/dom/StyleSheetApplicableStateChangeEvent.h"
 #include "nsJSUtils.h"
 #include "nsFrameLoader.h"
 #include "nsEscape.h"
 #include "nsObjectLoadingContent.h"
 #include "nsHtml5TreeOpExecutor.h"
-#include "nsIDOMElementReplaceEvent.h"
 #include "mozilla/dom/HTMLLinkElement.h"
 #include "mozilla/dom/HTMLMediaElement.h"
 #ifdef MOZ_WEBRTC
 #include "IPeerConnection.h"
 #endif // MOZ_WEBRTC
 
 #include "mozAutoDocUpdate.h"
 #include "nsGlobalWindow.h"
@@ -177,17 +176,16 @@
 #include "mozilla/dom/Comment.h"
 #include "nsTextNode.h"
 #include "mozilla/dom/Link.h"
 #include "mozilla/dom/HTMLElementBinding.h"
 #include "mozilla/dom/SVGElementBinding.h"
 #include "nsXULAppAPI.h"
 #include "mozilla/dom/Touch.h"
 #include "mozilla/dom/TouchEvent.h"
-#include "GeneratedEvents.h"
 
 #include "mozilla/Preferences.h"
 
 #include "imgILoader.h"
 #include "imgRequestProxy.h"
 #include "nsWrapperCacheInlines.h"
 #include "nsSandboxFlags.h"
 #include "nsIAppsService.h"
@@ -3978,66 +3976,61 @@ void
 nsDocument::AddStyleSheetToStyleSets(nsIStyleSheet* aSheet)
 {
   nsCOMPtr<nsIPresShell> shell = GetShell();
   if (shell) {
     shell->StyleSet()->AddDocStyleSheet(aSheet, this);
   }
 }
 
-#define DO_STYLESHEET_NOTIFICATION(createFunc, concreteInterface, initMethod, type, ...) \
-  do {                                                                  \
-    nsCOMPtr<nsIDOMEvent> event;                                        \
-    nsresult rv = createFunc(getter_AddRefs(event), this,               \
-                             mPresShell ?                               \
-                             mPresShell->GetPresContext() : nullptr,    \
-                             nullptr);                                  \
-    if (NS_FAILED(rv)) {                                                \
-      return;                                                           \
-    }                                                                   \
-    nsCOMPtr<nsIDOMCSSStyleSheet> cssSheet(do_QueryInterface(aSheet));  \
-    if (!cssSheet) {                                                    \
-      return;                                                           \
-    }                                                                   \
-    nsCOMPtr<concreteInterface> ssEvent(do_QueryInterface(event));      \
-    MOZ_ASSERT(ssEvent);                                                \
-    ssEvent->initMethod(NS_LITERAL_STRING(type), true, true,            \
-                        cssSheet, __VA_ARGS__);                         \
-    event->SetTrusted(true);                                            \
-    event->SetTarget(this);                                             \
-    nsRefPtr<AsyncEventDispatcher> asyncDispatcher =                    \
-      new AsyncEventDispatcher(this, event);                            \
-    asyncDispatcher->mDispatchChromeOnly = true;                        \
-    asyncDispatcher->PostDOMEvent();                                    \
+#define DO_STYLESHEET_NOTIFICATION(className, type, memberName, argName)      \
+  do {                                                                        \
+    nsRefPtr<CSSStyleSheet> cssSheet = do_QueryObject(aSheet);                \
+    if (!cssSheet) {                                                          \
+      return;                                                                 \
+    }                                                                         \
+                                                                              \
+    className##Init init;                                                     \
+    init.mBubbles = true;                                                     \
+    init.mCancelable = true;                                                  \
+    init.mStylesheet = cssSheet;                                              \
+    init.memberName = argName;                                                \
+                                                                              \
+    nsRefPtr<className> event =                                               \
+      className::Constructor(this, NS_LITERAL_STRING(type), init);            \
+    event->SetTrusted(true);                                                  \
+    event->SetTarget(this);                                                   \
+    nsRefPtr<AsyncEventDispatcher> asyncDispatcher =                          \
+      new AsyncEventDispatcher(this, event);                                  \
+    asyncDispatcher->mDispatchChromeOnly = true;                              \
+    asyncDispatcher->PostDOMEvent();                                          \
   } while (0);
 
 void
 nsDocument::NotifyStyleSheetAdded(nsIStyleSheet* aSheet, bool aDocumentSheet)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleSheetAdded, (this, aSheet, aDocumentSheet));
 
   if (StyleSheetChangeEventsEnabled()) {
-    DO_STYLESHEET_NOTIFICATION(NS_NewDOMStyleSheetChangeEvent,
-                               nsIDOMStyleSheetChangeEvent,
-                               InitStyleSheetChangeEvent,
+    DO_STYLESHEET_NOTIFICATION(StyleSheetChangeEvent,
                                "StyleSheetAdded",
+                               mDocumentSheet,
                                aDocumentSheet);
   }
 }
 
 void
 nsDocument::NotifyStyleSheetRemoved(nsIStyleSheet* aSheet, bool aDocumentSheet)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleSheetRemoved, (this, aSheet, aDocumentSheet));
 
   if (StyleSheetChangeEventsEnabled()) {
-    DO_STYLESHEET_NOTIFICATION(NS_NewDOMStyleSheetChangeEvent,
-                               nsIDOMStyleSheetChangeEvent,
-                               InitStyleSheetChangeEvent,
+    DO_STYLESHEET_NOTIFICATION(StyleSheetChangeEvent,
                                "StyleSheetRemoved",
+                               mDocumentSheet,
                                aDocumentSheet);
   }
 }
 
 void
 nsDocument::AddStyleSheet(nsIStyleSheet* aSheet)
 {
   NS_PRECONDITION(aSheet, "null arg");
@@ -4153,20 +4146,19 @@ nsDocument::SetStyleSheetApplicableState
   // We have to always notify, since this will be called for sheets
   // that are children of sheets in our style set, as well as some
   // sheets for nsHTMLEditor.
 
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleSheetApplicableStateChanged,
                                (this, aSheet, aApplicable));
 
   if (StyleSheetChangeEventsEnabled()) {
-    DO_STYLESHEET_NOTIFICATION(NS_NewDOMStyleSheetApplicableStateChangeEvent,
-                               nsIDOMStyleSheetApplicableStateChangeEvent,
-                               InitStyleSheetApplicableStateChangeEvent,
+    DO_STYLESHEET_NOTIFICATION(StyleSheetApplicableStateChangeEvent,
                                "StyleSheetApplicableStateChanged",
+                               mApplicable,
                                aApplicable);
   }
 
   if (!mSSApplicableStateNotificationPending) {
     nsRefPtr<nsIRunnable> notification = NS_NewRunnableMethod(this,
       &nsDocument::NotifyStyleSheetApplicableStateChanged);
     mSSApplicableStateNotificationPending =
       NS_SUCCEEDED(NS_DispatchToCurrentThread(notification));
@@ -4927,54 +4919,51 @@ nsDocument::StyleRuleChanged(nsIStyleShe
                              nsIStyleRule* aNewStyleRule)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleRuleChanged,
                                (this, aSheet,
                                 aOldStyleRule, aNewStyleRule));
 
   if (StyleSheetChangeEventsEnabled()) {
     nsCOMPtr<css::Rule> rule = do_QueryInterface(aNewStyleRule);
-    DO_STYLESHEET_NOTIFICATION(NS_NewDOMStyleRuleChangeEvent,
-                               nsIDOMStyleRuleChangeEvent,
-                               InitStyleRuleChangeEvent,
+    DO_STYLESHEET_NOTIFICATION(StyleRuleChangeEvent,
                                "StyleRuleChanged",
+                               mRule,
                                rule ? rule->GetDOMRule() : nullptr);
   }
 }
 
 void
 nsDocument::StyleRuleAdded(nsIStyleSheet* aSheet,
                            nsIStyleRule* aStyleRule)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleRuleAdded,
                                (this, aSheet, aStyleRule));
 
   if (StyleSheetChangeEventsEnabled()) {
     nsCOMPtr<css::Rule> rule = do_QueryInterface(aStyleRule);
-    DO_STYLESHEET_NOTIFICATION(NS_NewDOMStyleRuleChangeEvent,
-                               nsIDOMStyleRuleChangeEvent,
-                               InitStyleRuleChangeEvent,
+    DO_STYLESHEET_NOTIFICATION(StyleRuleChangeEvent,
                                "StyleRuleAdded",
+                               mRule,
                                rule ? rule->GetDOMRule() : nullptr);
   }
 }
 
 void
 nsDocument::StyleRuleRemoved(nsIStyleSheet* aSheet,
                              nsIStyleRule* aStyleRule)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(StyleRuleRemoved,
                                (this, aSheet, aStyleRule));
 
   if (StyleSheetChangeEventsEnabled()) {
     nsCOMPtr<css::Rule> rule = do_QueryInterface(aStyleRule);
-    DO_STYLESHEET_NOTIFICATION(NS_NewDOMStyleRuleChangeEvent,
-                               nsIDOMStyleRuleChangeEvent,
-                               InitStyleRuleChangeEvent,
+    DO_STYLESHEET_NOTIFICATION(StyleRuleChangeEvent,
                                "StyleRuleRemoved",
+                               mRule,
                                rule ? rule->GetDOMRule() : nullptr);
   }
 }
 
 #undef DO_STYLESHEET_NOTIFICATION
 
 
 //
@@ -8686,29 +8675,32 @@ nsDocument::GetContentInThisDocument(nsI
   return nullptr;
 }
 
 void
 nsDocument::DispatchPageTransition(EventTarget* aDispatchTarget,
                                    const nsAString& aType,
                                    bool aPersisted)
 {
-  if (aDispatchTarget) {
-    nsCOMPtr<nsIDOMEvent> event;
-    CreateEvent(NS_LITERAL_STRING("pagetransition"), getter_AddRefs(event));
-    nsCOMPtr<nsIDOMPageTransitionEvent> ptEvent = do_QueryInterface(event);
-    if (ptEvent && NS_SUCCEEDED(ptEvent->InitPageTransitionEvent(aType, true,
-                                                                 true,
-                                                                 aPersisted))) {
-      event->SetTrusted(true);
-      event->SetTarget(this);
-      EventDispatcher::DispatchDOMEvent(aDispatchTarget, nullptr, event,
-                                        nullptr, nullptr);
-    }
-  }
+  if (!aDispatchTarget) {
+    return;
+  }
+
+  PageTransitionEventInit init;
+  init.mBubbles = true;
+  init.mCancelable = true;
+  init.mPersisted = aPersisted;
+
+  nsRefPtr<PageTransitionEvent> event =
+    PageTransitionEvent::Constructor(this, aType, init);
+
+  event->SetTrusted(true);
+  event->SetTarget(this);
+  EventDispatcher::DispatchDOMEvent(aDispatchTarget, nullptr, event,
+                                    nullptr, nullptr);
 }
 
 static bool
 NotifyPageShow(nsIDocument* aDocument, void* aData)
 {
   const bool* aPersistedPtr = static_cast<const bool*>(aData);
   aDocument->OnPageShow(*aPersistedPtr, nullptr);
   return true;
@@ -8901,18 +8893,17 @@ nsDocument::MutationEventDispatched(nsIN
 {
   --mSubtreeModifiedDepth;
   if (mSubtreeModifiedDepth == 0) {
     int32_t count = mSubtreeModifiedTargets.Count();
     if (!count) {
       return;
     }
 
-    nsCOMPtr<nsPIDOMWindow> window;
-    window = do_QueryInterface(GetWindow());
+    nsPIDOMWindow* window = GetInnerWindow();
     if (window &&
         !window->HasMutationListeners(NS_EVENT_BITS_MUTATION_SUBTREEMODIFIED)) {
       mSubtreeModifiedTargets.Clear();
       return;
     }
 
     nsCOMArray<nsINode> realTargets;
     for (int32_t i = 0; i < count; ++i) {
--- a/content/base/test/chrome/cpows_child.js
+++ b/content/base/test/chrome/cpows_child.js
@@ -40,16 +40,17 @@ var async_obj;
 function make_object()
 {
   let o = { };
   o.i = 5;
   o.b = true;
   o.s = "hello";
   o.x = { i: 10 };
   o.f = function () { return 99; };
+  o.ctor = function() { this.a = 3; }
 
   // Doing anything with this Proxy will throw.
   var throwing = new Proxy({}, new Proxy({}, {
       get: function (trap) { throw trap; }
     }));
 
   let array = [1, 2, 3];
 
--- a/content/base/test/chrome/cpows_parent.xul
+++ b/content/base/test/chrome/cpows_parent.xul
@@ -43,16 +43,18 @@
         ok(Components.utils.isCrossProcessWrapper(data), "got a CPOW");
         ok(Components.utils.isCrossProcessWrapper(document), "got a CPOW");
       }
       ok(data.i === 5, "integer property");
       ok(data.b === true, "boolean property");
       ok(data.s === "hello", "string property");
       ok(data.x.i === 10, "nested property");
       ok(data.f() === 99, "function call");
+      let obj = new data.ctor();
+      ok(obj.a === 3, "constructor call");
       ok(document.title === "Hello, Kitty", "document node");
 
       data.i = 6;
       data.b = false;
       data.s = "bye";
       data.x = null;
       ok(data.i === 6, "integer property");
       ok(data.b === false, "boolean property");
--- a/content/canvas/test/webgl-conformance/test_webgl_conformance_test_suite.html
+++ b/content/canvas/test/webgl-conformance/test_webgl_conformance_test_suite.html
@@ -106,20 +106,20 @@ function start() {
     kOS = OS_LINUX;
   }
   
   var glVendor, glRenderer;
   [glVendor, glRenderer] = detectDriverInfo();
   info('GL vendor: ' + glVendor);
   info('GL renderer: ' + glRenderer);
   
-  if (glRenderer.contains('llvmpipe')) {
+  if (glRenderer.contains('Android Emulator')) {
+    kGLDriver = GLDRIVER_X86EMULATOR;
+  } else if (glRenderer.contains('llvmpipe')) {
     kGLDriver = GLDRIVER_MESA;
-  } else if (glRenderer.contains('Android Emulator')) {
-    kGLDriver = GLDRIVER_X86EMULATOR;
   } else if (glVendor.contains('NVIDIA')) {
     kGLDriver = GLDRIVER_NVIDIA;
   }
   
   if (kOS) {
     info('OS detected as: ' + kOS);
     info('  Version: ' + kOSVersion);
   } else {
@@ -527,20 +527,16 @@ function start() {
         case GLDRIVER_NVIDIA:
           failingTestsFilename = 'failing_tests_android_nvidia.txt';
           skippedTestsFilename = 'skipped_tests_android.txt';
           break;
         case GLDRIVER_X86EMULATOR:
           failingTestsFilename = 'failing_tests_android_x86.txt';
           skippedTestsFilename = 'skipped_tests_android_x86.txt';
           break;
-        case GLDRIVER_MESA:
-          failingTestsFilename = 'failing_tests_android_x86.txt';
-          skippedTestsFilename = 'skipped_tests_android_x86.txt';
-          break;
         default:
           failingTestsFilename = 'failing_tests_android.txt';
           skippedTestsFilename = 'skipped_tests_android.txt';
           break;
       }
       break;
     }
   }
--- a/content/html/content/src/HTMLInputElement.cpp
+++ b/content/html/content/src/HTMLInputElement.cpp
@@ -846,17 +846,17 @@ HTMLInputElement::InitColorPicker()
   nsCOMPtr<nsIDocument> doc = OwnerDoc();
 
   nsCOMPtr<nsPIDOMWindow> win = doc->GetWindow();
   if (!win) {
     return NS_ERROR_FAILURE;
   }
 
   if (IsPopupBlocked()) {
-    nsGlobalWindow::FirePopupBlockedEvent(doc, win, nullptr, EmptyString(), EmptyString());
+    win->FirePopupBlockedEvent(doc, nullptr, EmptyString(), EmptyString());
     return NS_OK;
   }
 
   // Get Loc title
   nsXPIDLString title;
   nsContentUtils::GetLocalizedString(nsContentUtils::eFORMS_PROPERTIES,
                                      "ColorPicker", title);
 
@@ -893,17 +893,17 @@ HTMLInputElement::InitFilePicker(FilePic
   nsCOMPtr<nsIDocument> doc = OwnerDoc();
 
   nsCOMPtr<nsPIDOMWindow> win = doc->GetWindow();
   if (!win) {
     return NS_ERROR_FAILURE;
   }
 
   if (IsPopupBlocked()) {
-    nsGlobalWindow::FirePopupBlockedEvent(doc, win, nullptr, EmptyString(), EmptyString());
+    win->FirePopupBlockedEvent(doc, nullptr, EmptyString(), EmptyString());
     return NS_OK;
   }
 
   // Get Loc title
   nsXPIDLString title;
   nsContentUtils::GetLocalizedString(nsContentUtils::eFORMS_PROPERTIES,
                                      "FileUpload", title);
 
--- a/content/html/content/src/UndoManager.cpp
+++ b/content/html/content/src/UndoManager.cpp
@@ -9,17 +9,18 @@
 #include "mozilla/dom/Event.h"
 #include "nsDOMClassInfoID.h"
 #include "nsIClassInfo.h"
 #include "nsIDOMDocument.h"
 #include "nsIXPCScriptable.h"
 #include "nsIVariant.h"
 #include "nsVariant.h"
 #include "nsINode.h"
-#include "nsIDOMDOMTransactionEvent.h"
+#include "mozilla/dom/DOMTransactionEvent.h"
+#include "mozilla/dom/ToJSValue.h"
 #include "nsContentUtils.h"
 #include "jsapi.h"
 #include "nsIDocument.h"
 
 #include "mozilla/ErrorResult.h"
 #include "mozilla/EventDispatcher.h"
 #include "mozilla/Preferences.h"
 
@@ -1145,58 +1146,32 @@ UndoManager::DispatchTransactionEvent(JS
                                       ErrorResult& aRv)
 {
   nsTArray<DOMTransaction*> items;
   ItemInternal(aPreviousPosition, items, aRv);
   if (aRv.Failed()) {
     return;
   }
 
-  nsRefPtr<Event> event = mHostNode->OwnerDoc()->CreateEvent(
-    NS_LITERAL_STRING("domtransaction"), aRv);
-  if (aRv.Failed()) {
+  JS::Rooted<JS::Value> array(aCx);
+  if (!ToJSValue(aCx, items, &array)) {
     return;
   }
 
-  nsCOMPtr<nsIWritableVariant> transactions = new nsVariant();
+  RootedDictionary<DOMTransactionEventInit> init(aCx);
+  init.mBubbles = true;
+  init.mCancelable = false;
+  init.mTransactions = array;
 
-  // Unwrap the DOMTransactions into jsvals, then convert
-  // to nsIVariant then put into a nsIVariant array. Arrays in XPIDL suck.
-  nsCOMArray<nsIVariant> keepAlive;
-  nsTArray<nsIVariant*> transactionItems;
-  for (uint32_t i = 0; i < items.Length(); i++) {
-    JS::Rooted<JS::Value> txVal(aCx, JS::ObjectValue(*items[i]->Callback()));
-    if (!JS_WrapValue(aCx, &txVal)) {
-      aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
-      return;
-    }
-    nsCOMPtr<nsIVariant> txVariant;
-    nsresult rv =
-      nsContentUtils::XPConnect()->JSToVariant(aCx, txVal,
-                                               getter_AddRefs(txVariant));
-    if (NS_SUCCEEDED(rv)) {
-      keepAlive.AppendObject(txVariant);
-      transactionItems.AppendElement(txVariant.get());
-    }
-  }
+  nsRefPtr<DOMTransactionEvent> event =
+    DOMTransactionEvent::Constructor(mHostNode, aType, init);
 
-  transactions->SetAsArray(nsIDataType::VTYPE_INTERFACE_IS,
-                           &NS_GET_IID(nsIVariant),
-                           transactionItems.Length(),
-                           transactionItems.Elements());
-
-  nsCOMPtr<nsIDOMDOMTransactionEvent> ptEvent = do_QueryInterface(event);
-  if (ptEvent &&
-      NS_SUCCEEDED(ptEvent->InitDOMTransactionEvent(aType, true, false,
-                                                    transactions))) {
-    event->SetTrusted(true);
-    event->SetTarget(mHostNode);
-    EventDispatcher::DispatchDOMEvent(mHostNode, nullptr, event,
-                                      nullptr, nullptr);
-  }
+  event->SetTrusted(true);
+  EventDispatcher::DispatchDOMEvent(mHostNode, nullptr, event,
+                                    nullptr, nullptr);
 }
 
 void
 UndoManager::ClearUndo(ErrorResult& aRv)
 {
   if (mIsDisconnected || mInTransaction) {
     aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR);
     return;
--- a/content/media/MediaRecorder.cpp
+++ b/content/media/MediaRecorder.cpp
@@ -1,21 +1,20 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "MediaRecorder.h"
-#include "GeneratedEvents.h"
 #include "MediaEncoder.h"
 #include "mozilla/DOMEventTargetHelper.h"
 #include "nsError.h"
 #include "nsIDocument.h"
-#include "nsIDOMRecordErrorEvent.h"
+#include "mozilla/dom/RecordErrorEvent.h"
 #include "nsTArray.h"
 #include "DOMMediaStream.h"
 #include "EncodedBufferCache.h"
 #include "nsIDOMFile.h"
 #include "mozilla/dom/BlobEvent.h"
 #include "nsIPrincipal.h"
 #include "nsMimeTypes.h"
 
@@ -757,24 +756,25 @@ MediaRecorder::NotifyError(nsresult aRv)
     break;
   case NS_ERROR_OUT_OF_MEMORY:
     errorMsg = NS_LITERAL_STRING("OutOfMemoryError");
     break;
   default:
     errorMsg = NS_LITERAL_STRING("GenericError");
   }
 
-  nsCOMPtr<nsIDOMEvent> event;
-  rv = NS_NewDOMRecordErrorEvent(getter_AddRefs(event), this, nullptr, nullptr);
+  RecordErrorEventInit init;
+  init.mBubbles = false;
+  init.mCancelable = false;
+  init.mName = errorMsg;
 
-  nsCOMPtr<nsIDOMRecordErrorEvent> errorEvent = do_QueryInterface(event);
-  rv = errorEvent->InitRecordErrorEvent(NS_LITERAL_STRING("error"),
-                                        false, false, errorMsg);
+  nsRefPtr<RecordErrorEvent> event =
+    RecordErrorEvent::Constructor(this, NS_LITERAL_STRING("error"), init);
+  event->SetTrusted(true);
 
-  event->SetTrusted(true);
   rv = DispatchDOMEvent(nullptr, event, nullptr, nullptr);
   if (NS_FAILED(rv)) {
     NS_ERROR("Failed to dispatch the error event!!!");
     return;
   }
   return;
 }
 
--- a/content/media/webspeech/recognition/SpeechRecognition.cpp
+++ b/content/media/webspeech/recognition/SpeechRecognition.cpp
@@ -12,18 +12,17 @@
 #include "mozilla/dom/SpeechRecognitionBinding.h"
 #include "mozilla/dom/MediaStreamTrackBinding.h"
 #include "mozilla/MediaManager.h"
 #include "mozilla/Services.h"
 
 #include "AudioSegment.h"
 #include "endpointer.h"
 
-#include "GeneratedEvents.h"
-#include "nsIDOMSpeechRecognitionEvent.h"
+#include "mozilla/dom/SpeechRecognitionEvent.h"
 #include "nsIObserverService.h"
 #include "nsServiceManagerUtils.h"
 
 #include <algorithm>
 
 namespace mozilla {
 namespace dom {
 
@@ -462,30 +461,30 @@ SpeechRecognition::WaitForSpeechEnd(Spee
   }
 }
 
 void
 SpeechRecognition::NotifyFinalResult(SpeechEvent* aEvent)
 {
   ResetAndEnd();
 
-  nsCOMPtr<nsIDOMEvent> domEvent;
-  NS_NewDOMSpeechRecognitionEvent(getter_AddRefs(domEvent), nullptr, nullptr, nullptr);
+  SpeechRecognitionEventInit init;
+  init.mBubbles = true;
+  init.mCancelable = false;
+  // init.mResultIndex = 0;
+  init.mResults = aEvent->mRecognitionResultList;
+  init.mInterpretation = NS_LITERAL_STRING("NOT_IMPLEMENTED");
+  // init.mEmma = nullptr;
 
-  nsCOMPtr<nsIDOMSpeechRecognitionEvent> srEvent = do_QueryInterface(domEvent);
-  nsRefPtr<SpeechRecognitionResultList> rlist = aEvent->mRecognitionResultList;
-  nsCOMPtr<nsISupports> ilist = do_QueryInterface(rlist);
-  srEvent->InitSpeechRecognitionEvent(NS_LITERAL_STRING("result"),
-                                      true, false, 0, ilist,
-                                      NS_LITERAL_STRING("NOT_IMPLEMENTED"),
-                                      nullptr);
-  domEvent->SetTrusted(true);
+  nsRefPtr<SpeechRecognitionEvent> event =
+    SpeechRecognitionEvent::Constructor(this, NS_LITERAL_STRING("result"), init);
+  event->SetTrusted(true);
 
   bool defaultActionEnabled;
-  this->DispatchEvent(domEvent, &defaultActionEnabled);
+  this->DispatchEvent(event, &defaultActionEnabled);
 }
 
 void
 SpeechRecognition::DoNothing(SpeechEvent* aEvent)
 {
 }
 
 void
--- a/content/media/webspeech/recognition/moz.build
+++ b/content/media/webspeech/recognition/moz.build
@@ -1,17 +1,16 @@
 # vim: set filetype=python:
 # 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/.
 
 XPIDL_MODULE = 'dom_webspeechrecognition'
 
 XPIDL_SOURCES = [
-  'nsIDOMSpeechRecognitionEvent.idl',
   'nsISpeechRecognitionService.idl'
 ]
 
 TEST_DIRS += ['test']
 
 EXPORTS.mozilla.dom += [
     'SpeechGrammar.h',
     'SpeechGrammarList.h',
deleted file mode 100644
--- a/content/media/webspeech/recognition/nsIDOMSpeechRecognitionEvent.idl
+++ /dev/null
@@ -1,31 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/.
- *
- * The origin of this IDL file is
- * http://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html
- *
- * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
- * liability, trademark and document use rules apply.
- */
-
-#include "nsIDOMEvent.idl"
-
-interface SpeechRecognitionResultList;
-
-[builtinclass, uuid(98dded70-33af-42d5-819d-e15b6f4a3aba)]
-interface nsIDOMSpeechRecognitionEvent : nsIDOMEvent {
-    [noscript] void initSpeechRecognitionEvent(in DOMString eventTypeArg,
-                                               in boolean canBubbleArg,
-                                               in boolean cancelableArg,
-                                               in unsigned long resultIndex,
-                                               in nsISupports results,
-                                               in DOMString interpretation,
-                                               in nsIDOMDocument emma);
-
-    readonly attribute unsigned long resultIndex;
-    readonly attribute nsISupports results;
-    readonly attribute DOMString interpretation;
-    readonly attribute nsIDOMDocument emma;
-};
--- a/content/media/webspeech/synth/SpeechSynthesisUtterance.cpp
+++ b/content/media/webspeech/synth/SpeechSynthesisUtterance.cpp
@@ -3,19 +3,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsCOMPtr.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsGkAtoms.h"
 
-#include "GeneratedEvents.h"
-#include "nsIDOMSpeechSynthesisEvent.h"
-
+#include "mozilla/dom/SpeechSynthesisEvent.h"
 #include "mozilla/dom/SpeechSynthesisUtteranceBinding.h"
 #include "SpeechSynthesisUtterance.h"
 #include "SpeechSynthesisVoice.h"
 
 namespace mozilla {
 namespace dom {
 
 NS_IMPL_CYCLE_COLLECTION_INHERITED(SpeechSynthesisUtterance,
@@ -152,20 +150,22 @@ SpeechSynthesisUtterance::SetPitch(float
 }
 
 void
 SpeechSynthesisUtterance::DispatchSpeechSynthesisEvent(const nsAString& aEventType,
                                                        uint32_t aCharIndex,
                                                        float aElapsedTime,
                                                        const nsAString& aName)
 {
-  nsCOMPtr<nsIDOMEvent> domEvent;
-  NS_NewDOMSpeechSynthesisEvent(getter_AddRefs(domEvent), nullptr, nullptr, nullptr);
+  SpeechSynthesisEventInit init;
+  init.mBubbles = false;
+  init.mCancelable = false;
+  init.mCharIndex = aCharIndex;
+  init.mElapsedTime = aElapsedTime;
+  init.mName = aName;
 
-  nsCOMPtr<nsIDOMSpeechSynthesisEvent> ssEvent = do_QueryInterface(domEvent);
-  ssEvent->InitSpeechSynthesisEvent(aEventType, false, false,
-                                    aCharIndex, aElapsedTime, aName);
-
-  DispatchTrustedEvent(domEvent);
+  nsRefPtr<SpeechSynthesisEvent> event =
+    SpeechSynthesisEvent::Constructor(this, aEventType, init);
+  DispatchTrustedEvent(event);
 }
 
 } // namespace dom
 } // namespace mozilla
--- a/content/media/webspeech/synth/moz.build
+++ b/content/media/webspeech/synth/moz.build
@@ -5,17 +5,16 @@
 
 if CONFIG['MOZ_WEBSPEECH']:
 
     TEST_DIRS += ['test', 'ipc/test']
 
     XPIDL_MODULE = 'dom_webspeechsynth'
 
     XPIDL_SOURCES += [
-        'nsIDOMSpeechSynthesisEvent.idl',
         'nsISpeechService.idl',
         'nsISynthVoiceRegistry.idl'
     ]
 
     EXPORTS.mozilla.dom += [
         'ipc/SpeechSynthesisChild.h',
         'ipc/SpeechSynthesisParent.h',
         'nsSpeechTask.h',
deleted file mode 100644
--- a/content/media/webspeech/synth/nsIDOMSpeechSynthesisEvent.idl
+++ /dev/null
@@ -1,27 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/.
- *
- * The origin of this IDL file is
- * http://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html
- *
- * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
- * liability, trademark and document use rules apply.
- */
-
-#include "nsIDOMEvent.idl"
-
-[uuid(b5240841-dc69-43dd-bcf1-9306b8ddaa09)]
-interface nsIDOMSpeechSynthesisEvent : nsIDOMEvent {
-  [noscript] void initSpeechSynthesisEvent(in DOMString aEventTypeArg,
-                                           in boolean aCanBubbleArg,
-                                           in boolean aCancelableArg,
-                                           in unsigned long aCharIndex,
-                                           in float aElapsedTime,
-                                           in DOMString aName);
-
-  readonly attribute unsigned long charIndex;
-  readonly attribute float elapsedTime;
-  readonly attribute DOMString name;
-};
--- a/content/xml/document/src/nsXMLPrettyPrinter.cpp
+++ b/content/xml/document/src/nsXMLPrettyPrinter.cpp
@@ -19,17 +19,16 @@
 #include "nsIDOMDocumentFragment.h"
 #include "nsBindingManager.h"
 #include "nsXBLService.h"
 #include "nsIScriptSecurityManager.h"
 #include "mozilla/Preferences.h"
 #include "nsIDocument.h"
 #include "nsVariant.h"
 #include "nsIDOMCustomEvent.h"
-#include "GeneratedEvents.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_IMPL_ISUPPORTS(nsXMLPrettyPrinter,
                   nsIDocumentObserver,
                   nsIMutationObserver)
 
--- a/dom/apps/src/Webapps.jsm
+++ b/dom/apps/src/Webapps.jsm
@@ -69,26 +69,26 @@ XPCOMUtils.defineLazyGetter(this, "libcu
   Cu.import("resource://gre/modules/systemlibs.js");
   return libcutils;
 });
 #endif
 
 #ifdef MOZ_WIDGET_ANDROID
 // On Android, define the "debug" function as a binding of the "d" function
 // from the AndroidLog module so it gets the "debug" priority and a log tag.
-// We always report debug messages on Android because it's hard to use a debug
-// build on Android and unnecessary to restrict reporting, per bug 1003469.
+// We always report debug messages on Android because it's unnecessary
+// to restrict reporting, per bug 1003469.
 let debug = Cu.import("resource://gre/modules/AndroidLog.jsm", {})
               .AndroidLog.d.bind(null, "Webapps");
 #else
-function debug(aMsg) {
-#ifdef DEBUG
-  dump("-*- Webapps.jsm : " + aMsg + "\n");
-#endif
-}
+// Elsewhere, report debug messages only if dom.mozApps.debug is set to true.
+// The pref is only checked once, on startup, so restart after changing it.
+let debug = Services.prefs.getBoolPref("dom.mozApps.debug")
+              ? (aMsg) => dump("-*- Webapps.jsm : " + aMsg + "\n")
+              : (aMsg) => {};
 #endif
 
 function getNSPRErrorCode(err) {
   return -1 * ((err) & 0xffff);
 }
 
 function supportUseCurrentProfile() {
   return Services.prefs.getBoolPref("dom.webapps.useCurrentProfile");
--- a/dom/base/WindowNamedPropertiesHandler.cpp
+++ b/dom/base/WindowNamedPropertiesHandler.cpp
@@ -82,16 +82,17 @@ GetWindowFromGlobal(JSObject* aGlobal)
   return static_cast<nsGlobalWindow*>(piWin.get());
 }
 
 bool
 WindowNamedPropertiesHandler::getOwnPropertyDescriptor(JSContext* aCx,
                                                        JS::Handle<JSObject*> aProxy,
                                                        JS::Handle<jsid> aId,
                                                        JS::MutableHandle<JSPropertyDescriptor> aDesc)
+                                                       const
 {
   // Note: The infallibleInit call below depends on this check.
   if (!JSID_IS_STRING(aId)) {
     // Nothing to do if we're resolving a non-string property.
     return true;
   }
 
   JS::Rooted<JSObject*> global(aCx, JS_GetGlobalForObject(aCx, aProxy));
@@ -155,29 +156,29 @@ WindowNamedPropertiesHandler::getOwnProp
   aDesc.setAttributes(JSPROP_ENUMERATE);
   return true;
 }
 
 bool
 WindowNamedPropertiesHandler::defineProperty(JSContext* aCx,
                                              JS::Handle<JSObject*> aProxy,
                                              JS::Handle<jsid> aId,
-                                             JS::MutableHandle<JSPropertyDescriptor> aDesc)
+                                             JS::MutableHandle<JSPropertyDescriptor> aDesc) const
 {
   ErrorResult rv;
   rv.ThrowTypeError(MSG_DEFINEPROPERTY_ON_GSP);
   rv.ReportTypeError(aCx);
   return false;
 }
 
 bool
 WindowNamedPropertiesHandler::ownPropNames(JSContext* aCx,
                                            JS::Handle<JSObject*> aProxy,
                                            unsigned flags,
-                                           JS::AutoIdVector& aProps)
+                                           JS::AutoIdVector& aProps) const
 {
   // Grab the DOM window.
   nsGlobalWindow* win = GetWindowFromGlobal(JS_GetGlobalForObject(aCx, aProxy));
   nsTArray<nsString> names;
   win->GetSupportedNames(names);
   // Filter out the ones we wouldn't expose from getOwnPropertyDescriptor.
   // We iterate backwards so we can remove things from the list easily.
   for (size_t i = names.Length(); i > 0; ) {
@@ -205,17 +206,17 @@ WindowNamedPropertiesHandler::ownPropNam
   }
 
   return js::AppendUnique(aCx, aProps, docProps);
 }
 
 bool
 WindowNamedPropertiesHandler::delete_(JSContext* aCx,
                                       JS::Handle<JSObject*> aProxy,
-                                      JS::Handle<jsid> aId, bool* aBp)
+                                      JS::Handle<jsid> aId, bool* aBp) const
 {
   *aBp = false;
   return true;
 }
 
 // static
 void
 WindowNamedPropertiesHandler::Install(JSContext* aCx,
--- a/dom/base/WindowNamedPropertiesHandler.h
+++ b/dom/base/WindowNamedPropertiesHandler.h
@@ -10,59 +10,60 @@
 #include "mozilla/dom/DOMJSProxyHandler.h"
 
 namespace mozilla {
 namespace dom {
 
 class WindowNamedPropertiesHandler : public BaseDOMProxyHandler
 {
 public:
-  WindowNamedPropertiesHandler() : BaseDOMProxyHandler(nullptr)
+  WindowNamedPropertiesHandler()
+    : BaseDOMProxyHandler(nullptr, /* hasPrototype = */ true)
   {
-    setHasPrototype(true);
   }
   virtual bool
-  preventExtensions(JSContext* aCx, JS::Handle<JSObject*> aProxy) MOZ_OVERRIDE
+  preventExtensions(JSContext* aCx, JS::Handle<JSObject*> aProxy) const MOZ_OVERRIDE
   {
     // Throw a TypeError, per WebIDL.
     JS_ReportErrorNumber(aCx, js_GetErrorMessage, nullptr,
                          JSMSG_CANT_CHANGE_EXTENSIBILITY);
     return false;
   }
   virtual bool
   getOwnPropertyDescriptor(JSContext* aCx, JS::Handle<JSObject*> aProxy,
                            JS::Handle<jsid> aId,
-                           JS::MutableHandle<JSPropertyDescriptor> aDesc) MOZ_OVERRIDE;
+                           JS::MutableHandle<JSPropertyDescriptor> aDesc)
+                           const MOZ_OVERRIDE;
   virtual bool
   defineProperty(JSContext* aCx, JS::Handle<JSObject*> aProxy,
                  JS::Handle<jsid> aId,
-                 JS::MutableHandle<JSPropertyDescriptor> aDesc) MOZ_OVERRIDE;
+                 JS::MutableHandle<JSPropertyDescriptor> aDesc) const MOZ_OVERRIDE;
   virtual bool
   ownPropNames(JSContext* aCx, JS::Handle<JSObject*> aProxy, unsigned flags,
-               JS::AutoIdVector& aProps) MOZ_OVERRIDE;
+               JS::AutoIdVector& aProps) const MOZ_OVERRIDE;
   virtual bool
   delete_(JSContext* aCx, JS::Handle<JSObject*> aProxy, JS::Handle<jsid> aId,
-          bool* aBp) MOZ_OVERRIDE;
+          bool* aBp) const MOZ_OVERRIDE;
   virtual bool
   isExtensible(JSContext* aCx, JS::Handle<JSObject*> aProxy,
-               bool* aIsExtensible) MOZ_OVERRIDE
+               bool* aIsExtensible) const MOZ_OVERRIDE
   {
     *aIsExtensible = true;
     return true;
   }
   virtual const char*
-  className(JSContext *aCx, JS::Handle<JSObject*> aProxy) MOZ_OVERRIDE
+  className(JSContext *aCx, JS::Handle<JSObject*> aProxy) const MOZ_OVERRIDE
   {
     return "WindowProperties";
   }
 
-  static WindowNamedPropertiesHandler*
+  static const WindowNamedPropertiesHandler*
   getInstance()
   {
-    static WindowNamedPropertiesHandler instance;
+    static const WindowNamedPropertiesHandler instance;
     return &instance;
   }
 
   // For Install, aProto is the proto of the Window we're associated with.
   static void
   Install(JSContext *aCx, JS::Handle<JSObject*> aProto);
 };
 
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -82,19 +82,16 @@
 #include "nsIDocument.h"
 #include "Crypto.h"
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
 #include "nsIDOMCryptoLegacy.h"
 #endif
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMEvent.h"
-#include "nsIDOMPopupBlockedEvent.h"
-#include "nsIDOMPopStateEvent.h"
-#include "nsIDOMHashChangeEvent.h"
 #include "nsIDOMOfflineResourceList.h"
 #include "nsPIDOMStorage.h"
 #include "nsDOMString.h"
 #include "nsIEmbeddingSiteWindow.h"
 #include "nsThreadUtils.h"
 #include "nsILoadContext.h"
 #include "nsIMarkupDocumentViewer.h"
 #include "nsIPresShell.h"
@@ -141,17 +138,17 @@
 #include "nsFocusManager.h"
 #include "nsIXULWindow.h"
 #include "nsITimedChannel.h"
 #include "nsServiceManagerUtils.h"
 #ifdef MOZ_XUL
 #include "nsIDOMXULControlElement.h"
 #include "nsMenuPopupFrame.h"
 #endif
-#include "nsIDOMCustomEvent.h"
+#include "mozilla/dom/CustomEvent.h"
 #include "nsIFrameRequestCallback.h"
 #include "nsIJARChannel.h"
 
 #include "xpcprivate.h"
 
 #ifdef NS_PRINTING
 #include "nsIPrintSettings.h"
 #include "nsIPrintSettingsService.h"
@@ -174,18 +171,16 @@
 #include "nsIPopupWindowManager.h"
 
 #include "nsIDragService.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/Selection.h"
 #include "nsFrameLoader.h"
 #include "nsISupportsPrimitives.h"
 #include "nsXPCOMCID.h"
-#include "GeneratedEvents.h"
-#include "GeneratedEventClasses.h"
 #include "mozIThirdPartyUtil.h"
 #ifdef MOZ_LOGGING
 // so we can get logging even in release builds
 #define FORCE_PR_LOG 1
 #endif
 #include "prlog.h"
 #include "prenv.h"
 #include "prprf.h"
@@ -212,16 +207,19 @@
 #include "mozilla/DOMEventTargetHelper.h"
 #include "prrng.h"
 #include "nsSandboxFlags.h"
 #include "TimeChangeObserver.h"
 #include "mozilla/dom/AudioContext.h"
 #include "mozilla/dom/BrowserElementDictionariesBinding.h"
 #include "mozilla/dom/Console.h"
 #include "mozilla/dom/FunctionBinding.h"
+#include "mozilla/dom/HashChangeEvent.h"
+#include "mozilla/dom/PopStateEvent.h"
+#include "mozilla/dom/PopupBlockedEvent.h"
 #include "mozilla/dom/WindowBinding.h"
 #include "nsITabChild.h"
 #include "mozilla/dom/MediaQueryList.h"
 #include "mozilla/dom/ScriptSettings.h"
 #include "mozilla/dom/NavigatorBinding.h"
 #ifdef HAVE_SIDEBAR
 #include "mozilla/dom/ExternalBinding.h"
 #endif
@@ -596,99 +594,102 @@ NS_IMPL_CYCLE_COLLECTING_RELEASE(DialogV
 // nsOuterWindowProxy: Outer Window Proxy
 //*****************************************************************************
 
 class nsOuterWindowProxy : public js::Wrapper
 {
 public:
   nsOuterWindowProxy() : js::Wrapper(0) { }
 
-  virtual bool finalizeInBackground(JS::Value priv) {
+  virtual bool finalizeInBackground(JS::Value priv) const MOZ_OVERRIDE {
     return false;
   }
 
   virtual const char *className(JSContext *cx,
-                                JS::Handle<JSObject*> wrapper) MOZ_OVERRIDE;
-  virtual void finalize(JSFreeOp *fop, JSObject *proxy) MOZ_OVERRIDE;
+                                JS::Handle<JSObject*> wrapper) const MOZ_OVERRIDE;
+  virtual void finalize(JSFreeOp *fop, JSObject *proxy) const MOZ_OVERRIDE;
 
   // Fundamental traps
   virtual bool isExtensible(JSContext *cx, JS::Handle<JSObject*> proxy, bool *extensible)
-                           MOZ_OVERRIDE;
+                            const MOZ_OVERRIDE;
   virtual bool preventExtensions(JSContext *cx,
-                                 JS::Handle<JSObject*> proxy) MOZ_OVERRIDE;
+                                 JS::Handle<JSObject*> proxy) const MOZ_OVERRIDE;
   virtual bool getPropertyDescriptor(JSContext* cx,
                                      JS::Handle<JSObject*> proxy,
                                      JS::Handle<jsid> id,
-                                     JS::MutableHandle<JSPropertyDescriptor> desc) MOZ_OVERRIDE;
+                                     JS::MutableHandle<JSPropertyDescriptor> desc)
+                                     const MOZ_OVERRIDE;
   virtual bool getOwnPropertyDescriptor(JSContext* cx,
                                         JS::Handle<JSObject*> proxy,
                                         JS::Handle<jsid> id,
-                                        JS::MutableHandle<JSPropertyDescriptor> desc) MOZ_OVERRIDE;
+                                        JS::MutableHandle<JSPropertyDescriptor> desc)
+                                        const MOZ_OVERRIDE;
   virtual bool defineProperty(JSContext* cx,
                               JS::Handle<JSObject*> proxy,
                               JS::Handle<jsid> id,
-                              JS::MutableHandle<JSPropertyDescriptor> desc) MOZ_OVERRIDE;
+                              JS::MutableHandle<JSPropertyDescriptor> desc)
+                              const MOZ_OVERRIDE;
   virtual bool getOwnPropertyNames(JSContext *cx,
                                    JS::Handle<JSObject*> proxy,
-                                   JS::AutoIdVector &props) MOZ_OVERRIDE;
+                                   JS::AutoIdVector &props) const MOZ_OVERRIDE;
   virtual bool delete_(JSContext *cx, JS::Handle<JSObject*> proxy,
                        JS::Handle<jsid> id,
-                       bool *bp) MOZ_OVERRIDE;
+                       bool *bp) const MOZ_OVERRIDE;
   virtual bool enumerate(JSContext *cx, JS::Handle<JSObject*> proxy,
-                         JS::AutoIdVector &props) MOZ_OVERRIDE;
+                         JS::AutoIdVector &props) const MOZ_OVERRIDE;
 
   virtual bool watch(JSContext *cx, JS::Handle<JSObject*> proxy,
-                     JS::Handle<jsid> id, JS::Handle<JSObject*> callable) MOZ_OVERRIDE;
+                     JS::Handle<jsid> id, JS::Handle<JSObject*> callable) const MOZ_OVERRIDE;
   virtual bool unwatch(JSContext *cx, JS::Handle<JSObject*> proxy,
-                       JS::Handle<jsid> id) MOZ_OVERRIDE;
+                       JS::Handle<jsid> id) const MOZ_OVERRIDE;
 
   // Derived traps
   virtual bool has(JSContext *cx, JS::Handle<JSObject*> proxy,
-                   JS::Handle<jsid> id, bool *bp) MOZ_OVERRIDE;
+                   JS::Handle<jsid> id, bool *bp) const MOZ_OVERRIDE;
   virtual bool hasOwn(JSContext *cx, JS::Handle<JSObject*> proxy,
-                      JS::Handle<jsid> id, bool *bp) MOZ_OVERRIDE;
+                      JS::Handle<jsid> id, bool *bp) const MOZ_OVERRIDE;
   virtual bool get(JSContext *cx, JS::Handle<JSObject*> proxy,
                    JS::Handle<JSObject*> receiver,
                    JS::Handle<jsid> id,
-                   JS::MutableHandle<JS::Value> vp) MOZ_OVERRIDE;
+                   JS::MutableHandle<JS::Value> vp) const MOZ_OVERRIDE;
   virtual bool set(JSContext *cx, JS::Handle<JSObject*> proxy,
                    JS::Handle<JSObject*> receiver,
                    JS::Handle<jsid> id,
                    bool strict,
-                   JS::MutableHandle<JS::Value> vp) MOZ_OVERRIDE;
+                   JS::MutableHandle<JS::Value> vp) const MOZ_OVERRIDE;
   virtual bool keys(JSContext *cx, JS::Handle<JSObject*> proxy,
-                    JS::AutoIdVector &props) MOZ_OVERRIDE;
+                    JS::AutoIdVector &props) const MOZ_OVERRIDE;
   virtual bool iterate(JSContext *cx, JS::Handle<JSObject*> proxy,
                        unsigned flags,
-                       JS::MutableHandle<JS::Value> vp) MOZ_OVERRIDE;
-
-  static nsOuterWindowProxy singleton;
+                       JS::MutableHandle<JS::Value> vp) const MOZ_OVERRIDE;
+
+  static const nsOuterWindowProxy singleton;
 
 protected:
-  nsGlobalWindow* GetWindow(JSObject *proxy)
+  nsGlobalWindow* GetWindow(JSObject *proxy) const
   {
     return nsGlobalWindow::FromSupports(
       static_cast<nsISupports*>(js::GetProxyExtra(proxy, 0).toPrivate()));
   }
 
   // False return value means we threw an exception.  True return value
   // but false "found" means we didn't have a subframe at that index.
   bool GetSubframeWindow(JSContext *cx, JS::Handle<JSObject*> proxy,
                          JS::Handle<jsid> id,
                          JS::MutableHandle<JS::Value> vp,
-                         bool &found);
+                         bool &found) const;
 
   // Returns a non-null window only if id is an index and we have a
   // window at that index.
   already_AddRefed<nsIDOMWindow> GetSubframeWindow(JSContext *cx,
                                                    JS::Handle<JSObject*> proxy,
-                                                   JS::Handle<jsid> id);
+                                                   JS::Handle<jsid> id) const;
 
   bool AppendIndexedPropertyNames(JSContext *cx, JSObject *proxy,
-                                  JS::AutoIdVector &props);
+                                  JS::AutoIdVector &props) const;
 };
 
 const js::Class OuterWindowProxyClass =
     PROXY_CLASS_WITH_EXT(
         "Proxy",
         0, /* additional slots */
         0, /* additional class flags */
         nullptr, /* call */
@@ -697,45 +698,45 @@ const js::Class OuterWindowProxyClass =
             nullptr, /* outerObject */
             js::proxy_innerObject,
             nullptr, /* iteratorObject */
             false   /* isWrappedNative */
         ));
 
 bool
 nsOuterWindowProxy::isExtensible(JSContext *cx, JS::Handle<JSObject*> proxy,
-                                 bool *extensible)
+                                 bool *extensible) const
 {
   // If [[Extensible]] could be false, then navigating a window could navigate
   // to a window that's [[Extensible]] after being at one that wasn't: an
   // invariant violation.  So always report true for this.
   *extensible = true;
   return true;
 }
 
 bool
 nsOuterWindowProxy::preventExtensions(JSContext *cx,
-                                      JS::Handle<JSObject*> proxy)
+                                      JS::Handle<JSObject*> proxy) const
 {
   // See above.
   JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                        JSMSG_CANT_CHANGE_EXTENSIBILITY);
   return false;
 }
 
 const char *
-nsOuterWindowProxy::className(JSContext *cx, JS::Handle<JSObject*> proxy)
+nsOuterWindowProxy::className(JSContext *cx, JS::Handle<JSObject*> proxy) const
 {
     MOZ_ASSERT(js::IsProxy(proxy));
 
     return "Window";
 }
 
 void
-nsOuterWindowProxy::finalize(JSFreeOp *fop, JSObject *proxy)
+nsOuterWindowProxy::finalize(JSFreeOp *fop, JSObject *proxy) const
 {
   nsGlobalWindow* global = GetWindow(proxy);
   if (global) {
     global->ClearWrapper();
 
     // Ideally we would use OnFinalize here, but it's possible that
     // EnsureScriptEnvironment will later be called on the window, and we don't
     // want to create a new script object in that case. Therefore, we need to
@@ -743,17 +744,17 @@ nsOuterWindowProxy::finalize(JSFreeOp *f
     global->PoisonOuterWindowProxy(proxy);
   }
 }
 
 bool
 nsOuterWindowProxy::getPropertyDescriptor(JSContext* cx,
                                           JS::Handle<JSObject*> proxy,
                                           JS::Handle<jsid> id,
-                                          JS::MutableHandle<JSPropertyDescriptor> desc)
+                                          JS::MutableHandle<JSPropertyDescriptor> desc) const
 {
   // The only thing we can do differently from js::Wrapper is shadow stuff with
   // our indexed properties, so we can just try getOwnPropertyDescriptor and if
   // that gives us nothing call on through to js::Wrapper.
   desc.object().set(nullptr);
   if (!getOwnPropertyDescriptor(cx, proxy, id, desc)) {
     return false;
   }
@@ -765,16 +766,17 @@ nsOuterWindowProxy::getPropertyDescripto
   return js::Wrapper::getPropertyDescriptor(cx, proxy, id, desc);
 }
 
 bool
 nsOuterWindowProxy::getOwnPropertyDescriptor(JSContext* cx,
                                              JS::Handle<JSObject*> proxy,
                                              JS::Handle<jsid> id,
                                              JS::MutableHandle<JSPropertyDescriptor> desc)
+                                             const
 {
   bool found;
   if (!GetSubframeWindow(cx, proxy, id, desc.value(), found)) {
     return false;
   }
   if (found) {
     FillPropertyDescriptor(desc, proxy, true);
     return true;
@@ -784,49 +786,50 @@ nsOuterWindowProxy::getOwnPropertyDescri
   return js::Wrapper::getOwnPropertyDescriptor(cx, proxy, id, desc);
 }
 
 bool
 nsOuterWindowProxy::defineProperty(JSContext* cx,
                                    JS::Handle<JSObject*> proxy,
                                    JS::Handle<jsid> id,
                                    JS::MutableHandle<JSPropertyDescriptor> desc)
+                                   const
 {
   int32_t index = GetArrayIndexFromId(cx, id);
   if (IsArrayIndex(index)) {
     // Spec says to Reject whether this is a supported index or not,
     // since we have no indexed setter or indexed creator.  That means
     // throwing in strict mode (FIXME: Bug 828137), doing nothing in
     // non-strict mode.
     return true;
   }
 
   return js::Wrapper::defineProperty(cx, proxy, id, desc);
 }
 
 bool
 nsOuterWindowProxy::getOwnPropertyNames(JSContext *cx,
                                         JS::Handle<JSObject*> proxy,
-                                        JS::AutoIdVector &props)
+                                        JS::AutoIdVector &props) const
 {
   // Just our indexed stuff followed by our "normal" own property names.
   if (!AppendIndexedPropertyNames(cx, proxy, props)) {
     return false;
   }
 
   JS::AutoIdVector innerProps(cx);
   if (!js::Wrapper::getOwnPropertyNames(cx, proxy, innerProps)) {
     return false;
   }
   return js::AppendUnique(cx, props, innerProps);
 }
 
 bool
 nsOuterWindowProxy::delete_(JSContext *cx, JS::Handle<JSObject*> proxy,
-                            JS::Handle<jsid> id, bool *bp)
+                            JS::Handle<jsid> id, bool *bp) const
 {
   if (nsCOMPtr<nsIDOMWindow> frame = GetSubframeWindow(cx, proxy, id)) {
     // Reject (which means throw if strict, else return false) the delete.
     // Except we don't even know whether we're strict.  See bug 803157.
     *bp = false;
     return true;
   }
 
@@ -837,59 +840,59 @@ nsOuterWindowProxy::delete_(JSContext *c
     return true;
   }
 
   return js::Wrapper::delete_(cx, proxy, id, bp);
 }
 
 bool
 nsOuterWindowProxy::enumerate(JSContext *cx, JS::Handle<JSObject*> proxy,
-                              JS::AutoIdVector &props)
+                              JS::AutoIdVector &props) const
 {
   // Just our indexed stuff followed by our "normal" own property names.
   if (!AppendIndexedPropertyNames(cx, proxy, props)) {
     return false;
   }
 
   JS::AutoIdVector innerProps(cx);
   if (!js::Wrapper::enumerate(cx, proxy, innerProps)) {
     return false;
   }
   return js::AppendUnique(cx, props, innerProps);
 }
 
 bool
 nsOuterWindowProxy::has(JSContext *cx, JS::Handle<JSObject*> proxy,
-                        JS::Handle<jsid> id, bool *bp)
+                        JS::Handle<jsid> id, bool *bp) const
 {
   if (nsCOMPtr<nsIDOMWindow> frame = GetSubframeWindow(cx, proxy, id)) {
     *bp = true;
     return true;
   }
 
   return js::Wrapper::has(cx, proxy, id, bp);
 }
 
 bool
 nsOuterWindowProxy::hasOwn(JSContext *cx, JS::Handle<JSObject*> proxy,
-                           JS::Handle<jsid> id, bool *bp)
+                           JS::Handle<jsid> id, bool *bp) const
 {
   if (nsCOMPtr<nsIDOMWindow> frame = GetSubframeWindow(cx, proxy, id)) {
     *bp = true;
     return true;
   }
 
   return js::Wrapper::hasOwn(cx, proxy, id, bp);
 }
 
 bool
 nsOuterWindowProxy::get(JSContext *cx, JS::Handle<JSObject*> proxy,
                         JS::Handle<JSObject*> receiver,
                         JS::Handle<jsid> id,
-                        JS::MutableHandle<JS::Value> vp)
+                        JS::MutableHandle<JS::Value> vp) const
 {
   if (id == nsDOMClassInfo::sWrappedJSObject_id &&
       xpc::AccessCheck::isChrome(js::GetContextCompartment(cx))) {
     vp.set(JS::ObjectValue(*proxy));
     return true;
   }
 
   bool found;
@@ -904,54 +907,54 @@ nsOuterWindowProxy::get(JSContext *cx, J
   return js::Wrapper::get(cx, proxy, receiver, id, vp);
 }
 
 bool
 nsOuterWindowProxy::set(JSContext *cx, JS::Handle<JSObject*> proxy,
                         JS::Handle<JSObject*> receiver,
                         JS::Handle<jsid> id,
                         bool strict,
-                        JS::MutableHandle<JS::Value> vp)
+                        JS::MutableHandle<JS::Value> vp) const
 {
   int32_t index = GetArrayIndexFromId(cx, id);
   if (IsArrayIndex(index)) {
     // Reject (which means throw if and only if strict) the set.
     if (strict) {
       // XXXbz This needs to throw, but see bug 828137.
     }
     return true;
   }
 
   return js::Wrapper::set(cx, proxy, receiver, id, strict, vp);
 }
 
 bool
 nsOuterWindowProxy::keys(JSContext *cx, JS::Handle<JSObject*> proxy,
-                         JS::AutoIdVector &props)
+                         JS::AutoIdVector &props) const
 {
   // BaseProxyHandler::keys seems to do what we want here: call
   // getOwnPropertyNames and then filter out the non-enumerable properties.
   return js::BaseProxyHandler::keys(cx, proxy, props);
 }
 
 bool
 nsOuterWindowProxy::iterate(JSContext *cx, JS::Handle<JSObject*> proxy,
-                            unsigned flags, JS::MutableHandle<JS::Value> vp)
+                            unsigned flags, JS::MutableHandle<JS::Value> vp) const
 {
   // BaseProxyHandler::iterate seems to do what we want here: fall
   // back on the property names returned from keys() and enumerate().
   return js::BaseProxyHandler::iterate(cx, proxy, flags, vp);
 }
 
 bool
 nsOuterWindowProxy::GetSubframeWindow(JSContext *cx,
                                       JS::Handle<JSObject*> proxy,
                                       JS::Handle<jsid> id,
                                       JS::MutableHandle<JS::Value> vp,
-                                      bool& found)
+                                      bool& found) const
 {
   nsCOMPtr<nsIDOMWindow> frame = GetSubframeWindow(cx, proxy, id);
   if (!frame) {
     found = false;
     return true;
   }
 
   found = true;
@@ -968,81 +971,81 @@ nsOuterWindowProxy::GetSubframeWindow(JS
 
   vp.setObject(*obj);
   return JS_WrapValue(cx, vp);
 }
 
 already_AddRefed<nsIDOMWindow>
 nsOuterWindowProxy::GetSubframeWindow(JSContext *cx,
                                       JS::Handle<JSObject*> proxy,
-                                      JS::Handle<jsid> id)
+                                      JS::Handle<jsid> id) const
 {
   int32_t index = GetArrayIndexFromId(cx, id);
   if (!IsArrayIndex(index)) {
     return nullptr;
   }
 
   nsGlobalWindow* win = GetWindow(proxy);
   bool unused;
   return win->IndexedGetter(index, unused);
 }
 
 bool
 nsOuterWindowProxy::AppendIndexedPropertyNames(JSContext *cx, JSObject *proxy,
-                                               JS::AutoIdVector &props)
+                                               JS::AutoIdVector &props) const
 {
   uint32_t length = GetWindow(proxy)->Length();
   MOZ_ASSERT(int32_t(length) >= 0);
   if (!props.reserve(props.length() + length)) {
     return false;
   }
   for (int32_t i = 0; i < int32_t(length); ++i) {
     props.append(INT_TO_JSID(i));
   }
 
   return true;
 }
 
 bool
 nsOuterWindowProxy::watch(JSContext *cx, JS::Handle<JSObject*> proxy,
-                          JS::Handle<jsid> id, JS::Handle<JSObject*> callable)
+                          JS::Handle<jsid> id, JS::Handle<JSObject*> callable) const
 {
   return js::WatchGuts(cx, proxy, id, callable);
 }
 
 bool
 nsOuterWindowProxy::unwatch(JSContext *cx, JS::Handle<JSObject*> proxy,
-                            JS::Handle<jsid> id)
+                            JS::Handle<jsid> id) const
 {
   return js::UnwatchGuts(cx, proxy, id);
 }
 
-nsOuterWindowProxy
+const nsOuterWindowProxy
 nsOuterWindowProxy::singleton;
 
 class nsChromeOuterWindowProxy : public nsOuterWindowProxy
 {
 public:
   nsChromeOuterWindowProxy() : nsOuterWindowProxy() {}
 
-  virtual const char *className(JSContext *cx, JS::Handle<JSObject*> wrapper) MOZ_OVERRIDE;
-
-  static nsChromeOuterWindowProxy singleton;
+  virtual const char *className(JSContext *cx, JS::Handle<JSObject*> wrapper) const MOZ_OVERRIDE;
+
+  static const nsChromeOuterWindowProxy singleton;
 };
 
 const char *
 nsChromeOuterWindowProxy::className(JSContext *cx,
-                                    JS::Handle<JSObject*> proxy)
+                                    JS::Handle<JSObject*> proxy) const
 {
     MOZ_ASSERT(js::IsProxy(proxy));
 
     return "ChromeWindow";
 }
 
-nsChromeOuterWindowProxy
+const nsChromeOuterWindowProxy
 nsChromeOuterWindowProxy::singleton;
 
 static JSObject*
 NewOuterWindowProxy(JSContext *cx, JS::Handle<JSObject*> parent, bool isChrome)
 {
   JSAutoCompartment ac(cx, parent);
   js::WrapperOptions options;
   options.setClass(&OuterWindowProxyClass);
@@ -7370,41 +7373,43 @@ bool IsPopupBlocked(nsIDocument* aDoc)
     return true;
   }
 
   uint32_t permission = nsIPopupWindowManager::ALLOW_POPUP;
   pm->TestPermission(aDoc->NodePrincipal(), &permission);
   return permission == nsIPopupWindowManager::DENY_POPUP;
 }
 
-/* static */
 void
 nsGlobalWindow::FirePopupBlockedEvent(nsIDocument* aDoc,
-                                      nsIDOMWindow *aRequestingWindow, nsIURI *aPopupURI,
-                                      const nsAString &aPopupWindowName,
-                                      const nsAString &aPopupWindowFeatures)
-{
-  if (aDoc) {
-    // Fire a "DOMPopupBlocked" event so that the UI can hear about
-    // blocked popups.
-    nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(aDoc);
-    nsCOMPtr<nsIDOMEvent> event;
-    doc->CreateEvent(NS_LITERAL_STRING("PopupBlockedEvents"), getter_AddRefs(event));
-    if (event) {
-      nsCOMPtr<nsIDOMPopupBlockedEvent> pbev(do_QueryInterface(event));
-      pbev->InitPopupBlockedEvent(NS_LITERAL_STRING("DOMPopupBlocked"),
-                                  true, true, aRequestingWindow,
-                                  aPopupURI, aPopupWindowName,
-                                  aPopupWindowFeatures);
-      event->SetTrusted(true);
-
-      bool defaultActionEnabled;
-      aDoc->DispatchEvent(event, &defaultActionEnabled);
-    }
-  }
+                                      nsIURI* aPopupURI,
+                                      const nsAString& aPopupWindowName,
+                                      const nsAString& aPopupWindowFeatures)
+{
+  MOZ_ASSERT(aDoc);
+
+  // Fire a "DOMPopupBlocked" event so that the UI can hear about
+  // blocked popups.
+  PopupBlockedEventInit init;
+  init.mBubbles = true;
+  init.mCancelable = true;
+  init.mRequestingWindow = this;
+  init.mPopupWindowURI = aPopupURI;
+  init.mPopupWindowName = aPopupWindowName;
+  init.mPopupWindowFeatures = aPopupWindowFeatures;
+
+  nsRefPtr<PopupBlockedEvent> event =
+    PopupBlockedEvent::Constructor(aDoc,
+                                   NS_LITERAL_STRING("DOMPopupBlocked"),
+                                   init);
+
+  event->SetTrusted(true);
+
+  bool defaultActionEnabled;
+  aDoc->DispatchEvent(event, &defaultActionEnabled);
 }
 
 static void FirePopupWindowEvent(nsIDocument* aDoc)
 {
   // Fire a "PopupWindow" event
   nsContentUtils::DispatchTrustedEvent(aDoc, aDoc,
                                        NS_LITERAL_STRING("PopupWindow"),
                                        true, true);
@@ -7531,17 +7536,17 @@ nsGlobalWindow::FireAbuseEvents(bool aBl
   // use the base URI to build what would have been the popup's URI
   nsCOMPtr<nsIIOService> ios(do_GetService(NS_IOSERVICE_CONTRACTID));
   if (ios)
     ios->NewURI(NS_ConvertUTF16toUTF8(aPopupURL), 0, baseURL,
                 getter_AddRefs(popupURI));
 
   // fire an event chock full of informative URIs
   if (aBlocked) {
-    FirePopupBlockedEvent(topDoc, this, popupURI, aPopupWindowName,
+    FirePopupBlockedEvent(topDoc, popupURI, aPopupWindowName,
                           aPopupWindowFeatures);
   }
   if (aWindow)
     FirePopupWindowEvent(topDoc);
 }
 
 already_AddRefed<nsIDOMWindow>
 nsGlobalWindow::Open(const nsAString& aUrl, const nsAString& aName,
@@ -10095,37 +10100,30 @@ nsGlobalWindow::FireHashchange(const nsA
   NS_ENSURE_STATE(IsCurrentInnerWindow());
 
   nsIPresShell *shell = mDoc->GetShell();
   nsRefPtr<nsPresContext> presContext;
   if (shell) {
     presContext = shell->GetPresContext();
   }
 
-  // Create a new hashchange event.
-  nsCOMPtr<nsIDOMEvent> domEvent;
-  nsresult rv =
-    EventDispatcher::CreateEvent(this, presContext, nullptr,
-                                 NS_LITERAL_STRING("hashchangeevent"),
-                                 getter_AddRefs(domEvent));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIDOMHashChangeEvent> hashchangeEvent = do_QueryInterface(domEvent);
-  NS_ENSURE_TRUE(hashchangeEvent, NS_ERROR_UNEXPECTED);
-
-  // The hashchange event bubbles and isn't cancellable.
-  rv = hashchangeEvent->InitHashChangeEvent(NS_LITERAL_STRING("hashchange"),
-                                            true, false,
-                                            aOldURL, aNewURL);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  domEvent->SetTrusted(true);
+  HashChangeEventInit init;
+  init.mBubbles = true;
+  init.mCancelable = false;
+  init.mNewURL = aNewURL;
+  init.mOldURL = aOldURL;
+
+  nsRefPtr<HashChangeEvent> event =
+    HashChangeEvent::Constructor(this, NS_LITERAL_STRING("hashchange"),
+                                 init);
+
+  event->SetTrusted(true);
 
   bool dummy;
-  return DispatchEvent(hashchangeEvent, &dummy);
+  return DispatchEvent(event, &dummy);
 }
 
 nsresult
 nsGlobalWindow::DispatchSyncPopState()
 {
   FORWARD_TO_INNER(DispatchSyncPopState, (), NS_OK);
 
   NS_ASSERTION(nsContentUtils::IsSafeToRunScript(),
@@ -10152,41 +10150,43 @@ nsGlobalWindow::DispatchSyncPopState()
 
   // Obtain a presentation shell for use in creating a popstate event.
   nsIPresShell *shell = mDoc->GetShell();
   nsRefPtr<nsPresContext> presContext;
   if (shell) {
     presContext = shell->GetPresContext();
   }
 
-  // Create a new popstate event
-  nsCOMPtr<nsIDOMEvent> domEvent;
-  rv = EventDispatcher::CreateEvent(this, presContext, nullptr,
-                                    NS_LITERAL_STRING("popstateevent"),
-                                    getter_AddRefs(domEvent));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Initialize the popstate event, which does bubble but isn't cancellable.
-  nsCOMPtr<nsIDOMPopStateEvent> popstateEvent = do_QueryInterface(domEvent);
-  rv = popstateEvent->InitPopStateEvent(NS_LITERAL_STRING("popstate"),
-                                        true, false,
-                                        stateObj);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  domEvent->SetTrusted(true);
-
-  nsCOMPtr<EventTarget> outerWindow =
-    do_QueryInterface(GetOuterWindow());
-  NS_ENSURE_TRUE(outerWindow, NS_ERROR_UNEXPECTED);
-
-  rv = domEvent->SetTarget(outerWindow);
-  NS_ENSURE_SUCCESS(rv, rv);
+  bool result = true;
+  nsPIDOMWindow* outerWindow = GetOuterWindow();
+  nsCOMPtr<EventTarget> outerWindowET = do_QueryInterface(outerWindow);
+  NS_ENSURE_TRUE(outerWindowET, NS_ERROR_FAILURE);
+
+  AutoJSAPI jsapi;
+  result = jsapi.Init(outerWindow);
+  NS_ENSURE_TRUE(result, NS_ERROR_FAILURE);
+
+  JSContext* cx = jsapi.cx();
+  JS::Rooted<JS::Value> stateJSValue(cx, JS::NullValue());
+  result = stateObj ? VariantToJsval(cx, stateObj, &stateJSValue) : true;
+  NS_ENSURE_TRUE(result, NS_ERROR_FAILURE);
+
+  RootedDictionary<PopStateEventInit> init(cx);
+  init.mBubbles = true;
+  init.mCancelable = false;
+  init.mState = stateJSValue;
+
+  nsRefPtr<PopStateEvent> event =
+    PopStateEvent::Constructor(outerWindowET, NS_LITERAL_STRING("popstate"),
+                               init);
+  event->SetTrusted(true);
+  event->SetTarget(outerWindowET);
 
   bool dummy; // default action
-  return DispatchEvent(popstateEvent, &dummy);
+  return DispatchEvent(event, &dummy);
 }
 
 // Find an nsICanvasFrame under aFrame.  Only search the principal
 // child lists.  aFrame must be non-null.
 static nsCanvasFrame* FindCanvasFrame(nsIFrame* aFrame)
 {
     nsCanvasFrame* canvasFrame = do_QueryFrame(aFrame);
     if (canvasFrame) {
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -677,20 +677,21 @@ public:
   void MaybeForgiveSpamCount();
   bool IsClosedOrClosing() {
     return (mIsClosed ||
             mInClose ||
             mHavePendingClose ||
             mCleanedUp);
   }
 
-  static void FirePopupBlockedEvent(nsIDocument* aDoc,
-                                    nsIDOMWindow *aRequestingWindow, nsIURI *aPopupURI,
-                                    const nsAString &aPopupWindowName,
-                                    const nsAString &aPopupWindowFeatures);
+  virtual void
+  FirePopupBlockedEvent(nsIDocument* aDoc,
+                        nsIURI* aPopupURI,
+                        const nsAString& aPopupWindowName,
+                        const nsAString& aPopupWindowFeatures) MOZ_OVERRIDE;
 
   virtual uint32_t GetSerial() {
     return mSerial;
   }
 
   static nsGlobalWindow* GetOuterWindowWithId(uint64_t aWindowID) {
     if (!sWindowsById) {
       return nullptr;
--- a/dom/base/nsPIDOMWindow.h
+++ b/dom/base/nsPIDOMWindow.h
@@ -55,18 +55,18 @@ enum PopupControlState {
 enum UIStateChangeType
 {
   UIStateChangeType_NoChange,
   UIStateChangeType_Set,
   UIStateChangeType_Clear
 };
 
 #define NS_PIDOMWINDOW_IID \
-{ 0x33403513, 0x6e4a, 0x4985, \
-  { 0x99, 0x8d, 0xfc, 0x02, 0x81, 0x6e, 0xb9, 0xf2 } }
+{ 0x71412748, 0x6368, 0x4332, \
+  { 0x82, 0x66, 0xff, 0xaa, 0x19, 0xda, 0x09, 0x7c } }
 
 class nsPIDOMWindow : public nsIDOMWindowInternal
 {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_PIDOMWINDOW_IID)
 
   virtual nsPIDOMWindow* GetPrivateRoot() = 0;
 
@@ -117,62 +117,38 @@ public:
     if (!mParentTarget) {
       UpdateParentTarget();
     }
     return mParentTarget;
   }
 
   bool HasMutationListeners(uint32_t aMutationEventType) const
   {
-    const nsPIDOMWindow *win;
-
-    if (IsOuterWindow()) {
-      win = GetCurrentInnerWindow();
-
-      if (!win) {
-        NS_ERROR("No current inner window available!");
+    MOZ_ASSERT(IsInnerWindow());
 
-        return false;
-      }
-    } else {
-      if (!mOuterWindow) {
-        NS_ERROR("HasMutationListeners() called on orphan inner window!");
+    if (!mOuterWindow) {
+      NS_ERROR("HasMutationListeners() called on orphan inner window!");
 
-        return false;
-      }
-
-      win = this;
+      return false;
     }
 
-    return (win->mMutationBits & aMutationEventType) != 0;
+    return (mMutationBits & aMutationEventType) != 0;
   }
 
   void SetMutationListeners(uint32_t aType)
   {
-    nsPIDOMWindow *win;
-
-    if (IsOuterWindow()) {
-      win = GetCurrentInnerWindow();
-
-      if (!win) {
-        NS_ERROR("No inner window available to set mutation bits on!");
+    MOZ_ASSERT(IsInnerWindow());
 
-        return;
-      }
-    } else {
-      if (!mOuterWindow) {
-        NS_ERROR("HasMutationListeners() called on orphan inner window!");
+    if (!mOuterWindow) {
+      NS_ERROR("HasMutationListeners() called on orphan inner window!");
 
-        return;
-      }
-
-      win = this;
+      return;
     }
 
-    win->mMutationBits |= aType;
+    mMutationBits |= aType;
   }
 
   virtual void MaybeUpdateTouchState() {}
   virtual void UpdateTouchState() {}
 
   nsIDocument* GetExtantDoc() const
   {
     return mDoc;
@@ -700,16 +676,25 @@ public:
    * Like nsIDOMWindow::Open, except that we don't navigate to the given URL.
    *
    * Outer windows only.
    */
   virtual nsresult
   OpenNoNavigate(const nsAString& aUrl, const nsAString& aName,
                  const nsAString& aOptions, nsIDOMWindow **_retval) = 0;
 
+  /**
+   * Fire a popup blocked event on the document.
+   */
+  virtual void
+  FirePopupBlockedEvent(nsIDocument* aDoc,
+                        nsIURI* aPopupURI,
+                        const nsAString& aPopupWindowName,
+                        const nsAString& aPopupWindowFeatures) = 0;
+
   // Inner windows only.
   void AddAudioContext(mozilla::dom::AudioContext* aAudioContext);
   void RemoveAudioContext(mozilla::dom::AudioContext* aAudioContext);
   void MuteAudioContexts();
   void UnmuteAudioContexts();
 
   // Given an inner window, return its outer if the inner is the current inner.
   // Otherwise (argument null or not an inner or not current) return null.
--- a/dom/base/nsPluginArray.cpp
+++ b/dom/base/nsPluginArray.cpp
@@ -361,16 +361,20 @@ NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(ns
 nsPluginElement::nsPluginElement(nsPIDOMWindow* aWindow,
                                  nsPluginTag* aPluginTag)
   : mWindow(aWindow),
     mPluginTag(aPluginTag)
 {
   SetIsDOMBinding();
 }
 
+nsPluginElement::~nsPluginElement()
+{
+}
+
 nsPIDOMWindow*
 nsPluginElement::GetParentObject() const
 {
   MOZ_ASSERT(mWindow);
   return mWindow;
 }
 
 JSObject*
--- a/dom/base/nsPluginArray.h
+++ b/dom/base/nsPluginArray.h
@@ -6,17 +6,16 @@
 
 #ifndef nsPluginArray_h___
 #define nsPluginArray_h___
 
 #include "nsTArray.h"
 #include "nsWeakReference.h"
 #include "nsIObserver.h"
 #include "nsWrapperCache.h"
-#include "nsMimeTypeArray.h"
 #include "nsPluginTags.h"
 #include "nsPIDOMWindow.h"
 
 class nsPluginElement;
 class nsMimeType;
 
 class nsPluginArray MOZ_FINAL : public nsIObserver,
                                 public nsSupportsWeakReference,
@@ -105,17 +104,17 @@ public:
   nsMimeType* NamedGetter(const nsAString& name, bool &found);
   bool NameIsEnumerable(const nsAString& aName);
   uint32_t Length();
   void GetSupportedNames(unsigned, nsTArray<nsString>& retval);
 
   nsTArray<nsRefPtr<nsMimeType> >& MimeTypes();
 
 protected:
-  ~nsPluginElement() {}
+  ~nsPluginElement();
 
   void EnsurePluginMimeTypes();
 
   nsCOMPtr<nsPIDOMWindow> mWindow;
   nsRefPtr<nsPluginTag> mPluginTag;
   nsTArray<nsRefPtr<nsMimeType> > mMimeTypes;
 };
 
--- a/dom/bindings/BindingUtils.cpp
+++ b/dom/bindings/BindingUtils.cpp
@@ -1267,20 +1267,17 @@ XrayResolveNativeProperty(JSContext* cx,
 bool
 XrayDefineProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
                    JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
                    JS::MutableHandle<JSPropertyDescriptor> desc, bool* defined)
 {
   if (!js::IsProxy(obj))
       return true;
 
-  MOZ_ASSERT(IsDOMProxy(obj), "What kind of proxy is this?");
-
-  DOMProxyHandler* handler =
-    static_cast<DOMProxyHandler*>(js::GetProxyHandler(obj));
+  const DOMProxyHandler* handler = GetDOMProxyHandler(obj);
   return handler->defineProperty(cx, wrapper, id, desc, defined);
 }
 
 bool
 XrayEnumerateAttributes(JSContext* cx, JS::Handle<JSObject*> wrapper,
                         JS::Handle<JSObject*> obj,
                         const Prefable<const JSPropertySpec>* attributes,
                         jsid* attributeIds, const JSPropertySpec* attributeSpecs,
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -8361,17 +8361,17 @@ class CGUnionStruct(CGThing):
                     "ToJSVal",
                     "bool",
                     [
                         Argument("JSContext*", "cx"),
                         Argument("JS::Handle<JSObject*>", "scopeObj"),
                         Argument("JS::MutableHandle<JS::Value>", "rval")
                     ],
                     body=CGSwitch("mType", toJSValCases,
-                                  default=CGGeneric("return false;\n")).define(),
+                                  default=CGGeneric("return false;\n")).define() + "\nreturn false;\n",
                     const=True))
 
         constructors = [ctor]
         selfName = CGUnionStruct.unionTypeName(self.type, self.ownsMembers)
         if self.ownsMembers:
             if traceCases:
                 traceBody = CGSwitch("mType", traceCases,
                                      default=CGGeneric("")).define()
@@ -9482,17 +9482,17 @@ class CGProxyUnwrap(CGAbstractMethod):
 
 class CGDOMJSProxyHandler_getOwnPropertyDescriptor(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('JS::MutableHandle<JSPropertyDescriptor>', 'desc')]
         ClassMethod.__init__(self, "getOwnPropertyDescriptor", "bool", args,
-                             virtual=True, override=True)
+                             virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         indexedGetter = self.descriptor.operations['IndexedGetter']
         indexedSetter = self.descriptor.operations['IndexedSetter']
 
         if self.descriptor.supportsIndexedProperties():
             readonly = toStringBool(indexedSetter is None)
@@ -9593,17 +9593,17 @@ class CGDOMJSProxyHandler_getOwnProperty
 
 class CGDOMJSProxyHandler_defineProperty(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('JS::MutableHandle<JSPropertyDescriptor>', 'desc'),
                 Argument('bool*', 'defined')]
-        ClassMethod.__init__(self, "defineProperty", "bool", args, virtual=True, override=True)
+        ClassMethod.__init__(self, "defineProperty", "bool", args, virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         set = ""
 
         indexedSetter = self.descriptor.operations['IndexedSetter']
         if indexedSetter:
             if self.descriptor.operations['IndexedCreator'] is not indexedSetter:
@@ -9674,17 +9674,17 @@ class CGDOMJSProxyHandler_defineProperty
 
 class CGDOMJSProxyHandler_delete(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('bool*', 'bp')]
         ClassMethod.__init__(self, "delete_", "bool", args,
-                             virtual=True, override=True)
+                             virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         def getDeleterBody(type):
             """
             type should be "Named" or "Indexed"
             """
             assert type in ("Named", "Indexed")
@@ -9773,17 +9773,17 @@ class CGDOMJSProxyHandler_delete(ClassMe
 
 class CGDOMJSProxyHandler_ownPropNames(ClassMethod):
     def __init__(self, descriptor, ):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('unsigned', 'flags'),
                 Argument('JS::AutoIdVector&', 'props')]
         ClassMethod.__init__(self, "ownPropNames", "bool", args,
-                             virtual=True, override=True)
+                             virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         # Per spec, we do indices, then named props, then everything else
         if self.descriptor.supportsIndexedProperties():
             addIndices = dedent("""
 
                 uint32_t length = UnwrapProxy(proxy)->Length();
@@ -9849,17 +9849,17 @@ class CGDOMJSProxyHandler_ownPropNames(C
 
 class CGDOMJSProxyHandler_hasOwn(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('bool*', 'bp')]
         ClassMethod.__init__(self, "hasOwn", "bool", args,
-                             virtual=True, override=True)
+                             virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         if self.descriptor.supportsIndexedProperties():
             indexed = fill(
                 """
                 int32_t index = GetArrayIndexFromId(cx, id);
                 if (IsArrayIndex(index)) {
@@ -9931,17 +9931,17 @@ class CGDOMJSProxyHandler_hasOwn(ClassMe
 class CGDOMJSProxyHandler_get(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<JSObject*>', 'receiver'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('JS::MutableHandle<JS::Value>', 'vp')]
         ClassMethod.__init__(self, "get", "bool", args,
-                             virtual=True, override=True)
+                             virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         getUnforgeableOrExpando = "JS::Rooted<JSObject*> sharedRoot(cx);\n"
         if UseHolderForUnforgeable(self.descriptor):
             hasUnforgeable = dedent("""
                 bool hasUnforgeable;
                 if (!JS_AlreadyHasOwnPropertyById(cx, ${holder}, id, &hasUnforgeable)) {
@@ -10033,17 +10033,17 @@ class CGDOMJSProxyHandler_get(ClassMetho
 
 class CGDOMJSProxyHandler_setCustom(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('JS::MutableHandle<JS::Value>', 'vp'),
                 Argument('bool*', 'done')]
-        ClassMethod.__init__(self, "setCustom", "bool", args, virtual=True, override=True)
+        ClassMethod.__init__(self, "setCustom", "bool", args, virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         assertion = ("MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),\n"
                      '           "Should not have a XrayWrapper here");\n')
 
         # Correctness first. If we have a NamedSetter and [OverrideBuiltins],
         # always call the NamedSetter and never do anything else.
@@ -10096,56 +10096,56 @@ class CGDOMJSProxyHandler_setCustom(Clas
                 "return true;\n")
 
 
 class CGDOMJSProxyHandler_className(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy')]
         ClassMethod.__init__(self, "className", "const char*", args,
-                             virtual=True, override=True)
+                             virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         return 'return "%s";\n' % self.descriptor.name
 
 
 class CGDOMJSProxyHandler_finalizeInBackground(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JS::Value', 'priv')]
         ClassMethod.__init__(self, "finalizeInBackground", "bool", args,
-                             virtual=True, override=True)
+                             virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         return "return false;\n"
 
 
 class CGDOMJSProxyHandler_finalize(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSFreeOp*', 'fop'), Argument('JSObject*', 'proxy')]
         ClassMethod.__init__(self, "finalize", "void", args,
-                             virtual=True, override=True)
+                             virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         return ("%s* self = UnwrapProxy(proxy);\n\n" % self.descriptor.nativeType +
                 finalizeHook(self.descriptor, FINALIZE_HOOK_NAME, self.args[0].name).define())
 
 
 class CGDOMJSProxyHandler_slice(ClassMethod):
     def __init__(self, descriptor):
         assert descriptor.supportsIndexedProperties()
 
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('uint32_t', 'begin'),
                 Argument('uint32_t', 'end'),
                 Argument('JS::Handle<JSObject*>', 'array')]
-        ClassMethod.__init__(self, "slice", "bool", args, virtual=True, override=True)
+        ClassMethod.__init__(self, "slice", "bool", args, virtual=True, override=True, const=True)
         self.descriptor = descriptor
 
     def getBody(self):
         # Just like getOwnPropertyNames we'll assume that we have no holes, so
         # we have all properties from 0 to length.  If that ever changes
         # (unlikely), we'll need to do something a bit more clever with how we
         # forward on to our ancestor.
 
@@ -10184,21 +10184,21 @@ class CGDOMJSProxyHandler_slice(ClassMet
             return true;
             """,
             nativeType=self.descriptor.nativeType,
             get=get)
 
 
 class CGDOMJSProxyHandler_getInstance(ClassMethod):
     def __init__(self):
-        ClassMethod.__init__(self, "getInstance", "DOMProxyHandler*", [], static=True)
+        ClassMethod.__init__(self, "getInstance", "const DOMProxyHandler*", [], static=True)
 
     def getBody(self):
         return dedent("""
-            static DOMProxyHandler instance;
+            static const DOMProxyHandler instance;
             return &instance;
             """)
 
 
 class CGDOMJSProxyHandler(CGClass):
     def __init__(self, descriptor):
         assert (descriptor.supportsIndexedProperties() or
                 descriptor.supportsNamedProperties())
@@ -10209,25 +10209,35 @@ class CGDOMJSProxyHandler(CGClass):
                    CGDOMJSProxyHandler_ownPropNames(descriptor),
                    CGDOMJSProxyHandler_hasOwn(descriptor),
                    CGDOMJSProxyHandler_get(descriptor),
                    CGDOMJSProxyHandler_className(descriptor),
                    CGDOMJSProxyHandler_finalizeInBackground(descriptor),
                    CGDOMJSProxyHandler_finalize(descriptor),
                    CGDOMJSProxyHandler_getInstance(),
                    CGDOMJSProxyHandler_delete(descriptor)]
+        constructors = [
+            ClassConstructor(
+                [],
+                bodyInHeader=True,
+                visibility="public",
+                explicit=True)
+        ]
+
+
         if descriptor.supportsIndexedProperties():
             methods.append(CGDOMJSProxyHandler_slice(descriptor))
         if (descriptor.operations['IndexedSetter'] is not None or
             (descriptor.operations['NamedSetter'] is not None and
              descriptor.interface.getExtendedAttribute('OverrideBuiltins'))):
             methods.append(CGDOMJSProxyHandler_setCustom(descriptor))
 
         CGClass.__init__(self, 'DOMProxyHandler',
                          bases=[ClassBase('mozilla::dom::DOMProxyHandler')],
+                         constructors=constructors,
                          methods=methods)
 
 
 class CGDOMJSProxyHandlerDeclarer(CGThing):
     """
     A class for declaring a DOMProxyHandler.
     """
     def __init__(self, handlerThing):
@@ -13667,56 +13677,117 @@ class CGEventGetter(CGNativeMember):
 
 class CGEventSetter(CGNativeMember):
     def __init__(self):
         raise TypeError("Event code generator does not support setters!")
 
 
 class CGEventMethod(CGNativeMember):
     def __init__(self, descriptor, method, signature, isConstructor, breakAfter=True):
-        if not isConstructor:
-            raise TypeError("Event code generator does not support methods!")
-        self.wantsConstructorForNativeCaller = True
+        self.isInit = False
+
         CGNativeMember.__init__(self, descriptor, method,
                                 CGSpecializedMethod.makeNativeName(descriptor,
                                                                    method),
                                 signature,
                                 descriptor.getExtendedAttributes(method),
                                 breakAfter=breakAfter,
                                 variadicIsSequence=True)
         self.originalArgs = list(self.args)
 
+        iface = descriptor.interface
+        allowed = isConstructor
+        if not allowed and iface.getExtendedAttribute("LegacyEventInit"):
+            # Allow it, only if it fits the initFooEvent profile exactly
+            # We could check the arg types but it's not worth the effort.
+            if (method.identifier.name == "init" + iface.identifier.name and
+                signature[1][0].type.isDOMString() and
+                signature[1][1].type.isBoolean() and
+                signature[1][2].type.isBoolean() and
+                # -3 on the left to ignore the type, bubbles, and cancelable parameters
+                # -1 on the right to ignore the .trusted property which bleeds through
+                # here because it is [Unforgeable].
+                len(signature[1]) - 3 == len(filter(lambda x: x.isAttr(), iface.members)) - 1):
+                allowed = True
+                self.isInit = True
+
+        if not allowed:
+            raise TypeError("Event code generator does not support methods!")
+
+
     def getArgs(self, returnType, argList):
         args = [self.getArg(arg) for arg in argList]
         return args
 
     def getArg(self, arg):
         decl, ref = self.getArgType(arg.type,
                                     arg.optional and not arg.defaultValue,
                                     "Variadic" if arg.variadic else False)
         if ref:
             decl = CGWrapper(decl, pre="const ", post="&")
 
         name = arg.identifier.name
         name = "a" + name[0].upper() + name[1:]
         return Argument(decl.define(), name)
 
     def declare(self, cgClass):
-        self.args = list(self.originalArgs)
-        self.args.insert(0, Argument("mozilla::dom::EventTarget*", "aOwner"))
-        constructorForNativeCaller = CGNativeMember.declare(self, cgClass)
+        if self.isInit:
+            constructorForNativeCaller = ""
+        else:
+            self.args = list(self.originalArgs)
+            self.args.insert(0, Argument("mozilla::dom::EventTarget*", "aOwner"))
+            constructorForNativeCaller = CGNativeMember.declare(self, cgClass)
+
         self.args = list(self.originalArgs)
         if needCx(None, self.arguments(), [], considerTypes=True, static=True):
             self.args.insert(0, Argument("JSContext*", "aCx"))
-        self.args.insert(0, Argument("const GlobalObject&", "aGlobal"))
+        if not self.isInit:
+            self.args.insert(0, Argument("const GlobalObject&", "aGlobal"))
         self.args.append(Argument('ErrorResult&', 'aRv'))
         return constructorForNativeCaller + CGNativeMember.declare(self, cgClass)
 
+    def defineInit(self, cgClass):
+        iface = self.descriptorProvider.interface
+        members = ""
+        while iface.identifier.name != "Event":
+            i = 3 # Skip the boilerplate args: type, bubble,s cancelable.
+            for m in iface.members:
+                if m.isAttr():
+                    # We need to initialize all the member variables that do
+                    # not come from Event.
+                    if getattr(m, "originatingInterface",
+                               iface).identifier.name == "Event":
+                        continue
+                    name = CGDictionary.makeMemberName(m.identifier.name)
+                    members += "%s = %s;\n" % (name, self.args[i].name)
+                    i += 1
+            iface = iface.parent
+
+        self.body = fill(
+            """
+            nsresult rv = InitEvent(${typeArg}, ${bubblesArg}, ${cancelableArg});
+            if (NS_FAILED(rv)) {
+              aRv.Throw(rv);
+              return;
+            }
+            ${members}
+            """,
+            typeArg = self.args[0].name,
+            bubblesArg = self.args[1].name,
+            cancelableArg = self.args[2].name,
+            members = members)
+
+        self.args.append(Argument('ErrorResult&', 'aRv'))
+
+        return CGNativeMember.define(self, cgClass)
+
     def define(self, cgClass):
         self.args = list(self.originalArgs)
+        if self.isInit:
+            return self.defineInit(cgClass)
         members = ""
         holdJS = ""
         iface = self.descriptorProvider.interface
         while iface.identifier.name != "Event":
             for m in self.descriptorProvider.getDescriptor(iface.identifier.name).interface.members:
                 if m.isAttr():
                     # We initialize all the other member variables in the
                     # Constructor except those ones coming from the Event.
--- a/dom/bindings/DOMJSProxyHandler.cpp
+++ b/dom/bindings/DOMJSProxyHandler.cpp
@@ -141,37 +141,37 @@ DOMProxyHandler::EnsureExpandoObject(JSC
 
   cache->SetPreservingWrapper(true);
   js::SetProxyExtra(obj, JSPROXYSLOT_EXPANDO, ObjectValue(*expando));
 
   return expando;
 }
 
 bool
-DOMProxyHandler::isExtensible(JSContext *cx, JS::Handle<JSObject*> proxy, bool *extensible)
+DOMProxyHandler::isExtensible(JSContext *cx, JS::Handle<JSObject*> proxy, bool *extensible) const
 {
   // always extensible per WebIDL
   *extensible = true;
   return true;
 }
 
 bool
-DOMProxyHandler::preventExtensions(JSContext *cx, JS::Handle<JSObject*> proxy)
+DOMProxyHandler::preventExtensions(JSContext *cx, JS::Handle<JSObject*> proxy) const
 {
   // Throw a TypeError, per WebIDL.
   JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
                        JSMSG_CANT_CHANGE_EXTENSIBILITY);
   return false;
 }
 
 bool
 BaseDOMProxyHandler::getPropertyDescriptor(JSContext* cx,
                                            JS::Handle<JSObject*> proxy,
                                            JS::Handle<jsid> id,
-                                           MutableHandle<JSPropertyDescriptor> desc)
+                                           MutableHandle<JSPropertyDescriptor> desc) const
 {
   if (!getOwnPropertyDescriptor(cx, proxy, id, desc)) {
     return false;
   }
   if (desc.object()) {
     return true;
   }
 
@@ -184,17 +184,17 @@ BaseDOMProxyHandler::getPropertyDescript
     return true;
   }
 
   return JS_GetPropertyDescriptorById(cx, proto, id, desc);
 }
 
 bool
 DOMProxyHandler::defineProperty(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
-                                MutableHandle<JSPropertyDescriptor> desc, bool* defined)
+                                MutableHandle<JSPropertyDescriptor> desc, bool* defined) const
 {
   if (desc.hasGetterObject() && desc.setter() == JS_StrictPropertyStub) {
     return JS_ReportErrorFlagsAndNumber(cx,
                                         JSREPORT_WARNING | JSREPORT_STRICT |
                                         JSREPORT_STRICT_MODE_ERROR,
                                         js_GetErrorMessage, nullptr,
                                         JSMSG_GETTER_ONLY);
   }
@@ -209,86 +209,86 @@ DOMProxyHandler::defineProperty(JSContex
   }
 
   bool dummy;
   return js_DefineOwnProperty(cx, expando, id, desc, &dummy);
 }
 
 bool
 DOMProxyHandler::set(JSContext *cx, Handle<JSObject*> proxy, Handle<JSObject*> receiver,
-                     Handle<jsid> id, bool strict, MutableHandle<JS::Value> vp)
+                     Handle<jsid> id, bool strict, MutableHandle<JS::Value> vp) const
 {
   MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
              "Should not have a XrayWrapper here");
   bool done;
   if (!setCustom(cx, proxy, id, vp, &done)) {
     return false;
   }
   if (done) {
     return true;
   }
   return mozilla::dom::BaseDOMProxyHandler::set(cx, proxy, receiver, id, strict, vp);
 }
 
 bool
 DOMProxyHandler::delete_(JSContext* cx, JS::Handle<JSObject*> proxy,
-                         JS::Handle<jsid> id, bool* bp)
+                         JS::Handle<jsid> id, bool* bp) const
 {
   JS::Rooted<JSObject*> expando(cx);
   if (!xpc::WrapperFactory::IsXrayWrapper(proxy) && (expando = GetExpandoObject(proxy))) {
     return JS_DeletePropertyById2(cx, expando, id, bp);
   }
 
   *bp = true;
   return true;
 }
 
 bool
 BaseDOMProxyHandler::enumerate(JSContext* cx, JS::Handle<JSObject*> proxy,
-                               AutoIdVector& props)
+                               AutoIdVector& props) const
 {
   JS::Rooted<JSObject*> proto(cx);
   if (!JS_GetPrototype(cx, proxy, &proto))  {
     return false;
   }
   return keys(cx, proxy, props) &&
          (!proto || js::GetPropertyNames(cx, proto, 0, &props));
 }
 
 bool
 BaseDOMProxyHandler::watch(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
-                           JS::Handle<JSObject*> callable)
+                           JS::Handle<JSObject*> callable) const
 {
   return js::WatchGuts(cx, proxy, id, callable);
 }
 
 bool
-BaseDOMProxyHandler::unwatch(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id)
+BaseDOMProxyHandler::unwatch(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id) const
 {
   return js::UnwatchGuts(cx, proxy, id);
 }
 
 bool
 BaseDOMProxyHandler::getOwnPropertyNames(JSContext* cx,
                                          JS::Handle<JSObject*> proxy,
-                                         JS::AutoIdVector& props)
+                                         JS::AutoIdVector& props) const
 {
   return ownPropNames(cx, proxy, JSITER_OWNONLY | JSITER_HIDDEN, props);
 }
 
 bool
 BaseDOMProxyHandler::keys(JSContext* cx,
                           JS::Handle<JSObject*> proxy,
-                          JS::AutoIdVector& props)
+                          JS::AutoIdVector& props) const
 {
   return ownPropNames(cx, proxy, JSITER_OWNONLY, props);
 }
 
 bool
-DOMProxyHandler::has(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, bool* bp)
+DOMProxyHandler::has(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, bool* bp) const
 {
   if (!hasOwn(cx, proxy, id, bp)) {
     return false;
   }
 
   if (*bp) {
     // We have the property ourselves; no need to worry about our prototype
     // chain.
@@ -323,16 +323,16 @@ IdToInt32(JSContext* cx, JS::Handle<jsid
     return -1;
   }
 
   return i;
 }
 
 bool
 DOMProxyHandler::setCustom(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
-                           JS::MutableHandle<JS::Value> vp, bool *done)
+                           JS::MutableHandle<JS::Value> vp, bool *done) const
 {
   *done = false;
   return true;
 }
 
 } // namespace dom
 } // namespace mozilla
--- a/dom/bindings/DOMJSProxyHandler.h
+++ b/dom/bindings/DOMJSProxyHandler.h
@@ -33,81 +33,85 @@ inline bool IsDOMProxy(JSObject *obj)
     const js::Class* clasp = js::GetObjectClass(obj);
     return clasp->isProxy() &&
            js::GetProxyHandler(obj)->family() == ProxyFamily();
 }
 
 class BaseDOMProxyHandler : public js::BaseProxyHandler
 {
 public:
-  BaseDOMProxyHandler(const void* aProxyFamily)
-    : js::BaseProxyHandler(aProxyFamily)
+  BaseDOMProxyHandler(const void* aProxyFamily, bool aHasPrototype = false)
+    : js::BaseProxyHandler(aProxyFamily, aHasPrototype)
   {}
 
   // Implementations of traps that can be implemented in terms of
   // fundamental traps.
   bool enumerate(JSContext* cx, JS::Handle<JSObject*> proxy,
-                 JS::AutoIdVector& props) MOZ_OVERRIDE;
+                 JS::AutoIdVector& props) const MOZ_OVERRIDE;
   bool getPropertyDescriptor(JSContext* cx, JS::Handle<JSObject*> proxy,
                              JS::Handle<jsid> id,
-                             JS::MutableHandle<JSPropertyDescriptor> desc) MOZ_OVERRIDE;
+                             JS::MutableHandle<JSPropertyDescriptor> desc) const MOZ_OVERRIDE;
 
   bool watch(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
-             JS::Handle<JSObject*> callable) MOZ_OVERRIDE;
+             JS::Handle<JSObject*> callable) const MOZ_OVERRIDE;
   bool unwatch(JSContext* cx, JS::Handle<JSObject*> proxy,
-               JS::Handle<jsid> id) MOZ_OVERRIDE;
+               JS::Handle<jsid> id) const MOZ_OVERRIDE;
   virtual bool getOwnPropertyNames(JSContext* cx, JS::Handle<JSObject*> proxy,
-                                   JS::AutoIdVector &props) MOZ_OVERRIDE;
+                                   JS::AutoIdVector &props) const MOZ_OVERRIDE;
   // We override keys() and implement it directly instead of using the
   // default implementation, which would getOwnPropertyNames and then
   // filter out the non-enumerable ones.  This avoids doing
   // unnecessary work during enumeration.
   virtual bool keys(JSContext* cx, JS::Handle<JSObject*> proxy,
-                    JS::AutoIdVector &props) MOZ_OVERRIDE;
+                    JS::AutoIdVector &props) const MOZ_OVERRIDE;
 
 protected:
   // Hook for subclasses to implement shared getOwnPropertyNames()/keys()
   // functionality.  The "flags" argument is either JSITER_OWNONLY (for keys())
   // or JSITER_OWNONLY | JSITER_HIDDEN (for getOwnPropertyNames()).
   virtual bool ownPropNames(JSContext* cx, JS::Handle<JSObject*> proxy,
                             unsigned flags,
-                            JS::AutoIdVector& props) = 0;
+                            JS::AutoIdVector& props) const = 0;
 };
 
 class DOMProxyHandler : public BaseDOMProxyHandler
 {
 public:
   DOMProxyHandler()
     : BaseDOMProxyHandler(ProxyFamily())
   {
   }
 
-  bool preventExtensions(JSContext *cx, JS::Handle<JSObject*> proxy) MOZ_OVERRIDE;
+  bool preventExtensions(JSContext *cx, JS::Handle<JSObject*> proxy) const MOZ_OVERRIDE;
   bool defineProperty(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
-                      JS::MutableHandle<JSPropertyDescriptor> desc) MOZ_OVERRIDE
+                      JS::MutableHandle<JSPropertyDescriptor> desc) const MOZ_OVERRIDE
   {
     bool unused;
     return defineProperty(cx, proxy, id, desc, &unused);
   }
   virtual bool defineProperty(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
-                              JS::MutableHandle<JSPropertyDescriptor> desc, bool* defined);
+                              JS::MutableHandle<JSPropertyDescriptor> desc, bool* defined)
+                              const;
   bool set(JSContext *cx, JS::Handle<JSObject*> proxy, JS::Handle<JSObject*> receiver,
-           JS::Handle<jsid> id, bool strict, JS::MutableHandle<JS::Value> vp) MOZ_OVERRIDE;
+           JS::Handle<jsid> id, bool strict, JS::MutableHandle<JS::Value> vp)
+           const MOZ_OVERRIDE;
   bool delete_(JSContext* cx, JS::Handle<JSObject*> proxy,
-               JS::Handle<jsid> id, bool* bp) MOZ_OVERRIDE;
-  bool has(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, bool* bp) MOZ_OVERRIDE;
-  bool isExtensible(JSContext *cx, JS::Handle<JSObject*> proxy, bool *extensible) MOZ_OVERRIDE;
+               JS::Handle<jsid> id, bool* bp) const MOZ_OVERRIDE;
+  bool has(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
+           bool* bp) const MOZ_OVERRIDE;
+  bool isExtensible(JSContext *cx, JS::Handle<JSObject*> proxy, bool *extensible)
+                    const MOZ_OVERRIDE;
 
   /*
    * If assigning to proxy[id] hits a named setter with OverrideBuiltins or
    * an indexed setter, call it and set *done to true on success. Otherwise, set
    * *done to false.
    */
   virtual bool setCustom(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
-                         JS::MutableHandle<JS::Value> vp, bool *done);
+                         JS::MutableHandle<JS::Value> vp, bool *done) const;
 
   static JSObject* GetExpandoObject(JSObject* obj)
   {
     MOZ_ASSERT(IsDOMProxy(obj), "expected a DOM proxy object");
     JS::Value v = js::GetProxyExtra(obj, JSPROXYSLOT_EXPANDO);
     if (v.isObject()) {
       return &v.toObject();
     }
@@ -122,21 +126,21 @@ public:
     return v.isUndefined() ? nullptr : &v.toObject();
   }
   /* GetAndClearExpandoObject does not DROP or clear the preserving wrapper flag. */
   static JSObject* GetAndClearExpandoObject(JSObject* obj);
   static JSObject* EnsureExpandoObject(JSContext* cx,
                                        JS::Handle<JSObject*> obj);
 };
 
-inline DOMProxyHandler*
+inline const DOMProxyHandler*
 GetDOMProxyHandler(JSObject* obj)
 {
   MOZ_ASSERT(IsDOMProxy(obj));
-  return static_cast<DOMProxyHandler*>(js::GetProxyHandler(obj));
+  return static_cast<const DOMProxyHandler*>(js::GetProxyHandler(obj));
 }
 
 extern jsid s_length_id;
 
 int32_t IdToInt32(JSContext* cx, JS::Handle<jsid> id);
 
 // XXXbz this should really return uint32_t, with the maximum value
 // meaning "not an index"...
--- a/dom/bindings/ToJSValue.h
+++ b/dom/bindings/ToJSValue.h
@@ -119,16 +119,30 @@ ToJSValue(JSContext* aCx,
 {
   // Make sure we're called in a compartment
   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
 
   aValue.setNumber(aArgument);
   return true;
 }
 
+// Accept CallbackObjects
+inline bool
+ToJSValue(JSContext* aCx,
+          CallbackObject& aArgument,
+          JS::MutableHandle<JS::Value> aValue)
+{
+  // Make sure we're called in a compartment
+  MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
+
+  aValue.setObject(*aArgument.Callback());
+
+  return MaybeWrapValue(aCx, aValue);
+}
+
 // Accept objects that inherit from nsWrapperCache and nsISupports (e.g. most
 // DOM objects).
 template <class T>
 typename EnableIf<IsBaseOf<nsWrapperCache, T>::value &&
                   IsBaseOf<nsISupports, T>::value, bool>::Type
 ToJSValue(JSContext* aCx,
           T& aArgument,
           JS::MutableHandle<JS::Value> aValue)
@@ -167,16 +181,17 @@ ISupportsToJSValue(JSContext* aCx,
                    nsISupports* aArgument,
                    JS::MutableHandle<JS::Value> aValue);
 } // namespace tojsvalue_detail
 
 // Accept objects that inherit from nsISupports but not nsWrapperCache (e.g.
 // nsIDOMFile).
 template <class T>
 typename EnableIf<!IsBaseOf<nsWrapperCache, T>::value &&
+                  !IsBaseOf<CallbackObject, T>::value &&
                   IsBaseOf<nsISupports, T>::value, bool>::Type
 ToJSValue(JSContext* aCx,
           T& aArgument,
           JS::MutableHandle<JS::Value> aValue)
 {
   // Make sure we're called in a compartment
   MOZ_ASSERT(JS::CurrentGlobalOrNull(aCx));
 
@@ -223,16 +238,26 @@ ToJSValue(JSContext* aCx, JS::Handle<JS:
 
 // Accept nsresult, for use in rejections, and create an XPCOM
 // exception object representing that nsresult.
 bool
 ToJSValue(JSContext* aCx,
           nsresult aArgument,
           JS::MutableHandle<JS::Value> aValue);
 
+// Accept pointers to other things we accept
+template <typename T>
+typename EnableIf<IsPointer<T>::value, bool>::Type
+ToJSValue(JSContext* aCx,
+          T aArgument,
+          JS::MutableHandle<JS::Value> aValue)
+{
+  return ToJSValue(aCx, *aArgument, aValue);
+}
+
 // Accept arrays of other things we accept
 template <typename T>
 bool
 ToJSValue(JSContext* aCx,
           T* aArguments,
           size_t aLength,
           JS::MutableHandle<JS::Value> aValue)
 {
--- a/dom/bindings/parser/WebIDL.py
+++ b/dom/bindings/parser/WebIDL.py
@@ -986,17 +986,18 @@ class IDLInterface(IDLObjectWithScope):
                                       [attr.location, self.location])
             elif identifier == "Global":
                 if not attr.noArguments():
                     raise WebIDLError("[Global] must take no arguments",
                                       [attr.location])
                 self._isOnGlobalProtoChain = True
             elif (identifier == "NeedNewResolve" or
                   identifier == "OverrideBuiltins" or
-                  identifier == "ChromeOnly"):
+                  identifier == "ChromeOnly" or
+                  identifier == "LegacyEventInit"):
                 # Known extended attributes that do not take values
                 if not attr.noArguments():
                     raise WebIDLError("[%s] must take no arguments" % identifier,
                                       [attr.location])
             elif (identifier == "Pref" or
                   identifier == "JSImplementation" or
                   identifier == "HeaderFile" or
                   identifier == "NavigatorProperty" or
--- a/dom/browser-element/BrowserElementParent.cpp
+++ b/dom/browser-element/BrowserElementParent.cpp
@@ -11,22 +11,21 @@
 #ifdef CreateEvent
 #undef CreateEvent
 #endif
 
 #include "BrowserElementParent.h"
 #include "mozilla/EventDispatcher.h"
 #include "mozilla/dom/HTMLIFrameElement.h"
 #include "mozilla/dom/ToJSValue.h"
-#include "nsIDOMCustomEvent.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsVariant.h"
 #include "mozilla/dom/BrowserElementDictionariesBinding.h"
 #include "nsCxPusher.h"
-#include "GeneratedEventClasses.h"
+#include "mozilla/dom/CustomEvent.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 namespace {
 
 using mozilla::BrowserElementParent;
 /**
--- a/dom/cellbroadcast/src/CellBroadcast.cpp
+++ b/dom/cellbroadcast/src/CellBroadcast.cpp
@@ -3,17 +3,16 @@
  * 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 "CellBroadcast.h"
 #include "mozilla/dom/MozCellBroadcastBinding.h"
 #include "mozilla/dom/MozCellBroadcastEvent.h"
 #include "nsIDOMMozCellBroadcastMessage.h"
 #include "nsServiceManagerUtils.h"
-#include "GeneratedEvents.h"
 
 #define NS_RILCONTENTHELPER_CONTRACTID "@mozilla.org/ril/content-helper;1"
 
 using namespace mozilla::dom;
 
 /**
  * CellBroadcast::Listener Implementation.
  */
--- a/dom/devicestorage/nsDeviceStorage.cpp
+++ b/dom/devicestorage/nsDeviceStorage.cpp
@@ -6,16 +6,17 @@
 
 #include "nsDeviceStorage.h"
 
 #include "mozilla/Attributes.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/dom/DeviceStorageBinding.h"
+#include "mozilla/dom/DeviceStorageChangeEvent.h"
 #include "mozilla/dom/DeviceStorageFileSystem.h"
 #include "mozilla/dom/devicestorage/PDeviceStorageRequestChild.h"
 #include "mozilla/dom/Directory.h"
 #include "mozilla/dom/FileSystemUtils.h"
 #include "mozilla/dom/ipc/Blob.h"
 #include "mozilla/dom/PBrowserChild.h"
 #include "mozilla/dom/PContentPermissionRequestChild.h"
 #include "mozilla/dom/PermissionMessageUtils.h"
@@ -42,20 +43,18 @@
 #include "nsIPrincipal.h"
 #include "nsJSUtils.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsXULAppAPI.h"
 #include "TabChild.h"
 #include "DeviceStorageFileDescriptor.h"
 #include "DeviceStorageRequestChild.h"
-#include "nsIDOMDeviceStorageChangeEvent.h"
 #include "nsCRT.h"
 #include "nsIObserverService.h"
-#include "GeneratedEvents.h"
 #include "nsIMIMEService.h"
 #include "nsCExternalHandlerService.h"
 #include "nsIPermissionManager.h"
 #include "nsIStringBundle.h"
 #include "nsIDocument.h"
 #include "nsPrintfCString.h"
 #include <algorithm>
 #include "private/pprio.h"
@@ -4191,31 +4190,29 @@ void
 nsDOMDeviceStorage::DispatchMountChangeEvent(nsAString& aVolumeStatus)
 {
   if (aVolumeStatus == mLastStatus) {
     // We've already sent this status, don't bother sending it again.
     return;
   }
   mLastStatus = aVolumeStatus;
 
-  nsCOMPtr<nsIDOMEvent> event;
-  NS_NewDOMDeviceStorageChangeEvent(getter_AddRefs(event), this,
-                                    nullptr, nullptr);
-
-  nsCOMPtr<nsIDOMDeviceStorageChangeEvent> ce = do_QueryInterface(event);
-  nsresult rv = ce->InitDeviceStorageChangeEvent(NS_LITERAL_STRING("change"),
-                                                 true, false,
-                                                 mStorageName,
-                                                 aVolumeStatus);
-  if (NS_FAILED(rv)) {
-    return;
-  }
+  DeviceStorageChangeEventInit init;
+  init.mBubbles = true;
+  init.mCancelable = false;
+  init.mPath = mStorageName;
+  init.mReason = aVolumeStatus;
+
+  nsRefPtr<DeviceStorageChangeEvent> event =
+    DeviceStorageChangeEvent::Constructor(this, NS_LITERAL_STRING("change"),
+                                          init);
+  event->SetTrusted(true);
 
   bool ignore;
-  DispatchEvent(ce, &ignore);
+  DispatchEvent(event, &ignore);
 }
 #endif
 
 NS_IMETHODIMP
 nsDOMDeviceStorage::Observe(nsISupports *aSubject,
                             const char *aTopic,
                             const char16_t *aData)
 {
@@ -4281,34 +4278,29 @@ nsDOMDeviceStorage::Notify(const char* a
   }
 
   if (!mStorageType.Equals(aFile->mStorageType) ||
       !mStorageName.Equals(aFile->mStorageName)) {
     // Ignore this
     return NS_OK;
   }
 
-  nsCOMPtr<nsIDOMEvent> event;
-  NS_NewDOMDeviceStorageChangeEvent(getter_AddRefs(event), this,
-                                    nullptr, nullptr);
-
-  nsCOMPtr<nsIDOMDeviceStorageChangeEvent> ce = do_QueryInterface(event);
-
-  nsString reason;
-  reason.AssignWithConversion(aReason);
-
-  nsString fullPath;
-  aFile->GetFullPath(fullPath);
-  nsresult rv = ce->InitDeviceStorageChangeEvent(NS_LITERAL_STRING("change"),
-                                                 true, false, fullPath,
-                                                 reason);
-  NS_ENSURE_SUCCESS(rv, rv);
+  DeviceStorageChangeEventInit init;
+  init.mBubbles = true;
+  init.mCancelable = false;
+  aFile->GetFullPath(init.mPath);
+  init.mReason.AssignWithConversion(aReason);
+
+  nsRefPtr<DeviceStorageChangeEvent> event =
+    DeviceStorageChangeEvent::Constructor(this, NS_LITERAL_STRING("change"),
+                                          init);
+  event->SetTrusted(true);
 
   bool ignore;
-  DispatchEvent(ce, &ignore);
+  DispatchEvent(event, &ignore);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDOMDeviceStorage::AddEventListener(const nsAString & aType,
                                      nsIDOMEventListener *aListener,
                                      bool aUseCapture,
                                      bool aWantsUntrusted,
new file mode 100644
--- /dev/null
+++ b/dom/events/CustomEvent.cpp
@@ -0,0 +1,117 @@
+/* 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 "CustomEvent.h"
+#include "mozilla/dom/CustomEventBinding.h"
+
+#include "mozilla/dom/BindingUtils.h"
+#include "nsContentUtils.h"
+#include "nsIXPConnect.h"
+
+using namespace mozilla;
+using namespace mozilla::dom;
+
+CustomEvent::CustomEvent(mozilla::dom::EventTarget* aOwner,
+                         nsPresContext* aPresContext,
+                         mozilla::WidgetEvent* aEvent)
+: Event(aOwner, aPresContext, aEvent)
+{
+}
+
+CustomEvent::~CustomEvent() {}
+
+NS_IMPL_CYCLE_COLLECTION_CLASS(CustomEvent)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(CustomEvent, Event)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK(mDetail)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(CustomEvent, Event)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDetail)
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_IMPL_ADDREF_INHERITED(CustomEvent, Event)
+NS_IMPL_RELEASE_INHERITED(CustomEvent, Event)
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(CustomEvent)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMCustomEvent)
+NS_INTERFACE_MAP_END_INHERITING(Event)
+
+already_AddRefed<CustomEvent>
+CustomEvent::Constructor(const GlobalObject& aGlobal,
+                         const nsAString& aType,
+                         const CustomEventInit& aParam,
+                         ErrorResult& aRv)
+{
+  nsCOMPtr<mozilla::dom::EventTarget> t = do_QueryInterface(aGlobal.GetAsSupports());
+  nsRefPtr<CustomEvent> e = new CustomEvent(t, nullptr, nullptr);
+  bool trusted = e->Init(t);
+  JS::Rooted<JS::Value> detail(aGlobal.Context(), aParam.mDetail);
+  e->InitCustomEvent(aGlobal.Context(), aType, aParam.mBubbles, aParam.mCancelable, detail, aRv);
+  e->SetTrusted(trusted);
+  return e.forget();
+}
+
+JSObject*
+CustomEvent::WrapObject(JSContext* aCx)
+{
+  return mozilla::dom::CustomEventBinding::Wrap(aCx, this);
+}
+
+NS_IMETHODIMP
+CustomEvent::InitCustomEvent(const nsAString& aType,
+                             bool aCanBubble,
+                             bool aCancelable,
+                             nsIVariant* aDetail)
+{
+  nsresult rv = Event::InitEvent(aType, aCanBubble, aCancelable);
+  NS_ENSURE_SUCCESS(rv, rv);
+  mDetail = aDetail;
+  return NS_OK;
+}
+
+void
+CustomEvent::InitCustomEvent(JSContext* aCx,
+                             const nsAString& aType,
+                             bool aCanBubble,
+                             bool aCancelable,
+                             JS::Handle<JS::Value> aDetail,
+                             ErrorResult& aRv)
+{
+  nsCOMPtr<nsIVariant> detail;
+  if (nsIXPConnect* xpc = nsContentUtils::XPConnect()) {
+    xpc->JSToVariant(aCx, aDetail, getter_AddRefs(detail));
+  }
+
+  if (!detail) {
+    aRv.Throw(NS_ERROR_FAILURE);
+    return;
+  }
+  aRv = InitCustomEvent(aType, aCanBubble, aCancelable, detail);
+}
+
+NS_IMETHODIMP
+CustomEvent::GetDetail(nsIVariant** aDetail)
+{
+  NS_IF_ADDREF(*aDetail = mDetail);
+  return NS_OK;
+}
+
+void
+CustomEvent::GetDetail(JSContext* aCx,
+                       JS::MutableHandle<JS::Value> aRetval)
+{
+  VariantToJsval(aCx, mDetail, aRetval);
+}
+
+nsresult
+NS_NewDOMCustomEvent(nsIDOMEvent** aInstancePtrResult,
+                     mozilla::dom::EventTarget* aOwner,
+                     nsPresContext* aPresContext,
+                     mozilla::WidgetEvent* aEvent)
+{
+  CustomEvent* it = new CustomEvent(aOwner, aPresContext, aEvent);
+  NS_ADDREF(it);
+  *aInstancePtrResult = static_cast<Event*>(it);
+  return NS_OK;
+}
new file mode 100644
--- /dev/null
+++ b/dom/events/CustomEvent.h
@@ -0,0 +1,59 @@
+/* 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 CustomEvent_h__
+#define CustomEvent_h__
+
+#include "mozilla/dom/Event.h"
+#include "nsIDOMCustomEvent.h"
+
+namespace mozilla {
+namespace dom {
+
+struct CustomEventInit;
+
+class CustomEvent MOZ_FINAL : public Event,
+                              public nsIDOMCustomEvent
+{
+private:
+  virtual ~CustomEvent();
+
+  nsCOMPtr<nsIVariant> mDetail;
+
+public:
+  CustomEvent(mozilla::dom::EventTarget* aOwner,
+              nsPresContext* aPresContext = nullptr,
+              mozilla::WidgetEvent* aEvent = nullptr);
+
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(CustomEvent, Event)
+  NS_FORWARD_TO_EVENT
+  NS_DECL_NSIDOMCUSTOMEVENT
+
+  static already_AddRefed<CustomEvent>
+  Constructor(const GlobalObject& aGlobal,
+              const nsAString& aType,
+              const CustomEventInit& aParam,
+              ErrorResult& aRv);
+
+  virtual JSObject*
+  WrapObject(JSContext* aCx) MOZ_OVERRIDE;
+
+  void
+  GetDetail(JSContext* aCx,
+            JS::MutableHandle<JS::Value> aRetval);
+
+  void
+  InitCustomEvent(JSContext* aCx,
+                  const nsAString& aType,
+                  bool aCanBubble,
+                  bool aCancelable,
+                  JS::Handle<JS::Value> aDetail,
+                  ErrorResult& aRv);
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // CustomEvent_h__
--- a/dom/events/EventDispatcher.cpp
+++ b/dom/events/EventDispatcher.cpp
@@ -8,19 +8,23 @@
 #include "nsContentUtils.h"
 #include "nsError.h"
 #include <new>
 #include "nsIContent.h"
 #include "nsIDocument.h"
 #include "nsINode.h"
 #include "nsPIDOMWindow.h"
 #include "GeckoProfiler.h"
-#include "GeneratedEvents.h"
 #include "mozilla/ContentEvents.h"
+#include "mozilla/dom/CloseEvent.h"
+#include "mozilla/dom/DeviceOrientationEvent.h"
 #include "mozilla/dom/EventTarget.h"
+#include "mozilla/dom/HashChangeEvent.h"
+#include "mozilla/dom/PageTransitionEvent.h"
+#include "mozilla/dom/PopStateEvent.h"
 #include "mozilla/dom/StorageEvent.h"
 #include "mozilla/dom/TouchEvent.h"
 #include "mozilla/EventDispatcher.h"
 #include "mozilla/EventListenerManager.h"
 #include "mozilla/InternalMutationEvent.h"
 #include "mozilla/MiscEvents.h"
 #include "mozilla/MouseEvents.h"
 #include "mozilla/TextEvents.h"
@@ -769,20 +773,23 @@ EventDispatcher::CreateEvent(EventTarget
   if (aEventType.LowerCaseEqualsLiteral("compositionevent"))
     return NS_NewDOMCompositionEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("mutationevent") ||
         aEventType.LowerCaseEqualsLiteral("mutationevents"))
     return NS_NewDOMMutationEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("textevent") ||
       aEventType.LowerCaseEqualsLiteral("textevents"))
     return NS_NewDOMUIEvent(aDOMEvent, aOwner, aPresContext, nullptr);
-  if (aEventType.LowerCaseEqualsLiteral("popupblockedevents"))
-    return NS_NewDOMPopupBlockedEvent(aDOMEvent, aOwner, aPresContext, nullptr);
-  if (aEventType.LowerCaseEqualsLiteral("deviceorientationevent"))
-    return NS_NewDOMDeviceOrientationEvent(aDOMEvent, aOwner, aPresContext, nullptr);
+  if (aEventType.LowerCaseEqualsLiteral("deviceorientationevent")) {
+    DeviceOrientationEventInit init;
+    nsRefPtr<DeviceOrientationEvent> event =
+      DeviceOrientationEvent::Constructor(aOwner, EmptyString(), init);
+    event.forget(aDOMEvent);
+    return NS_OK;
+  }
   if (aEventType.LowerCaseEqualsLiteral("devicemotionevent"))
     return NS_NewDOMDeviceMotionEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("uievent") ||
       aEventType.LowerCaseEqualsLiteral("uievents"))
     return NS_NewDOMUIEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("event") ||
       aEventType.LowerCaseEqualsLiteral("events") ||
       aEventType.LowerCaseEqualsLiteral("htmlevents") ||
@@ -796,44 +803,65 @@ EventDispatcher::CreateEvent(EventTarget
       aEventType.LowerCaseEqualsLiteral("timeevents"))
     return NS_NewDOMTimeEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("xulcommandevent") ||
       aEventType.LowerCaseEqualsLiteral("xulcommandevents"))
     return NS_NewDOMXULCommandEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("commandevent") ||
       aEventType.LowerCaseEqualsLiteral("commandevents"))
     return NS_NewDOMCommandEvent(aDOMEvent, aOwner, aPresContext, nullptr);
-  if (aEventType.LowerCaseEqualsLiteral("elementreplace"))
-    return NS_NewDOMElementReplaceEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("datacontainerevent") ||
       aEventType.LowerCaseEqualsLiteral("datacontainerevents"))
     return NS_NewDOMDataContainerEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("messageevent"))
     return NS_NewDOMMessageEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("notifypaintevent"))
     return NS_NewDOMNotifyPaintEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("simplegestureevent"))
     return NS_NewDOMSimpleGestureEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("beforeunloadevent"))
     return NS_NewDOMBeforeUnloadEvent(aDOMEvent, aOwner, aPresContext, nullptr);
-  if (aEventType.LowerCaseEqualsLiteral("pagetransition"))
-    return NS_NewDOMPageTransitionEvent(aDOMEvent, aOwner, aPresContext, nullptr);
-  if (aEventType.LowerCaseEqualsLiteral("domtransaction"))
-    return NS_NewDOMDOMTransactionEvent(aDOMEvent, aOwner, aPresContext, nullptr);
+  // XXXkhuey this is broken
+  if (aEventType.LowerCaseEqualsLiteral("pagetransition")) {
+    PageTransitionEventInit init;
+    nsRefPtr<PageTransitionEvent> event =
+      PageTransitionEvent::Constructor(aOwner, EmptyString(), init);
+    event.forget(aDOMEvent);
+    return NS_OK;
+  }
   if (aEventType.LowerCaseEqualsLiteral("scrollareaevent"))
     return NS_NewDOMScrollAreaEvent(aDOMEvent, aOwner, aPresContext, nullptr);
-  if (aEventType.LowerCaseEqualsLiteral("popstateevent"))
-    return NS_NewDOMPopStateEvent(aDOMEvent, aOwner, aPresContext, nullptr);
-  if (aEventType.LowerCaseEqualsLiteral("closeevent"))
-    return NS_NewDOMCloseEvent(aDOMEvent, aOwner, aPresContext, nullptr);
+  if (aEventType.LowerCaseEqualsLiteral("closeevent")) {
+    CloseEventInit init;
+    nsRefPtr<CloseEvent> event =
+      CloseEvent::Constructor(aOwner, EmptyString(), init);
+    event.forget(aDOMEvent);
+    return NS_OK;
+  }
+  // XXXkhuey Chrome supports popstateevent here, even though it provides no
+  // initPopStateEvent method.  This is nuts ... but copying it is unlikely to
+  // break the web.
+  if (aEventType.LowerCaseEqualsLiteral("popstateevent")) {
+    AutoJSContext cx;
+    RootedDictionary<PopStateEventInit> init(cx);
+    nsRefPtr<PopStateEvent> event =
+      PopStateEvent::Constructor(aOwner, EmptyString(), init);
+    event.forget(aDOMEvent);
+    return NS_OK;
+  }
   if (aEventType.LowerCaseEqualsLiteral("touchevent") &&
       TouchEvent::PrefEnabled())
     return NS_NewDOMTouchEvent(aDOMEvent, aOwner, aPresContext, nullptr);
-  if (aEventType.LowerCaseEqualsLiteral("hashchangeevent"))
-    return NS_NewDOMHashChangeEvent(aDOMEvent, aOwner, aPresContext, nullptr);
+  if (aEventType.LowerCaseEqualsLiteral("hashchangeevent")) {
+    HashChangeEventInit init;
+    nsRefPtr<HashChangeEvent> event =
+      HashChangeEvent::Constructor(aOwner, EmptyString(), init);
+    event.forget(aDOMEvent);
+    return NS_OK;
+  }
   if (aEventType.LowerCaseEqualsLiteral("customevent"))
     return NS_NewDOMCustomEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("storageevent")) {
     return NS_NewDOMStorageEvent(aDOMEvent, aOwner);
   }
 
 
   // NEW EVENT TYPES SHOULD NOT BE ADDED HERE; THEY SHOULD USE ONLY EVENT
--- a/dom/events/moz.build
+++ b/dom/events/moz.build
@@ -31,16 +31,17 @@ EXPORTS.mozilla += [
 ]
 
 EXPORTS.mozilla.dom += [
     'AnimationEvent.h',
     'BeforeUnloadEvent.h',
     'ClipboardEvent.h',
     'CommandEvent.h',
     'CompositionEvent.h',
+    'CustomEvent.h',
     'DataContainerEvent.h',
     'DataTransfer.h',
     'DeviceMotionEvent.h',
     'DragEvent.h',
     'Event.h',
     'EventTarget.h',
     'FocusEvent.h',
     'InputEvent.h',
@@ -107,16 +108,17 @@ UNIFIED_SOURCES += [
     'UIEvent.cpp',
     'WheelEvent.cpp',
     'WheelHandlingHelper.cpp',
     'XULCommandEvent.cpp',
 ]
 
 # nsEventStateManager.cpp should be built separately because of Mac OS X headers.
 SOURCES += [
+    'CustomEvent.cpp',
     'EventStateManager.cpp',
 ]
 
 if CONFIG['MOZ_WEBSPEECH']:
     UNIFIED_SOURCES += ['SpeechRecognitionError.cpp']
 
 FAIL_ON_WARNINGS = True
 
--- a/dom/events/test/test_all_synthetic_events.html
+++ b/dom/events/test/test_all_synthetic_events.html
@@ -158,20 +158,16 @@ const kEventConstructors = {
                                                                          aProps.button, aProps.relatedTarget, aProps.dataTransfer);
                                                          return e;
                                                        },
                                              },
   ErrorEvent:                                { create: function (aName, aProps) {
                                                          return new ErrorEvent(aName, aProps);
                                                        },
   },
-  ElementReplaceEvent:                       { create: function (aName, aProps) {
-                                                         return new ElementReplaceEvent(aName, aProps);
-                                                       },
-                                             },
   FocusEvent:                                { create: function (aName, aProps) {
                                                          return new FocusEvent(aName, aProps);
                                                        },
                                              },
   GamepadEvent:                              { create: function (aName, aProps) {
                                                          return new GamepadEvent(aName, aProps);
                                                        },
                                              },
--- a/dom/events/test/test_eventctors.html
+++ b/dom/events/test/test_eventctors.html
@@ -633,19 +633,19 @@ e = new DeviceLightEvent("hello", {value
 is(e.value, -Infinity, "value should be negative infinity");
 e = new DeviceLightEvent("hello");
 is(e.value, Infinity, "Uninitialized value should be positive infinity");
 
 // DeviceOrientationEvent
 e = new DeviceOrientationEvent("hello");
 is(e.type, "hello", "Wrong event type!");
 ok(!e.isTrusted, "Event should not be trusted");
-is(e.alpha, 0);
-is(e.beta, 0);
-is(e.gamma, 0);
+is(e.alpha, null);
+is(e.beta, null);
+is(e.gamma, null);
 is(e.absolute, false);
 
 e = new DeviceOrientationEvent("hello", { alpha: 1, beta: 2, gamma: 3, absolute: true } );
 is(e.type, "hello", "Wrong event type!");
 ok(!e.isTrusted, "Event should not be trusted");
 is(e.alpha, 1);
 is(e.beta, 2);
 is(e.gamma, 3);
--- a/dom/gamepad/GamepadService.cpp
+++ b/dom/gamepad/GamepadService.cpp
@@ -7,17 +7,16 @@
 #include "mozilla/Preferences.h"
 #include "mozilla/StaticPtr.h"
 
 #include "GamepadService.h"
 #include "Gamepad.h"
 #include "nsAutoPtr.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMDocument.h"
-#include "GeneratedEvents.h"
 #include "nsIDOMWindow.h"
 #include "nsIObserver.h"
 #include "nsIObserverService.h"
 #include "nsIServiceManager.h"
 #include "nsITimer.h"
 #include "nsThreadUtils.h"
 #include "mozilla/Services.h"
 
--- a/dom/icc/src/IccManager.cpp
+++ b/dom/icc/src/IccManager.cpp
@@ -1,15 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "IccManager.h"
 #include "mozilla/dom/MozIccManagerBinding.h"
-#include "GeneratedEvents.h"
 #include "Icc.h"
 #include "IccListener.h"
 #include "mozilla/dom/IccChangeEvent.h"
 #include "mozilla/Preferences.h"
 #include "nsIDOMIccInfo.h"
 
 using namespace mozilla::dom;
 
--- a/dom/interfaces/apps/moz.build
+++ b/dom/interfaces/apps/moz.build
@@ -5,15 +5,14 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 XPIDL_SOURCES += [
     'mozIApplication.idl',
     'mozIApplicationClearPrivateDataParams.idl',
     'nsIAppsService.idl',
     'nsIDOMApplicationRegistry.idl',
     'nsIDOMApplicationRegistry2.idl',
-    'nsIDOMMozApplicationEvent.idl',
     'nsIInterAppCommService.idl',
     'nsIInterAppCommUIGlue.idl'
 ]
 
 XPIDL_MODULE = 'dom_apps'
 
deleted file mode 100644
--- a/dom/interfaces/apps/nsIDOMMozApplicationEvent.idl
+++ /dev/null
@@ -1,18 +0,0 @@
-/* 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 "nsIDOMEvent.idl"
-
-interface mozIDOMApplication;
-
-[builtinclass, uuid(453ae38a-8d8d-465f-a718-3f01240f8f75)]
-interface nsIDOMMozApplicationEvent : nsIDOMEvent
-{
-  readonly attribute mozIDOMApplication application;
-
-  [noscript] void initMozApplicationEvent(in DOMString aType,
-                                          in boolean aCanBubble,
-                                          in boolean aCancelable,
-                                          in mozIDOMApplication aApplication);
-};
--- a/dom/interfaces/devicestorage/moz.build
+++ b/dom/interfaces/devicestorage/moz.build
@@ -1,12 +1,11 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # 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/.
 
 XPIDL_SOURCES += [
     'nsIDOMDeviceStorage.idl',
-    'nsIDOMDeviceStorageChangeEvent.idl',
 ]
 
 XPIDL_MODULE = 'dom_devicestorage'
deleted file mode 100644
--- a/dom/interfaces/devicestorage/nsIDOMDeviceStorageChangeEvent.idl
+++ /dev/null
@@ -1,20 +0,0 @@
-/* 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 "domstubs.idl"
-#include "nsIDOMEvent.idl"
-
-[uuid(30eaf0b9-8f3f-49fe-818e-7b7d9fbf8f95), builtinclass]
-interface nsIDOMDeviceStorageChangeEvent : nsIDOMEvent
-{
-
-  [noscript] void initDeviceStorageChangeEvent(in DOMString eventTypeArg,
-                                               in boolean canBubbleArg,
-                                               in boolean cancelableArg,
-                                               in DOMString path,
-                                               in DOMString reason);
-  
-  readonly attribute DOMString path;
-  readonly attribute DOMString reason;
-};
--- a/dom/interfaces/events/moz.build
+++ b/dom/interfaces/events/moz.build
@@ -3,49 +3,36 @@
 # 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/.
 
 XPIDL_SOURCES += [
     'nsIDOMAnimationEvent.idl',
     'nsIDOMBeforeUnloadEvent.idl',
     'nsIDOMClipboardEvent.idl',
-    'nsIDOMCloseEvent.idl',
     'nsIDOMCommandEvent.idl',
     'nsIDOMCompositionEvent.idl',
     'nsIDOMCustomEvent.idl',
     'nsIDOMDataContainerEvent.idl',
     'nsIDOMDataTransfer.idl',
-    'nsIDOMDeviceOrientationEvent.idl',
-    'nsIDOMDOMTransactionEvent.idl',
     'nsIDOMDragEvent.idl',
-    'nsIDOMElementReplaceEvent.idl',
     'nsIDOMEvent.idl',
     'nsIDOMEventListener.idl',
     'nsIDOMEventTarget.idl',
     'nsIDOMFocusEvent.idl',
-    'nsIDOMHashChangeEvent.idl',
     'nsIDOMKeyEvent.idl',
     'nsIDOMMessageEvent.idl',
     'nsIDOMMouseEvent.idl',
     'nsIDOMMouseScrollEvent.idl',
     'nsIDOMMutationEvent.idl',
     'nsIDOMNotifyPaintEvent.idl',
     'nsIDOMNSEvent.idl',
-    'nsIDOMPageTransitionEvent.idl',
     'nsIDOMPaintRequest.idl',
-    'nsIDOMPopStateEvent.idl',
-    'nsIDOMPopupBlockedEvent.idl',
-    'nsIDOMRecordErrorEvent.idl',
     'nsIDOMScrollAreaEvent.idl',
     'nsIDOMSimpleGestureEvent.idl',
-    'nsIDOMSmartCardEvent.idl',
-    'nsIDOMStyleRuleChangeEvent.idl',
-    'nsIDOMStyleSheetApplicableStateChangeEvent.idl',
-    'nsIDOMStyleSheetChangeEvent.idl',
     'nsIDOMTouchEvent.idl',
     'nsIDOMTransitionEvent.idl',
     'nsIDOMUIEvent.idl',
     'nsIDOMWheelEvent.idl',
 ]
 
 XPIDL_MODULE = 'dom_events'
 
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMCloseEvent.idl
+++ /dev/null
@@ -1,28 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-/**
- * The CloseEvent interface is the interface to the event
- * close on a WebSocket object.
- *
- * For more information on this interface, please see
- * http://dev.w3.org/html5/websockets/#closeevent
- */
-[builtinclass, uuid(0b85dc61-2436-4786-b153-097f5c3a33b6)]
-interface nsIDOMCloseEvent : nsIDOMEvent
-{
-  readonly attribute boolean wasClean;
-  readonly attribute unsigned short code;
-  readonly attribute DOMString reason;
-
-  void initCloseEvent(in DOMString aType,
-                      in boolean aCanBubble,
-                      in boolean aCancelable,
-                      in boolean aWasClean,
-                      in unsigned short aReasonCode,
-                      in DOMString aReason);
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMDOMTransactionEvent.idl
+++ /dev/null
@@ -1,19 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-interface nsIVariant;
-
-[builtinclass, uuid(f57f7c46-d420-4f32-a61b-0eb585d30ee1)]
-interface nsIDOMDOMTransactionEvent : nsIDOMEvent
-{
-  readonly attribute nsIVariant transactions;
-
-  void initDOMTransactionEvent(in DOMString typeArg,
-                               in boolean canBubbleArg,
-                               in boolean canCancelArg,
-                               in nsIVariant transactions);
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMDeviceOrientationEvent.idl
+++ /dev/null
@@ -1,42 +0,0 @@
-/* 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 "nsIDOMEvent.idl"
-
-[builtinclass, uuid(f5921a77-3ac5-4374-bc0c-1ed52fe83123)]
-interface nsIDOMDeviceOrientationEvent : nsIDOMEvent
-{
-  void initDeviceOrientationEvent(in DOMString eventTypeArg,
-                                  in boolean canBubbleArg,
-                                  in boolean cancelableArg,
-                                  in double alpha,
-                                  in double beta,
-                                  in double gamma,
-                                  in boolean absolute);
-
-  /*
-   * W3C specification values: http://dev.w3.org/geo/api/spec-source-orientation.html
-   *
-   * Alpha, beta and gamma are Tait-Bryan angles (Z-X'-Y''), that is they correspond to
-   * yaw, pitch and roll in flight coordinates. More specifically, assume the device
-   * is resting face up on a flat surface (its screen is pointing straight up). Then
-   * the X axis points to the right when looking at the screen, the Y axis points up
-   * when looking at the screen, and the Z axis points toward you when looking at
-   * the screen. Alpha/beta/gamma then define the device's orientation by applying
-   * the following rotations to the device in order:
-   *
-   * 1) Rotate it by alpha degrees around its Z axis (like a compass, or like changing
-   *    the yaw of an aircraft, assuming the Y axis is the nose of the craft); alpha
-   *    is in [0,360).
-   * 2) Rotate it by beta degrees around its X axis (tilting the top of the device
-   *    towards or away from you, like pitching an aircraft); beta is in [-180,180).
-   * 3) Rotate it by gamma degrees around its Y axis (tilting it sideways, like
-   *    rolling an aircraft); gamma is in [-90,90).
-   */
-
-  readonly attribute double alpha;
-  readonly attribute double beta;
-  readonly attribute double gamma;
-  readonly attribute boolean absolute;
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMElementReplaceEvent.idl
+++ /dev/null
@@ -1,19 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-interface nsIDOMElement;
-
-[builtinclass, uuid(19a31767-54bf-4044-8769-cd172e37eca2)]
-interface nsIDOMElementReplaceEvent : nsIDOMEvent
-{
-  readonly attribute nsIDOMElement upgrade;
-
-  void initElementReplaceEvent(in DOMString typeArg,
-                               in boolean canBubbleArg,
-                               in boolean canCancelArg,
-                               in nsIDOMElement upgrade);
-};
--- a/dom/interfaces/events/nsIDOMEvent.idl
+++ b/dom/interfaces/events/nsIDOMEvent.idl
@@ -361,18 +361,13 @@ NS_NewDOMPointerEvent(nsIDOMEvent** aIns
                       nsPresContext* aPresContext,
                       mozilla::WidgetPointerEvent* aEvent);
 nsresult
 NS_NewDOMTouchEvent(nsIDOMEvent** aInstancePtrResult,
                     mozilla::dom::EventTarget* aOwner,
                     nsPresContext* aPresContext,
                     mozilla::WidgetTouchEvent* aEvent);
 nsresult
-NS_NewDOMMozSettingsEvent(nsIDOMEvent** aInstancePtrResult,
-                          mozilla::dom::EventTarget* aOwner,
-                          nsPresContext* aPresContext,
-                          mozilla::WidgetEvent* aEvent);
-nsresult
-NS_NewDOMMozApplicationEvent(nsIDOMEvent** aInstancePtrResult,
-                             mozilla::dom::EventTarget* aOwner,
-                             nsPresContext* aPresContext,
-                             mozilla::WidgetEvent* aEvent);
+NS_NewDOMCustomEvent(nsIDOMEvent** aInstancePtrResult,
+                     mozilla::dom::EventTarget* aOwner,
+                     nsPresContext* aPresContext,
+                     mozilla::WidgetEvent* aEvent);
 %}
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMHashChangeEvent.idl
+++ /dev/null
@@ -1,19 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-[builtinclass, uuid(d83f3cb2-1fa4-4ee0-8eb1-8181f6d3e214)]
-interface nsIDOMHashChangeEvent : nsIDOMEvent
-{
-  readonly attribute DOMString oldURL;
-  readonly attribute DOMString newURL;
-
-  void initHashChangeEvent(in DOMString typeArg,
-                           in boolean canBubbleArg,
-                           in boolean cancelableArg,
-                           in DOMString oldURLArg,
-                           in DOMString newURLArg);
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMPageTransitionEvent.idl
+++ /dev/null
@@ -1,29 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-/**
- * The nsIDOMPageTransitionEvent interface is used for the pageshow and
- * pagehide events, which are generic events that apply to both page
- * load/unload and saving/restoring a document from session history.
- */
-
-[builtinclass, uuid(8a69a3d6-c7da-4caa-993c-7f9583d9f896)]
-interface nsIDOMPageTransitionEvent : nsIDOMEvent
-{
-  /**
-   * Set to true if the document has been or will be persisted across
-   * firing of the event.  For example, if a document is being cached in
-   * session history, |persisted| is true for the PageHide event.
-   */
-  readonly attribute boolean persisted;
-
-  /* Initialize a new pageshow or pagehide event. */
-  void initPageTransitionEvent(in DOMString typeArg,
-                               in boolean canBubbleArg,
-                               in boolean canCancelArg,
-                               in boolean persisted);
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMPopStateEvent.idl
+++ /dev/null
@@ -1,22 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-interface nsIVariant;
-
-[builtinclass, uuid(f0def4a3-0eb3-4c08-b476-582e37b8564b)]
-interface nsIDOMPopStateEvent : nsIDOMEvent
-{
-  /**
-   * The state associated with this popstate event
-   */
-  readonly attribute nsIVariant state;
-
-  void initPopStateEvent(in DOMString typeArg,
-                         in boolean canBubbleArg,
-                         in boolean cancelableArg,
-                         in nsIVariant stateArg);
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMPopupBlockedEvent.idl
+++ /dev/null
@@ -1,49 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-interface nsIURI;
-
-/**
- * The nsIDOMPopupBlockedEvent interface is the datatype for events
- * posted when a popup window is blocked.
- */
-
-[builtinclass, uuid(f6e77f79-d178-419d-8177-dfae4392d318)]
-interface nsIDOMPopupBlockedEvent : nsIDOMEvent
-{
-  /**
-   * The window object that attempted to open the blocked popup
-   * (i.e. the window object on which open() was called).
-   */
-  readonly attribute nsIDOMWindow requestingWindow;
-
-
-  /**
-   * The URI of the window that was blocked.
-   */
-  readonly attribute nsIURI popupWindowURI;
-
-  /**
-   * The window name passed to the window.open() call
-   * (as the second argument)
-   */
-  readonly attribute DOMString popupWindowName;
-
-  /**
-   * The string of features passed to the window.open() call
-   * (as the third argument)
-   */
-  readonly attribute DOMString popupWindowFeatures;
-
-  void initPopupBlockedEvent(in DOMString typeArg,
-                             in boolean canBubbleArg,
-                             in boolean cancelableArg,
-                             in nsIDOMWindow requestingWindow,
-                             in nsIURI popupWindowURI,
-                             in DOMString popupWindowName,
-                             in DOMString popupWindowFeatures);
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMRecordErrorEvent.idl
+++ /dev/null
@@ -1,27 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-/**
- * The nsIDOMRecordErrorEvent interface is used for media recorder sent events
- * and for indeciate what's wrong in the object
- * The name value is defined in the
- * http://www.w3.org/TR/2012/WD-dom-20121206/#error-names-table
- */
-[builtinclass, uuid(606e6f94-bf02-11e2-8a01-e722108c6d66)]
-interface nsIDOMRecordErrorEvent : nsIDOMEvent
-{
-  /**
-   * The error name in this event.
-   */
-  readonly attribute DOMString name;
-
-  [noscript]
-  void initRecordErrorEvent(in DOMString aType,
-                            in boolean aCanBubble,
-                            in boolean aCancelable,
-                            in DOMString aName);
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMSmartCardEvent.idl
+++ /dev/null
@@ -1,21 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-%{C++
-#define SMARTCARDEVENT_INSERT "smartcard-insert"
-#define SMARTCARDEVENT_REMOVE "smartcard-remove"
-%}
-
-[builtinclass, uuid(cd251f11-7020-4f85-a7bd-94c98d884fa7)]
-interface nsIDOMSmartCardEvent : nsIDOMEvent
-{
-  readonly attribute DOMString   tokenName;
-  [noscript] void initSmartCardEvent(in DOMString aTypeArg,
-                                     in boolean aCanBubbleArg,
-                                     in boolean aCancelableArg,
-                                     in DOMString aTokenNAme);
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMStyleRuleChangeEvent.idl
+++ /dev/null
@@ -1,21 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-interface nsIDOMCSSRule;
-interface nsIDOMCSSStyleSheet;
-
-[builtinclass, uuid(36098d39-b471-47e9-976e-33fee3d81467)]
-interface nsIDOMStyleRuleChangeEvent : nsIDOMEvent
-{
-  readonly attribute nsIDOMCSSStyleSheet stylesheet;
-  readonly attribute nsIDOMCSSRule rule;
-  [noscript] void initStyleRuleChangeEvent(in DOMString aTypeArg,
-                                           in boolean aCanBubbleArg,
-                                           in boolean aCancelableArg,
-                                           in nsIDOMCSSStyleSheet aStyleSheet,
-                                           in nsIDOMCSSRule aRule);
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMStyleSheetApplicableStateChangeEvent.idl
+++ /dev/null
@@ -1,20 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-interface nsIDOMCSSStyleSheet;
-
-[builtinclass, uuid(75f27960-fd1a-4e05-8b8b-55d97ea22a9a)]
-interface nsIDOMStyleSheetApplicableStateChangeEvent : nsIDOMEvent
-{
-  readonly attribute nsIDOMCSSStyleSheet stylesheet;
-  readonly attribute boolean applicable;
-  [noscript] void initStyleSheetApplicableStateChangeEvent(in DOMString aTypeArg,
-                                                           in boolean aCanBubbleArg,
-                                                           in boolean aCancelableArg,
-                                                           in nsIDOMCSSStyleSheet aStyleSheet,
-                                                           in boolean aApplicable);
-};
deleted file mode 100644
--- a/dom/interfaces/events/nsIDOMStyleSheetChangeEvent.idl
+++ /dev/null
@@ -1,20 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIDOMEvent.idl"
-
-interface nsIDOMCSSStyleSheet;
-
-[builtinclass, uuid(f94c6a47-58f0-4996-b1db-3ea1d14c4ddd)]
-interface nsIDOMStyleSheetChangeEvent : nsIDOMEvent
-{
-  readonly attribute nsIDOMCSSStyleSheet stylesheet;
-  readonly attribute boolean documentSheet;
-  [noscript] void initStyleSheetChangeEvent(in DOMString aTypeArg,
-                                            in boolean aCanBubbleArg,
-                                            in boolean aCancelableArg,
-                                            in nsIDOMCSSStyleSheet aStyleSheet,
-                                            in boolean aDocumentSheet);
-};
--- a/dom/interfaces/settings/moz.build
+++ b/dom/interfaces/settings/moz.build
@@ -1,13 +1,12 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # 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/.
 
 XPIDL_SOURCES += [
-    'nsIDOMMozSettingsEvent.idl',
     'nsISettingsService.idl',
 ]
 
 XPIDL_MODULE = 'dom_settings'
 
deleted file mode 100644
--- a/dom/interfaces/settings/nsIDOMMozSettingsEvent.idl
+++ /dev/null
@@ -1,19 +0,0 @@
-/* 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 "nsIDOMEvent.idl"
-interface nsIVariant;
-
-[builtinclass, uuid(d5081bf4-6a63-4ee6-8ce6-f488082dc08f)]
-interface nsIDOMMozSettingsEvent : nsIDOMEvent
-{
-  readonly attribute DOMString  settingName;
-  readonly attribute nsIVariant settingValue;
-
-  [noscript] void initMozSettingsEvent(in DOMString aType,
-                                       in boolean aCanBubble,
-                                       in boolean aCancelable,
-                                       in DOMString aSettingName,
-                                       in nsIVariant aSettingValue);
-};
--- a/dom/media/MediaManager.cpp
+++ b/dom/media/MediaManager.cpp
@@ -1373,22 +1373,23 @@ MediaManager::GetUserMedia(bool aPrivile
     if (aWindow->GetPopupControlState() > openControlled) {
       nsCOMPtr<nsIPopupWindowManager> pm =
         do_GetService(NS_POPUPWINDOWMANAGER_CONTRACTID);
       if (!pm) {
         return NS_OK;
       }
       uint32_t permission;
       nsCOMPtr<nsIDocument> doc = aWindow->GetExtantDoc();
-      pm->TestPermission(doc->NodePrincipal(), &permission);
-      if (permission == nsIPopupWindowManager::DENY_POPUP) {
-        nsGlobalWindow::FirePopupBlockedEvent(
-          doc, aWindow, nullptr, EmptyString(), EmptyString()
-        );
-        return NS_OK;
+      if (doc) {
+        pm->TestPermission(doc->NodePrincipal(), &permission);
+        if (permission == nsIPopupWindowManager::DENY_POPUP) {
+          aWindow->FirePopupBlockedEvent(doc, nullptr, EmptyString(),
+                                         EmptyString());
+          return NS_OK;
+        }
       }
     }
   }
 #endif
 
   static bool created = false;
   if (!created) {
     // Force MediaManager to startup before we try to access it from other threads
--- a/dom/mobileconnection/src/MobileConnection.cpp
+++ b/dom/mobileconnection/src/MobileConnection.cpp
@@ -1,15 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "MobileConnection.h"
 
-#include "GeneratedEvents.h"
 #include "mozilla/dom/CFStateChangeEvent.h"
 #include "mozilla/dom/DataErrorEvent.h"
 #include "mozilla/dom/MozClirModeEvent.h"
 #include "mozilla/dom/MozEmergencyCbModeEvent.h"
 #include "mozilla/dom/MozOtaStatusEvent.h"
 #include "mozilla/dom/ToJSValue.h"
 #include "mozilla/dom/USSDReceivedEvent.h"
 #include "mozilla/Preferences.h"
--- a/dom/src/storage/DOMStorage.cpp
+++ b/dom/src/storage/DOMStorage.cpp
@@ -12,17 +12,16 @@
 #include "nsIScriptSecurityManager.h"
 #include "nsIPermissionManager.h"
 #include "nsIPrincipal.h"
 #include "nsICookiePermission.h"
 
 #include "nsDOMClassInfoID.h"
 #include "mozilla/Services.h"
 #include "mozilla/Preferences.h"
-#include "GeneratedEvents.h"
 #include "nsThreadUtils.h"
 #include "nsContentUtils.h"
 #include "nsServiceManagerUtils.h"
 
 DOMCI_DATA(Storage, mozilla::dom::DOMStorage)
 
 namespace mozilla {
 namespace dom {
--- a/dom/system/nsDeviceSensors.cpp
+++ b/dom/system/nsDeviceSensors.cpp
@@ -9,22 +9,22 @@
 
 #include "nsAutoPtr.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMDocument.h"
 #include "nsIServiceManager.h"
 #include "nsIServiceManager.h"
-#include "GeneratedEvents.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/Services.h"
 #include "nsIPermissionManager.h"
 #include "mozilla/dom/DeviceLightEvent.h"
+#include "mozilla/dom/DeviceOrientationEvent.h"
 #include "mozilla/dom/DeviceProximityEvent.h"
 #include "mozilla/dom/UserProximityEvent.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace hal;
 
 #undef near
@@ -221,17 +221,17 @@ nsDeviceSensors::Notify(const mozilla::h
 
     if (domdoc) {
       nsCOMPtr<mozilla::dom::EventTarget> target = do_QueryInterface(windowListeners[i]);
       if (type == nsIDeviceSensorData::TYPE_ACCELERATION ||
         type == nsIDeviceSensorData::TYPE_LINEAR_ACCELERATION ||
         type == nsIDeviceSensorData::TYPE_GYROSCOPE)
         FireDOMMotionEvent(domdoc, target, type, x, y, z);
       else if (type == nsIDeviceSensorData::TYPE_ORIENTATION)
-        FireDOMOrientationEvent(domdoc, target, x, y, z);
+        FireDOMOrientationEvent(target, x, y, z);
       else if (type == nsIDeviceSensorData::TYPE_PROXIMITY)
         FireDOMProximityEvent(target, x, y, z);
       else if (type == nsIDeviceSensorData::TYPE_LIGHT)
         FireDOMLightEvent(target, x);
 
     }
   }
 }
@@ -301,43 +301,37 @@ nsDeviceSensors::FireDOMUserProximityEve
 
   event->SetTrusted(true);
 
   bool defaultActionEnabled;
   aTarget->DispatchEvent(event, &defaultActionEnabled);
 }
 
 void
-nsDeviceSensors::FireDOMOrientationEvent(nsIDOMDocument* domdoc,
-                                         EventTarget* target,
-                                         double alpha,
-                                         double beta,
-                                         double gamma)
+nsDeviceSensors::FireDOMOrientationEvent(EventTarget* aTarget,
+                                         double aAlpha,
+                                         double aBeta,
+                                         double aGamma)
 {
-  nsCOMPtr<nsIDOMEvent> event;
-  bool defaultActionEnabled = true;
-  domdoc->CreateEvent(NS_LITERAL_STRING("DeviceOrientationEvent"), getter_AddRefs(event));
-
-  nsCOMPtr<nsIDOMDeviceOrientationEvent> oe = do_QueryInterface(event);
+  DeviceOrientationEventInit init;
+  init.mBubbles = true;
+  init.mCancelable = false;
+  init.mAlpha.SetValue(aAlpha);
+  init.mBeta.SetValue(aBeta);
+  init.mGamma.SetValue(aGamma);
+  init.mAbsolute = true;
 
-  if (!oe) {
-    return;
-  }
-
-  oe->InitDeviceOrientationEvent(NS_LITERAL_STRING("deviceorientation"),
-                                 true,
-                                 false,
-                                 alpha,
-                                 beta,
-                                 gamma,
-                                 true);
-
+  nsRefPtr<DeviceOrientationEvent> event =
+    DeviceOrientationEvent::Constructor(aTarget,
+                                        NS_LITERAL_STRING("deviceorientation"),
+                                        init);
   event->SetTrusted(true);
 
-  target->DispatchEvent(event, &defaultActionEnabled);
+  bool dummy;
+  aTarget->DispatchEvent(event, &dummy);
 }
 
 
 void
 nsDeviceSensors::FireDOMMotionEvent(nsIDOMDocument *domdoc,
                                     EventTarget* target,
                                     uint32_t type,
                                     double x,
--- a/dom/system/nsDeviceSensors.h
+++ b/dom/system/nsDeviceSensors.h
@@ -5,17 +5,16 @@
 #ifndef nsDeviceSensors_h
 #define nsDeviceSensors_h
 
 #include "nsIDeviceSensors.h"
 #include "nsCOMArray.h"
 #include "nsTArray.h"
 #include "nsCOMPtr.h"
 #include "nsITimer.h"
-#include "nsIDOMDeviceOrientationEvent.h"
 #include "mozilla/dom/DeviceMotionEvent.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/HalSensor.h"
 #include "nsDataHashtable.h"
 
 class nsIDOMWindow;
 
 namespace mozilla {
@@ -48,18 +47,17 @@ private:
   void FireDOMProximityEvent(mozilla::dom::EventTarget* aTarget,
                              double aValue,
                              double aMin,
                              double aMax);
 
   void FireDOMUserProximityEvent(mozilla::dom::EventTarget* aTarget,
                                  bool aNear);
 
-  void FireDOMOrientationEvent(class nsIDOMDocument *domDoc,
-                               mozilla::dom::EventTarget* target,
+  void FireDOMOrientationEvent(mozilla::dom::EventTarget* target,
                                double alpha,
                                double beta,
                                double gamma);
 
   void FireDOMMotionEvent(class nsIDOMDocument *domDoc,
                           mozilla::dom::EventTarget* target,
                           uint32_t type,
                           double x,
--- a/dom/tests/mochitest/general/test_bug628069_2.html
+++ b/dom/tests/mochitest/general/test_bug628069_2.html
@@ -24,16 +24,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 gotHashChange = 0;
 document.addEventListener("hashChange", function(e) {
   gotHashChange = 1;
   is(e.oldURL, "oldURL");
   is(e.newURL, "newURL");
   is(e.isTrusted, false, "Hashchange event shouldn't be trusted.");
 }, true);
 
-let hc = document.createEvent("HashChangeEvent");
-hc.initHashChangeEvent("hashChange", true, false, "oldURL", "newURL");
+let hc = new HashChangeEvent("hashChange", { bubbles: true,
+                                             cancelable: false,
+                                             oldURL: "oldURL",
+                                             newURL: "newURL" });
 document.documentElement.dispatchEvent(hc);
 is(gotHashChange, 1, 'Document received hashchange event.');
 
 </script>
 </body>
 </html>
--- a/dom/tests/mochitest/general/test_bug653364.html
+++ b/dom/tests/mochitest/general/test_bug653364.html
@@ -23,16 +23,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 
 gotPopState = 0;
 document.addEventListener("popState", function(e) {
   gotPopState = 1;
   is(e.state.foo, 'bar', "PopState event should have state we set.");
   is(e.isTrusted, false, "PopState event shouldn't be trusted.");
 }, true);
 
-let ps = document.createEvent("PopStateEvent");
-ps.initPopStateEvent("popState", true, false, {'foo': 'bar'});
+let ps = new PopStateEvent("popState", { bubbles: true,
+                                         cancelable: false,
+                                         state: {'foo': 'bar'} });
 document.documentElement.dispatchEvent(ps);
 is(gotPopState, 1, 'Document received PopState event.');
 
 </script>
 </body>
 </html>
--- a/dom/tests/mochitest/general/test_interfaces.html
+++ b/dom/tests/mochitest/general/test_interfaces.html
@@ -347,18 +347,16 @@ var interfaceNamesInGlobalScope =
     "DOMTransactionEvent",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "DragEvent",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "DynamicsCompressorNode",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "Element",
 // IMPORTANT: Do not change this list without review from a DOM peer!
-    "ElementReplaceEvent",
-// IMPORTANT: Do not change this list without review from a DOM peer!
     "ErrorEvent",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "Event",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "EventSource",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "EventTarget",
 // IMPORTANT: Do not change this list without review from a DOM peer!
--- a/dom/voicemail/Voicemail.cpp
+++ b/dom/voicemail/Voicemail.cpp
@@ -9,17 +9,16 @@
 #include "mozilla/dom/MozVoicemailBinding.h"
 #include "mozilla/dom/MozVoicemailEvent.h"
 #include "nsIDOMMozVoicemailStatus.h"
 
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
 #include "nsDOMClassInfo.h"
 #include "nsServiceManagerUtils.h"
-#include "GeneratedEvents.h"
 
 #define NS_RILCONTENTHELPER_CONTRACTID "@mozilla.org/ril/content-helper;1"
 const char* kPrefRilNumRadioInterfaces = "ril.numRadioInterfaces";
 
 using namespace mozilla::dom;
 
 class Voicemail::Listener : public nsIVoicemailListener
 {
--- a/dom/webidl/CloseEvent.webidl
+++ b/dom/webidl/CloseEvent.webidl
@@ -5,31 +5,30 @@
  *
  * The nsIDOMCloseEvent interface is the interface to the event
  * close on a WebSocket object.
  *
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/multipage/network.html#closeevent
  */
 
-[Constructor(DOMString type, optional CloseEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional CloseEventInit eventInitDict),LegacyEventInit]
 interface CloseEvent : Event
 {
   readonly attribute boolean wasClean;
   readonly attribute unsigned short code;
   readonly attribute DOMString? reason;
 
-  // initCloseEvent is a Gecko specific deprecated method.
   [Throws]
-  void initCloseEvent(DOMString type,
-                      boolean canBubble,
-                      boolean cancelable,
-                      boolean wasClean,
-                      unsigned short code,
-                      DOMString? reason);
+  void initCloseEvent(DOMString aType,
+                      boolean aCanBubble,
+                      boolean aCancelable,
+                      boolean aWasClean,
+                      unsigned short aReasonCode,
+                      DOMString? aReason);
 };
 
 dictionary CloseEventInit : EventInit
 {
   boolean wasClean = false;
   unsigned short code = 0;
   DOMString reason = "";
 };
--- a/dom/webidl/CustomEvent.webidl
+++ b/dom/webidl/CustomEvent.webidl
@@ -5,20 +5,19 @@
  *
  * The origin of this IDL file is
  * http://www.w3.org/TR/2012/WD-dom-20120105/
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[Constructor(DOMString type, optional CustomEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional CustomEventInit eventInitDict)]
 interface CustomEvent : Event
 {
-  [Throws]
   readonly attribute any detail;
 
   // initCustomEvent is a Gecko specific deprecated method.
   [Throws]
   void initCustomEvent(DOMString type,
                        boolean canBubble,
                        boolean cancelable,
                        any detail);
--- a/dom/webidl/DOMTransactionEvent.webidl
+++ b/dom/webidl/DOMTransactionEvent.webidl
@@ -1,23 +1,16 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[Constructor(DOMString type, optional DOMTransactionEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional DOMTransactionEventInit eventInitDict)]
 interface DOMTransactionEvent : Event
 {
-  [Throws]
   readonly attribute any transactions;
-
-  [Throws]
-  void initDOMTransactionEvent(DOMString type,
-                               boolean canBubble,
-                               boolean cancelable,
-                               any transactions);
 };
 
 dictionary DOMTransactionEventInit : EventInit
 {
   any transactions = null;
 };
--- a/dom/webidl/DeviceOrientationEvent.webidl
+++ b/dom/webidl/DeviceOrientationEvent.webidl
@@ -1,32 +1,32 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[Constructor(DOMString type, optional DeviceOrientationEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional DeviceOrientationEventInit eventInitDict), LegacyEventInit]
 interface DeviceOrientationEvent : Event
 {
-  readonly attribute double alpha;
-  readonly attribute double beta;
-  readonly attribute double gamma;
+  readonly attribute double? alpha;
+  readonly attribute double? beta;
+  readonly attribute double? gamma;
   readonly attribute boolean absolute;
 
   // initDeviceOrientationEvent is a Gecko specific deprecated method.
   [Throws]
   void initDeviceOrientationEvent(DOMString type,
                                   boolean canBubble,
                                   boolean cancelable,
-                                  double alpha,
-                                  double beta,
-                                  double gamma,
+                                  double? alpha,
+                                  double? beta,
+                                  double? gamma,
                                   boolean absolute);
 };
 
 dictionary DeviceOrientationEventInit : EventInit
 {
-  double alpha = 0;
-  double beta = 0;
-  double gamma = 0;
+  double? alpha = null;
+  double? beta = null;
+  double? gamma = null;
   boolean absolute = false;
 };
--- a/dom/webidl/DeviceStorageChangeEvent.webidl
+++ b/dom/webidl/DeviceStorageChangeEvent.webidl
@@ -1,15 +1,15 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[Constructor(DOMString type, optional DeviceStorageChangeEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional DeviceStorageChangeEventInit eventInitDict)]
 interface DeviceStorageChangeEvent : Event
 {
   readonly attribute DOMString? path;
   readonly attribute DOMString? reason;
 };
 
 dictionary DeviceStorageChangeEventInit : EventInit
 {
deleted file mode 100644
--- a/dom/webidl/ElementReplaceEvent.webidl
+++ /dev/null
@@ -1,23 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/.
- */
-
-[Constructor(DOMString type, optional ElementReplaceEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
-interface ElementReplaceEvent : Event
-{
-  readonly attribute Element? upgrade;
-
-  // initElementReplaceEvent is a Gecko specific deprecated method.
-  [Throws]
-  void initElementReplaceEvent(DOMString type,
-                               boolean canBubble,
-                               boolean cancelable,
-                               Element? upgrade);
-};
-
-dictionary ElementReplaceEventInit : EventInit
-{
-  Element? upgrade = null;
-};
--- a/dom/webidl/HashChangeEvent.webidl
+++ b/dom/webidl/HashChangeEvent.webidl
@@ -1,26 +1,25 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[Constructor(DOMString type, optional HashChangeEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional HashChangeEventInit eventInitDict), LegacyEventInit]
 interface HashChangeEvent : Event
 {
   readonly attribute DOMString? oldURL;
   readonly attribute DOMString? newURL;
 
-  // initHashChangeEvent is a Gecko specific deprecated method.
   [Throws]
-  void initHashChangeEvent(DOMString type,
-                           boolean canBubble,
-                           boolean cancelable,
-                           DOMString? oldURL,
-                           DOMString? newURL);
+  void initHashChangeEvent(DOMString typeArg,
+                           boolean canBubbleArg,
+                           boolean cancelableArg,
+                           DOMString? oldURLArg,
+                           DOMString? newURLArg);
 };
 
 dictionary HashChangeEventInit : EventInit
 {
   DOMString oldURL = "";
   DOMString newURL = "";
 };
--- a/dom/webidl/MozApplicationEvent.webidl
+++ b/dom/webidl/MozApplicationEvent.webidl
@@ -1,16 +1,16 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 interface mozIDOMApplication;
 
-[Constructor(DOMString type, optional MozApplicationEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional MozApplicationEventInit eventInitDict)]
 interface MozApplicationEvent : Event
 {
   readonly attribute mozIDOMApplication? application;
 };
 
 dictionary MozApplicationEventInit : EventInit
 {
   mozIDOMApplication? application = null;
--- a/dom/webidl/MozSettingsEvent.webidl
+++ b/dom/webidl/MozSettingsEvent.webidl
@@ -1,19 +1,18 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[Constructor(DOMString type, optional MozSettingsEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional MozSettingsEventInit eventInitDict)]
 interface MozSettingsEvent : Event
 {
   readonly attribute DOMString? settingName;
-  [Throws]
   readonly attribute any settingValue;
 };
 
 dictionary MozSettingsEventInit : EventInit
 {
   DOMString settingName = "";
   any settingValue = null;
 };
--- a/dom/webidl/PageTransitionEvent.webidl
+++ b/dom/webidl/PageTransitionEvent.webidl
@@ -1,23 +1,16 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[Constructor(DOMString type, optional PageTransitionEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional PageTransitionEventInit eventInitDict)]
 interface PageTransitionEvent : Event
 {
   readonly attribute boolean persisted;
-
-  // initPageTransitionEvent is a Gecko specific deprecated method.
-  [Throws]
-  void initPageTransitionEvent(DOMString type,
-                               boolean canBubble,
-                               boolean cancelable,
-                               boolean persisted);
 };
 
 dictionary PageTransitionEventInit : EventInit
 {
   boolean persisted = false;
 };
--- a/dom/webidl/PopStateEvent.webidl
+++ b/dom/webidl/PopStateEvent.webidl
@@ -1,24 +1,16 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[Constructor(DOMString type, optional PopStateEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional PopStateEventInit eventInitDict)]
 interface PopStateEvent : Event
 {
-  [Throws]
   readonly attribute any state;
-
-  // initPopStateEvent is a Gecko specific deprecated method.
-  [Throws]
-  void initPopStateEvent(DOMString type,
-                         boolean canBubble,
-                         boolean cancelable,
-                         any state);
 };
 
 dictionary PopStateEventInit : EventInit
 {
   any state = null;
 };
--- a/dom/webidl/PopupBlockedEvent.webidl
+++ b/dom/webidl/PopupBlockedEvent.webidl
@@ -1,31 +1,22 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 interface URI;
 
-[Constructor(DOMString type, optional PopupBlockedEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional PopupBlockedEventInit eventInitDict)]
 interface PopupBlockedEvent : Event
 {
   readonly attribute Window? requestingWindow;
   readonly attribute URI? popupWindowURI;
   readonly attribute DOMString? popupWindowName;
   readonly attribute DOMString? popupWindowFeatures;
-
-  [Throws]
-  void initPopupBlockedEvent(DOMString type,
-                             boolean canBubble,
-                             boolean cancelable,
-                             Window? requestingWindow,
-                             URI? popupWindowURI,
-                             DOMString? popupWindowName,
-                             DOMString? popupWindowFeatures);
 };
 
 dictionary PopupBlockedEventInit : EventInit
 {
   Window? requestingWindow = null;
   URI? popupWindowURI = null;
   DOMString popupWindowName = "";
   DOMString popupWindowFeatures = "";
--- a/dom/webidl/RecordErrorEvent.webidl
+++ b/dom/webidl/RecordErrorEvent.webidl
@@ -1,15 +1,15 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[Constructor(DOMString type, optional RecordErrorEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional RecordErrorEventInit eventInitDict)]
 interface RecordErrorEvent : Event
 {
   readonly attribute DOMString name;
 };
 
 dictionary RecordErrorEventInit : EventInit
 {
   DOMString name = "";
--- a/dom/webidl/SmartCardEvent.webidl
+++ b/dom/webidl/SmartCardEvent.webidl
@@ -1,15 +1,15 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[Constructor(DOMString type, optional SmartCardEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[Constructor(DOMString type, optional SmartCardEventInit eventInitDict)]
 interface SmartCardEvent : Event
 {
   readonly attribute DOMString? tokenName;
 };
 
 dictionary SmartCardEventInit : EventInit
 {
   DOMString tokenName = "";
--- a/dom/webidl/SpeechRecognitionEvent.webidl
+++ b/dom/webidl/SpeechRecognitionEvent.webidl
@@ -1,18 +1,17 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 interface nsISupports;
 
 [Pref="media.webspeech.recognition.enable",
- Constructor(DOMString type, optional SpeechRecognitionEventInit eventInitDict),
- HeaderFile="GeneratedEventClasses.h"]
+ Constructor(DOMString type, optional SpeechRecognitionEventInit eventInitDict)]
 interface SpeechRecognitionEvent : Event
 {
   readonly attribute unsigned long resultIndex;
   readonly attribute nsISupports? results;
   readonly attribute DOMString? interpretation;
   readonly attribute Document? emma;
 };
 
--- a/dom/webidl/SpeechSynthesisEvent.webidl
+++ b/dom/webidl/SpeechSynthesisEvent.webidl
@@ -6,17 +6,16 @@
  * The origin of this IDL file is
  * http://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
 [Constructor(DOMString type, optional SpeechSynthesisEventInit eventInitDict),
- HeaderFile="GeneratedEventClasses.h",
  Pref="media.webspeech.synth.enabled"]
 interface SpeechSynthesisEvent : Event
 {
   readonly attribute unsigned long charIndex;
   readonly attribute float elapsedTime;
   readonly attribute DOMString? name;
 };
 
--- a/dom/webidl/StyleRuleChangeEvent.webidl
+++ b/dom/webidl/StyleRuleChangeEvent.webidl
@@ -1,16 +1,16 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 interface CSSRule;
 
-[ChromeOnly, Constructor(DOMString type, optional StyleRuleChangeEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[ChromeOnly, Constructor(DOMString type, optional StyleRuleChangeEventInit eventInitDict)]
 interface StyleRuleChangeEvent : Event
 {
   readonly attribute CSSStyleSheet? stylesheet;
   readonly attribute CSSRule? rule;
 };
 
 dictionary StyleRuleChangeEventInit : EventInit
 {
--- a/dom/webidl/StyleSheetApplicableStateChangeEvent.webidl
+++ b/dom/webidl/StyleSheetApplicableStateChangeEvent.webidl
@@ -1,15 +1,15 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[ChromeOnly, Constructor(DOMString type, optional StyleSheetApplicableStateChangeEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[ChromeOnly, Constructor(DOMString type, optional StyleSheetApplicableStateChangeEventInit eventInitDict)]
 interface StyleSheetApplicableStateChangeEvent : Event
 {
   readonly attribute CSSStyleSheet? stylesheet;
   readonly attribute boolean applicable;
 };
 
 dictionary StyleSheetApplicableStateChangeEventInit : EventInit
 {
--- a/dom/webidl/StyleSheetChangeEvent.webidl
+++ b/dom/webidl/StyleSheetChangeEvent.webidl
@@ -1,15 +1,15 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
-[ChromeOnly, Constructor(DOMString type, optional StyleSheetChangeEventInit eventInitDict), HeaderFile="GeneratedEventClasses.h"]
+[ChromeOnly, Constructor(DOMString type, optional StyleSheetChangeEventInit eventInitDict)]
 interface StyleSheetChangeEvent : Event
 {
   readonly attribute CSSStyleSheet? stylesheet;
   readonly attribute boolean documentSheet;
 };
 
 dictionary StyleSheetChangeEventInit : EventInit
 {
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -511,16 +511,18 @@ if CONFIG['MOZ_WEBRTC']:
     ]
 
 if CONFIG['MOZ_WEBSPEECH']:
     WEBIDL_FILES += [
         'SpeechGrammar.webidl',
         'SpeechGrammarList.webidl',
         'SpeechRecognition.webidl',
         'SpeechRecognitionAlternative.webidl',
+        'SpeechRecognitionError.webidl',
+        'SpeechRecognitionEvent.webidl',
         'SpeechRecognitionResult.webidl',
         'SpeechRecognitionResultList.webidl',
         'SpeechSynthesis.webidl',
         'SpeechSynthesisEvent.webidl',
         'SpeechSynthesisUtterance.webidl',
         'SpeechSynthesisVoice.webidl',
     ]
 
@@ -530,17 +532,16 @@ if CONFIG['MOZ_GAMEPAD']:
     ]
 
 WEBIDL_FILES += [
     'CloseEvent.webidl',
     'CustomEvent.webidl',
     'DeviceOrientationEvent.webidl',
     'DeviceStorageChangeEvent.webidl',
     'DOMTransactionEvent.webidl',
-    'ElementReplaceEvent.webidl',
     'HashChangeEvent.webidl',
     'MozApplicationEvent.webidl',
     'MozSettingsEvent.webidl',
     'PageTransitionEvent.webidl',
     'PopStateEvent.webidl',
     'PopupBlockedEvent.webidl',
     'ProgressEvent.webidl',
     'RecordErrorEvent.webidl',
@@ -603,64 +604,79 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk
         'MozWifiManager.webidl',
         'MozWifiP2pManager.webidl',
     ]
 else:
     WEBIDL_FILES += [
         'InstallTrigger.webidl',
     ]
 
-if CONFIG['MOZ_WEBSPEECH']:
-    WEBIDL_FILES += [
-        'SpeechRecognitionError.webidl',
-        'SpeechRecognitionEvent.webidl',
-    ]
-
 if CONFIG['MOZ_B2G_FM']:
     WEBIDL_FILES += [
         'FMRadio.webidl',
     ]
 
 if not CONFIG['MOZ_DISABLE_CRYPTOLEGACY']:
     WEBIDL_FILES += [
         'CRMFObject.webidl',
     ]
 
 GENERATED_EVENTS_WEBIDL_FILES = [
     'AutocompleteErrorEvent.webidl',
     'BlobEvent.webidl',
     'CallEvent.webidl',
     'CallGroupErrorEvent.webidl',
     'CFStateChangeEvent.webidl',
+    'CloseEvent.webidl',
     'DataErrorEvent.webidl',
     'DataStoreChangeEvent.webidl',
     'DeviceLightEvent.webidl',
+    'DeviceOrientationEvent.webidl',
     'DeviceProximityEvent.webidl',
+    'DeviceStorageChangeEvent.webidl',
+    'DOMTransactionEvent.webidl',
     'DownloadEvent.webidl',
     'ErrorEvent.webidl',
+    'HashChangeEvent.webidl',
     'IccChangeEvent.webidl',
     'MediaStreamEvent.webidl',
+    'MozApplicationEvent.webidl',
     'MozClirModeEvent.webidl',
     'MozContactChangeEvent.webidl',
     'MozEmergencyCbModeEvent.webidl',
     'MozInterAppMessageEvent.webidl',
     'MozMmsEvent.webidl',
     'MozOtaStatusEvent.webidl',
+    'MozSettingsEvent.webidl',
     'MozSmsEvent.webidl',
     'MozStkCommandEvent.webidl',
+    'PageTransitionEvent.webidl',
+    'PopStateEvent.webidl',
+    'PopupBlockedEvent.webidl',
     'ProgressEvent.webidl',
+    'RecordErrorEvent.webidl',
     'RTCDataChannelEvent.webidl',
     'RTCPeerConnectionIceEvent.webidl',
     'RTCPeerConnectionIdentityErrorEvent.webidl',
     'RTCPeerConnectionIdentityEvent.webidl',
+    'SmartCardEvent.webidl',
+    'StyleRuleChangeEvent.webidl',
+    'StyleSheetApplicableStateChangeEvent.webidl',
+    'StyleSheetChangeEvent.webidl',
     'TrackEvent.webidl',
     'UserProximityEvent.webidl',
     'USSDReceivedEvent.webidl',
 ]
 
+if CONFIG['MOZ_WEBSPEECH']:
+    GENERATED_EVENTS_WEBIDL_FILES += [
+        'SpeechRecognitionEvent.webidl',
+        'SpeechSynthesisEvent.webidl',
+    ]
+
 if CONFIG['MOZ_GAMEPAD']:
     GENERATED_EVENTS_WEBIDL_FILES += [
         'GamepadAxisMoveEvent.webidl',
         'GamepadButtonEvent.webidl',
         'GamepadEvent.webidl',
     ]
 
 if CONFIG['MOZ_B2G_BT']:
--- a/extensions/spellcheck/src/mozInlineSpellChecker.cpp
+++ b/extensions/spellcheck/src/mozInlineSpellChecker.cpp
@@ -1,9 +1,10 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set sw=2 ts=2 sts=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/. */
 
 /**
  * This class is called by the editor to handle spellchecking after various
  * events. The main entrypoint is SpellCheckAfterEditorChange, which is called
  * when the text is changed.
@@ -39,17 +40,19 @@
 #include "nsIDOMNode.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMHTMLElement.h"
 #include "nsIDOMMouseEvent.h"
 #include "nsIDOMKeyEvent.h"
 #include "nsIDOMNode.h"
 #include "nsIDOMNodeList.h"
+#include "nsGenericHTMLElement.h"
 #include "nsRange.h"
+#include "mozilla/dom/Selection.h"
 #include "nsIPlaintextEditor.h"
 #include "nsIPrefBranch.h"
 #include "nsIPrefService.h"
 #include "nsIRunnable.h"
 #include "nsISelection.h"
 #include "nsISelectionPrivate.h"
 #include "nsISelectionController.h"
 #include "nsIServiceManager.h"
@@ -59,18 +62,19 @@
 #include "nsUnicharUtils.h"
 #include "nsIContent.h"
 #include "nsRange.h"
 #include "nsContentUtils.h"
 #include "nsEditor.h"
 #include "mozilla/Services.h"
 #include "nsIObserverService.h"
 #include "nsITextControlElement.h"
-#include "prtime.h" 
+#include "prtime.h"
 
+using namespace mozilla;
 using namespace mozilla::dom;
 
 // Set to spew messages to the console about what is happening.
 //#define DEBUG_INLINESPELL
 
 // the number of milliseconds that we will take at once to do spellchecking
 #define INLINESPELL_CHECK_TIMEOUT 50
 
@@ -1203,134 +1207,111 @@ mozInlineSpellChecker::SpellCheckBetween
     return NS_OK; // range is empty: nothing to do
 
   mozInlineSpellStatus status(this);
   rv = status.InitForRange(range);
   NS_ENSURE_SUCCESS(rv, rv);
   return ScheduleSpellCheck(status);
 }
 
-// mozInlineSpellChecker::SkipSpellCheckForNode
+// mozInlineSpellChecker::ShouldSpellCheckNode
 //
 //    There are certain conditions when we don't want to spell check a node. In
 //    particular quotations, moz signatures, etc. This routine returns false
 //    for these cases.
 
-nsresult
-mozInlineSpellChecker::SkipSpellCheckForNode(nsIEditor* aEditor,
-                                             nsIDOMNode *aNode,
-                                             bool *checkSpelling)
+bool
+mozInlineSpellChecker::ShouldSpellCheckNode(nsIEditor* aEditor,
+                                            nsINode *aNode)
 {
-  *checkSpelling = true;
-  NS_ENSURE_ARG_POINTER(aNode);
+  MOZ_ASSERT(aNode);
+  if (!aNode->IsContent())
+    return true;
+
+  nsIContent *content = aNode->AsContent();
 
   uint32_t flags;
   aEditor->GetFlags(&flags);
-  if (flags & nsIPlaintextEditor::eEditorMailMask)
-  {
-    nsCOMPtr<nsIDOMNode> parent;
-    aNode->GetParentNode(getter_AddRefs(parent));
-
-    while (parent)
-    {
-      nsCOMPtr<nsIDOMElement> parentElement = do_QueryInterface(parent);
-      if (!parentElement)
-        break;
-
-      nsAutoString parentTagName;
-      parentElement->GetTagName(parentTagName);
-
-      if (parentTagName.Equals(NS_LITERAL_STRING("blockquote"), nsCaseInsensitiveStringComparator()))
-      {
-        nsAutoString quotetype;
-        parentElement->GetAttribute(NS_LITERAL_STRING("type"), quotetype);
-        if (quotetype.Equals(NS_LITERAL_STRING("cite"), nsCaseInsensitiveStringComparator()))
-        {
-          *checkSpelling = false;
-          break;
-        }
+  if (flags & nsIPlaintextEditor::eEditorMailMask) {
+    nsIContent *parent = content->GetParent();
+    while (parent) {
+      if (parent->IsHTML(nsGkAtoms::blockquote) &&
+          parent->AttrValueIs(kNameSpaceID_None,
+                              nsGkAtoms::type,
+                              nsGkAtoms::cite,
+                              eIgnoreCase)) {
+        return false;
       }
-      else if (parentTagName.Equals(NS_LITERAL_STRING("pre"), nsCaseInsensitiveStringComparator()))
-      {
-        nsAutoString classname;
-        parentElement->GetAttribute(NS_LITERAL_STRING("class"),classname);
-        if (classname.EqualsLiteral("moz-signature"))
-          *checkSpelling = false;
+      if (parent->IsHTML(nsGkAtoms::pre) &&
+          parent->AttrValueIs(kNameSpaceID_None,
+                              nsGkAtoms::_class,
+                              nsGkAtoms::mozsignature,
+                              eIgnoreCase)) {
+        return false;
       }
 
-      nsCOMPtr<nsIDOMNode> nextParent;
-      parent->GetParentNode(getter_AddRefs(nextParent));
-      parent = nextParent;
+      parent = parent->GetParent();
     }
-  }
-  else {
+  } else {
     // Check spelling only if the node is editable, and GetSpellcheck() is true
     // on the nearest HTMLElement ancestor.
-    nsCOMPtr<nsIContent> content = do_QueryInterface(aNode);
     if (!content->IsEditable()) {
-      *checkSpelling = false;
-      return NS_OK;
+      return false;
     }
 
     // Make sure that we can always turn on spell checking for inputs/textareas.
     // Note that because of the previous check, at this point we know that the
     // node is editable.
     if (content->IsInAnonymousSubtree()) {
-      nsCOMPtr<nsIContent> node = content->GetParent();
+      nsIContent *node = content->GetParent();
       while (node && node->IsInNativeAnonymousSubtree()) {
         node = node->GetParent();
       }
       nsCOMPtr<nsITextControlElement> textControl = do_QueryInterface(node);
       if (textControl) {
-        *checkSpelling = true;
-        return NS_OK;
+        return true;
       }
     }
 
     // Get HTML element ancestor (might be aNode itself, although probably that
     // has to be a text node in real life here)
-    nsCOMPtr<nsIDOMHTMLElement> htmlElement = do_QueryInterface(content);
-    while (content && !htmlElement) {
-      content = content->GetParent();
-      htmlElement = do_QueryInterface(content);
-    }
-    NS_ASSERTION(htmlElement, "Why do we have no htmlElement?");
-    if (!htmlElement) {
-      return NS_OK;
+    nsIContent *parent = content;
+    while (!parent->IsHTML()) {
+      parent = parent->GetParent();
+      if (!parent) {
+        return true;
+      }
     }
 
     // See if it's spellcheckable
-    htmlElement->GetSpellcheck(checkSpelling);
-    return NS_OK;
+    return static_cast<nsGenericHTMLElement *>(parent)->Spellcheck();
   }
 
-  return NS_OK;
+  return true;
 }
 
 // mozInlineSpellChecker::ScheduleSpellCheck
 //
 //    This is called by code to do the actual spellchecking. We will set up
 //    the proper structures for calls to DoSpellCheck.
 
 nsresult
 mozInlineSpellChecker::ScheduleSpellCheck(const mozInlineSpellStatus& aStatus)
 {
   if (mFullSpellCheckScheduled) {
     // Just ignore this; we're going to spell-check everything anyway
     return NS_OK;
   }
 
-  mozInlineSpellResume* resume =
+  nsRefPtr<mozInlineSpellResume> resume =
     new mozInlineSpellResume(aStatus, mDisabledAsyncToken);
   NS_ENSURE_TRUE(resume, NS_ERROR_OUT_OF_MEMORY);
 
   nsresult rv = resume->Post();
-  if (NS_FAILED(rv)) {
-    delete resume;
-  } else {
+  if (NS_SUCCEEDED(rv)) {
     if (aStatus.IsFullSpellCheck()) {
       // We're going to check everything.  Suppress further spell-check attempts
       // until that happens.
       mFullSpellCheckScheduled = true;
     }
     ChangeNumPendingSpellChecks(1);
   }
   return rv;
@@ -1344,39 +1325,35 @@ mozInlineSpellChecker::ScheduleSpellChec
 //    be removed from the selection.
 //
 //    FIXME-PERFORMANCE: This takes as long as it takes and is not resumable.
 //    Typically, checking this small amount of text is relatively fast, but
 //    for large numbers of words, a lag may be noticeable.
 
 nsresult
 mozInlineSpellChecker::DoSpellCheckSelection(mozInlineSpellWordUtil& aWordUtil,
-                                             nsISelection* aSpellCheckSelection,
+                                             Selection* aSpellCheckSelection,
                                              mozInlineSpellStatus* aStatus)
 {
   nsresult rv;
 
   // clear out mNumWordsInSpellSelection since we'll be rebuilding the ranges.
   mNumWordsInSpellSelection = 0;
 
   // Since we could be modifying the ranges for the spellCheckSelection while
   // looping on the spell check selection, keep a separate array of range
   // elements inside the selection
-  nsCOMArray<nsIDOMRange> ranges;
+  nsTArray<nsRefPtr<nsRange>> ranges;
 
-  int32_t count;
-  aSpellCheckSelection->GetRangeCount(&count);
+  int32_t count = aSpellCheckSelection->GetRangeCount();
 
-  int32_t idx;
-  nsCOMPtr<nsIDOMRange> checkRange;
-  for (idx = 0; idx < count; idx ++) {
-    aSpellCheckSelection->GetRangeAt(idx, getter_AddRefs(checkRange));
-    if (checkRange) {
-      if (! ranges.AppendObject(checkRange))
-        return NS_ERROR_OUT_OF_MEMORY;
+  for (int32_t idx = 0; idx < count; idx++) {
+    nsRange *range = aSpellCheckSelection->GetRangeAt(idx);
+    if (range) {
+      ranges.AppendElement(range);
     }
   }
 
   // We have saved the ranges above. Clearing the spellcheck selection here
   // isn't necessary (rechecking each word will modify it as necessary) but
   // provides better performance. By ensuring that no ranges need to be
   // removed in DoSpellCheck, we can save checking range inclusion which is
   // slow.
@@ -1385,31 +1362,29 @@ mozInlineSpellChecker::DoSpellCheckSelec
   // We use this state object for all calls, and just update its range. Note
   // that we don't need to call FinishInit since we will be filling in the
   // necessary information.
   mozInlineSpellStatus status(this);
   rv = status.InitForRange(nullptr);
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool doneChecking;
-  for (idx = 0; idx < count; idx ++) {
-    checkRange = ranges[idx];
-    if (checkRange) {
-      // We can consider this word as "added" since we know it has no spell
-      // check range over it that needs to be deleted. All the old ranges
-      // were cleared above. We also need to clear the word count so that we
-      // check all words instead of stopping early.
-      status.mRange = static_cast<nsRange*>(checkRange.get());
-      rv = DoSpellCheck(aWordUtil, aSpellCheckSelection, &status,
-                        &doneChecking);
-      NS_ENSURE_SUCCESS(rv, rv);
-      NS_ASSERTION(doneChecking, "We gave the spellchecker one word, but it didn't finish checking?!?!");
+  for (int32_t idx = 0; idx < count; idx++) {
+    // We can consider this word as "added" since we know it has no spell
+    // check range over it that needs to be deleted. All the old ranges
+    // were cleared above. We also need to clear the word count so that we
+    // check all words instead of stopping early.
+    status.mRange = ranges[idx];
+    rv = DoSpellCheck(aWordUtil, aSpellCheckSelection, &status,
+                      &doneChecking);
+    NS_ENSURE_SUCCESS(rv, rv);
+    MOZ_ASSERT(doneChecking,
+               "We gave the spellchecker one word, but it didn't finish checking?!?!");
 
-      status.mWordCount = 0;
-    }
+    status.mWordCount = 0;
   }
 
   return NS_OK;
 }
 
 // mozInlineSpellChecker::DoSpellCheck
 //
 //    This function checks words intersecting the given range, excluding those
@@ -1437,44 +1412,37 @@ mozInlineSpellChecker::DoSpellCheckSelec
 //                                               [---] aNoCheckRange
 //      -> recheck all words in range except those in aNoCheckRange
 //
 //    If checking is complete, *aDoneChecking will be set. If there is more
 //    but we ran out of time, this will be false and the range will be
 //    updated with the stuff that still needs checking.
 
 nsresult mozInlineSpellChecker::DoSpellCheck(mozInlineSpellWordUtil& aWordUtil,
-                                             nsISelection *aSpellCheckSelection,
+                                             Selection *aSpellCheckSelection,
                                              mozInlineSpellStatus* aStatus,
                                              bool* aDoneChecking)
 {
   *aDoneChecking = true;
 
   NS_ENSURE_TRUE(mSpellCheck, NS_ERROR_NOT_INITIALIZED);
 
-  // get the editor for SkipSpellCheckForNode, this may fail in reasonable
+  // get the editor for ShouldSpellCheckNode, this may fail in reasonable
   // circumstances since the editor could have gone away
   nsCOMPtr<nsIEditor> editor (do_QueryReferent(mEditor));
   if (! editor)
     return NS_ERROR_FAILURE;
 
-  bool iscollapsed;
-  nsresult rv = aStatus->mRange->GetCollapsed(&iscollapsed);
-  NS_ENSURE_SUCCESS(rv, rv);
-  if (iscollapsed)
+  if (aStatus->mRange->Collapsed())
     return NS_OK;
 
-  nsCOMPtr<nsISelectionPrivate> privSel = do_QueryInterface(aSpellCheckSelection);
-
   // see if the selection has any ranges, if not, then we can optimize checking
   // range inclusion later (we have no ranges when we are initially checking or
   // when there are no misspelled words yet).
-  int32_t originalRangeCount;
-  rv = aSpellCheckSelection->GetRangeCount(&originalRangeCount);
-  NS_ENSURE_SUCCESS(rv, rv);
+  int32_t originalRangeCount = aSpellCheckSelection->GetRangeCount();
 
   // set the starting DOM position to be the beginning of our range
   {
     // Scope for the node/offset pairs here so they don't get
     // accidentally used later
     nsINode* beginNode = aStatus->mRange->GetStartParent();
     int32_t beginOffset = aStatus->mRange->StartOffset();
     nsINode* endNode = aStatus->mRange->GetEndParent();
@@ -1483,106 +1451,98 @@ nsresult mozInlineSpellChecker::DoSpellC
     // Now check that we're still looking at a range that's under
     // aWordUtil.GetRootNode()
     nsINode* rootNode = aWordUtil.GetRootNode();
     if (!nsContentUtils::ContentIsDescendantOf(beginNode, rootNode) ||
         !nsContentUtils::ContentIsDescendantOf(endNode, rootNode)) {
       // Just bail out and don't try to spell-check this
       return NS_OK;
     }
-  
+
     aWordUtil.SetEnd(endNode, endOffset);
     aWordUtil.SetPosition(beginNode, beginOffset);
   }
 
   // aWordUtil.SetPosition flushes pending notifications, check editor again.
+  // XXX Uhhh, *we're* holding a strong ref to the editor.
   editor = do_QueryReferent(mEditor);
   if (! editor)
     return NS_ERROR_FAILURE;
 
   int32_t wordsSinceTimeCheck = 0;
   PRTime beginTime = PR_Now();
 
   nsAutoString wordText;
   nsRefPtr<nsRange> wordRange;
   bool dontCheckWord;
   while (NS_SUCCEEDED(aWordUtil.GetNextWord(wordText,
                                             getter_AddRefs(wordRange),
                                             &dontCheckWord)) &&
          wordRange) {
-    wordsSinceTimeCheck ++;
+    wordsSinceTimeCheck++;
 
     // get the range for the current word.
-    // Not using nsINode here for now because we have to call into
-    // selection APIs that use nsIDOMNode. :(
-    nsCOMPtr<nsIDOMNode> beginNode, endNode;
+    nsINode *beginNode;
+    nsINode *endNode;
     int32_t beginOffset, endOffset;
-    wordRange->GetStartContainer(getter_AddRefs(beginNode));
-    wordRange->GetEndContainer(getter_AddRefs(endNode));
-    wordRange->GetStartOffset(&beginOffset);
-    wordRange->GetEndOffset(&endOffset);
+
+    ErrorResult erv;
+    beginNode = wordRange->GetStartContainer(erv);
+    endNode = wordRange->GetEndContainer(erv);
+    beginOffset = wordRange->GetStartOffset(erv);
+    endOffset = wordRange->GetEndOffset(erv);
 
 #ifdef DEBUG_INLINESPELL
     printf("->Got word \"%s\"", NS_ConvertUTF16toUTF8(wordText).get());
     if (dontCheckWord)
       printf(" (not checking)");
     printf("\n");
 #endif
 
     // see if there is a spellcheck range that already intersects the word
     // and remove it. We only need to remove old ranges, so don't bother if
     // there were no ranges when we started out.
     if (originalRangeCount > 0) {
       // likewise, if this word is inside new text, we won't bother testing
-      bool inCreatedRange = false;
-      if (aStatus->mCreatedRange)
-        aStatus->mCreatedRange->IsPointInRange(beginNode, beginOffset, &inCreatedRange);
-      if (! inCreatedRange) {
-        nsTArray<nsRange*> ranges;
-        nsCOMPtr<nsINode> firstNode = do_QueryInterface(beginNode);
-        nsCOMPtr<nsINode> lastNode = do_QueryInterface(endNode);
-        rv = privSel->GetRangesForIntervalArray(firstNode, beginOffset,
-                                                lastNode, endOffset,
-                                                true, &ranges);
-        NS_ENSURE_SUCCESS(rv, rv);
+      if (!aStatus->mCreatedRange ||
+          !aStatus->mCreatedRange->IsPointInRange(*beginNode, beginOffset, erv)) {
+        nsTArray<nsRefPtr<nsRange>> ranges;
+        aSpellCheckSelection->GetRangesForInterval(*beginNode, beginOffset,
+                                                   *endNode, endOffset,
+                                                   true, ranges, erv);
+        ENSURE_SUCCESS(erv, erv.ErrorCode());
         for (uint32_t i = 0; i < ranges.Length(); i++)
           RemoveRange(aSpellCheckSelection, ranges[i]);
       }
     }
 
     // some words are special and don't need checking
     if (dontCheckWord)
       continue;
 
     // some nodes we don't spellcheck
-    bool checkSpelling;
-    rv = SkipSpellCheckForNode(editor, beginNode, &checkSpelling);
-    NS_ENSURE_SUCCESS(rv, rv);
-    if (!checkSpelling)
+    if (!ShouldSpellCheckNode(editor, beginNode))
       continue;
 
     // Don't check spelling if we're inside the noCheckRange. This needs to
     // be done after we clear any old selection because the excluded word
     // might have been previously marked.
     //
     // We do a simple check to see if the beginning of our word is in the
     // exclusion range. Because the exclusion range is a multiple of a word,
     // this is sufficient.
-    if (aStatus->mNoCheckRange) {
-      bool inExclusion = false;
-      aStatus->mNoCheckRange->IsPointInRange(beginNode, beginOffset,
-                                             &inExclusion);
-      if (inExclusion)
-        continue;
+    if (aStatus->mNoCheckRange &&
+        aStatus->mNoCheckRange->IsPointInRange(*beginNode, beginOffset, erv)) {
+      continue;
     }
 
     // check spelling and add to selection if misspelled
     bool isMisspelled;
     aWordUtil.NormalizeWord(wordText);
-    rv = mSpellCheck->CheckCurrentWordNoSuggest(wordText.get(), &isMisspelled);
+    nsresult rv = mSpellCheck->CheckCurrentWordNoSuggest(wordText.get(), &isMisspelled);
     if (NS_FAILED(rv))
       continue;
 
     if (isMisspelled) {
       // misspelled words count extra toward the max
       wordsSinceTimeCheck += MISSPELLED_WORD_COUNT_PENALTY;
       AddRange(aSpellCheckSelection, wordRange);
 
@@ -1663,36 +1623,37 @@ mozInlineSpellChecker::ResumeCheck(mozIn
   if (! editor)
     return NS_OK; // editor is gone
 
   mozInlineSpellWordUtil wordUtil;
   nsresult rv = wordUtil.Init(mEditor);
   if (NS_FAILED(rv))
     return NS_OK; // editor doesn't like us, don't assert
 
-  nsCOMPtr<nsISelection> spellCheckSelection;
-  rv = GetSpellCheckSelection(getter_AddRefs(spellCheckSelection));
+  nsCOMPtr<nsISelection> spellCheckSelectionRef;
+  rv = GetSpellCheckSelection(getter_AddRefs(spellCheckSelectionRef));
   NS_ENSURE_SUCCESS(rv, rv);
 
+  auto spellCheckSelection =
+    static_cast<Selection *>(spellCheckSelectionRef.get());
+
   nsAutoString currentDictionary;
   rv = mSpellCheck->GetCurrentDictionary(currentDictionary);
   if (NS_FAILED(rv)) {
     // no active dictionary
-    int32_t count;
-    spellCheckSelection->GetRangeCount(&count);
+    int32_t count = spellCheckSelection->GetRangeCount();
     for (int32_t index = count - 1; index >= 0; index--) {
-      nsCOMPtr<nsIDOMRange> checkRange;
-      spellCheckSelection->GetRangeAt(index, getter_AddRefs(checkRange));
+      nsRange *checkRange = spellCheckSelection->GetRangeAt(index);
       if (checkRange) {
         RemoveRange(spellCheckSelection, checkRange);
       }
     }
-    return NS_OK; 
+    return NS_OK;
   }
- 
+
   CleanupRangesInSelection(spellCheckSelection);
 
   rv = aStatus->FinishInitOnEvent(wordUtil);
   NS_ENSURE_SUCCESS(rv, rv);
   if (! aStatus->mRange)
     return NS_OK; // empty range, nothing to do
 
   bool doneChecking = true;
@@ -1737,35 +1698,31 @@ mozInlineSpellChecker::IsPointInSelectio
 
   // there may be more than one range returned, and we don't know what do
   // do with that, so just get the first one
   NS_ADDREF(*aRange = ranges[0]);
   return NS_OK;
 }
 
 nsresult
-mozInlineSpellChecker::CleanupRangesInSelection(nsISelection *aSelection)
+mozInlineSpellChecker::CleanupRangesInSelection(Selection *aSelection)
 {
   // integrity check - remove ranges that have collapsed to nothing. This
   // can happen if the node containing a highlighted word was removed.
-  NS_ENSURE_ARG_POINTER(aSelection);
+  if (!aSelection)
+    return NS_ERROR_FAILURE;
 
-  int32_t count;
-  aSelection->GetRangeCount(&count);
+  int32_t count = aSelection->GetRangeCount();
 
   for (int32_t index = 0; index < count; index++)
   {
-    nsCOMPtr<nsIDOMRange> checkRange;
-    aSelection->GetRangeAt(index, getter_AddRefs(checkRange));
-
+    nsRange *checkRange = aSelection->GetRangeAt(index);
     if (checkRange)
     {
-      bool collapsed;
-      checkRange->GetCollapsed(&collapsed);
-      if (collapsed)
+      if (checkRange->Collapsed())
       {
         RemoveRange(aSelection, checkRange);
         index--;
         count--;
       }
     }
   }
 
@@ -1775,27 +1732,28 @@ mozInlineSpellChecker::CleanupRangesInSe
 
 // mozInlineSpellChecker::RemoveRange
 //
 //    For performance reasons, we have an upper bound on the number of word
 //    ranges  in the spell check selection. When removing a range from the
 //    selection, we need to decrement mNumWordsInSpellSelection
 
 nsresult
-mozInlineSpellChecker::RemoveRange(nsISelection* aSpellCheckSelection,
-                                   nsIDOMRange* aRange)
+mozInlineSpellChecker::RemoveRange(Selection *aSpellCheckSelection,
+                                   nsRange *aRange)
 {
   NS_ENSURE_ARG_POINTER(aSpellCheckSelection);
   NS_ENSURE_ARG_POINTER(aRange);
 
-  nsresult rv = aSpellCheckSelection->RemoveRange(aRange);
-  if (NS_SUCCEEDED(rv) && mNumWordsInSpellSelection)
+  ErrorResult rv;
+  aSpellCheckSelection->RemoveRange(*aRange, rv);
+  if (!rv.Failed() && mNumWordsInSpellSelection)
     mNumWordsInSpellSelection--;
 
-  return rv;
+  return rv.ErrorCode();
 }
 
 
 // mozInlineSpellChecker::AddRange
 //
 //    For performance reasons, we have an upper bound on the number of word
 //    ranges we'll add to the spell check selection. Once we reach that upper
 //    bound, stop adding the ranges
--- a/extensions/spellcheck/src/mozInlineSpellChecker.h
+++ b/extensions/spellcheck/src/mozInlineSpellChecker.h
@@ -72,17 +72,17 @@ public:
   Operation mOp;
 
   // Used for events where we have already computed the range to use. It can
   // also be nullptr in these cases where we need to check the entire range.
   nsRefPtr<nsRange> mRange;
 
   // If we happen to know something was inserted, this is that range.
   // Can be nullptr (this only allows an optimization, so not setting doesn't hurt)
-  nsCOMPtr<nsIDOMRange> mCreatedRange;
+  nsRefPtr<nsRange> mCreatedRange;
 
   // Contains the range computed for the current word. Can be nullptr.
   nsRefPtr<nsRange> mNoCheckRange;
 
   // Indicates the position of the cursor for the event (so we can compute
   // mNoCheckRange). It can be nullptr if we don't care about the cursor position
   // (such as for the intial check of everything).
   //
@@ -207,44 +207,44 @@ public:
   nsresult SpellCheckBetweenNodes(nsIDOMNode *aStartNode,
                                   int32_t aStartOffset,
                                   nsIDOMNode *aEndNode,
                                   int32_t aEndOffset);
 
   // examines the dom node in question and returns true if the inline spell
   // checker should skip the node (i.e. the text is inside of a block quote
   // or an e-mail signature...)
-  nsresult SkipSpellCheckForNode(nsIEditor* aEditor,
-                                 nsIDOMNode *aNode, bool * aCheckSpelling);
+  bool ShouldSpellCheckNode(nsIEditor* aEditor, nsINode *aNode);
 
   nsresult SpellCheckAfterChange(nsIDOMNode* aCursorNode, int32_t aCursorOffset,
                                  nsIDOMNode* aPreviousNode, int32_t aPreviousOffset,
                                  nsISelection* aSpellCheckSelection);
 
   // spell check the text contained within aRange, potentially scheduling
   // another check in the future if the time threshold is reached
   nsresult ScheduleSpellCheck(const mozInlineSpellStatus& aStatus);
 
   nsresult DoSpellCheckSelection(mozInlineSpellWordUtil& aWordUtil,
-                                 nsISelection* aSpellCheckSelection,
+                                 mozilla::dom::Selection* aSpellCheckSelection,
                                  mozInlineSpellStatus* aStatus);
   nsresult DoSpellCheck(mozInlineSpellWordUtil& aWordUtil,
-                        nsISelection *aSpellCheckSelection,
+                        mozilla::dom::Selection *aSpellCheckSelection,
                         mozInlineSpellStatus* aStatus,
                         bool* aDoneChecking);
 
   // helper routine to determine if a point is inside of the passed in selection.
   nsresult IsPointInSelection(nsISelection *aSelection,
                               nsIDOMNode *aNode,
                               int32_t aOffset,
                               nsIDOMRange **aRange);
 
-  nsresult CleanupRangesInSelection(nsISelection *aSelection);
+  nsresult CleanupRangesInSelection(mozilla::dom::Selection *aSelection);
 
-  nsresult RemoveRange(nsISelection *aSpellCheckSelection, nsIDOMRange * aRange);
+  nsresult RemoveRange(mozilla::dom::Selection *aSpellCheckSelection,
+                       nsRange *aRange);
   nsresult AddRange(nsISelection *aSpellCheckSelection, nsIDOMRange * aRange);
   bool     SpellCheckSelectionIsFull() { return mNumWordsInSpellSelection >= mMaxNumWordsInSpellSelection; }
 
   nsresult MakeSpellCheckRange(nsIDOMNode* aStartNode, int32_t aStartOffset,
                                nsIDOMNode* aEndNode, int32_t aEndOffset,
                                nsRange** aRange);
 
   // DOM and editor event registration helper routines
--- a/gfx/2d/DrawTargetCairo.cpp
+++ b/gfx/2d/DrawTargetCairo.cpp
@@ -128,16 +128,46 @@ PatternIsCompatible(const Pattern& aPatt
 static cairo_user_data_key_t surfaceDataKey;
 
 void
 ReleaseData(void* aData)
 {
   static_cast<DataSourceSurface*>(aData)->Release();
 }
 
+cairo_surface_t*
+CopyToImageSurface(unsigned char *aData,
+                   const IntSize &aSize,
+                   int32_t aStride,
+                   SurfaceFormat aFormat)
+{
+  cairo_surface_t* surf = cairo_image_surface_create(GfxFormatToCairoFormat(aFormat),
+                                                     aSize.width,
+                                                     aSize.height);
+  // In certain scenarios, requesting larger than 8k image fails.  Bug 803568
+  // covers the details of how to run into it, but the full detailed
+  // investigation hasn't been done to determine the underlying cause.  We
+  // will just handle the failure to allocate the surface to avoid a crash.
+  if (cairo_surface_status(surf)) {
+    return nullptr;
+  }
+
+  unsigned char* surfData = cairo_image_surface_get_data(surf);
+  int surfStride = cairo_image_surface_get_stride(surf);
+  int32_t pixelWidth = BytesPerPixel(aFormat);
+
+  for (int32_t y = 0; y < aSize.height; ++y) {
+    memcpy(surfData + y * surfStride,
+           aData + y * aStride,
+           aSize.width * pixelWidth);
+  }
+  cairo_surface_mark_dirty(surf);
+  return surf;
+}
+
 /**
  * Returns cairo surface for the given SourceSurface.
  * If possible, it will use the cairo_surface associated with aSurface,
  * otherwise, it will create a new cairo_surface.
  * In either case, the caller must call cairo_surface_destroy on the
  * result when it is done with it.
  */
 cairo_surface_t*
@@ -172,17 +202,26 @@ GetCairoSurfaceForSourceSurface(SourceSu
                                         data->GetSize().height,
                                         data->Stride());
 
   // In certain scenarios, requesting larger than 8k image fails.  Bug 803568
   // covers the details of how to run into it, but the full detailed
   // investigation hasn't been done to determine the underlying cause.  We
   // will just handle the failure to allocate the surface to avoid a crash.
   if (cairo_surface_status(surf)) {
-    cairo_surface_destroy(surf);
+    if (cairo_surface_status(surf) == CAIRO_STATUS_INVALID_STRIDE) {
+      // If we failed because of an invalid stride then copy into
+      // a new surface with a stride that cairo chooses. No need to
+      // set user data since we're not dependent on the original
+      // data.
+      return CopyToImageSurface(data->GetData(),
+                                data->GetSize(),
+                                data->Stride(),
+                                data->GetFormat());
+    }
     return nullptr;
   }
 
   cairo_surface_set_user_data(surf,
  				                      &surfaceDataKey,
  				                      data.forget().drop(),
  				                      ReleaseData);
   return surf;
@@ -1051,62 +1090,23 @@ DrawTargetCairo::CreateGradientStops(Gra
 }
 
 TemporaryRef<FilterNode>
 DrawTargetCairo::CreateFilter(FilterType aType)
 {
   return FilterNodeSoftware::Create(aType);
 }
 
-/**
- * Copies pixel data from aData into aSurface; aData must have the dimensions
- * given in aSize, with a stride of aStride bytes and aPixelWidth bytes per pixel
- */
-static void
-CopyDataToCairoSurface(cairo_surface_t* aSurface,
-                       unsigned char *aData,
-                       const IntSize &aSize,
-                       int32_t aStride,
-                       int32_t aPixelWidth)
-{
-  unsigned char* surfData = cairo_image_surface_get_data(aSurface);
-  int surfStride = cairo_image_surface_get_stride(aSurface);
-  // In certain scenarios, requesting larger than 8k image fails.  Bug 803568
-  // covers the details of how to run into it, but the full detailed
-  // investigation hasn't been done to determine the underlying cause.  We
-  // will just handle the failure to allocate the surface to avoid a crash.
-  if (!surfData) {
-    return;
-  }
-  for (int32_t y = 0; y < aSize.height; ++y) {
-    memcpy(surfData + y * surfStride,
-           aData + y * aStride,
-           aSize.width * aPixelWidth);
-  }
-  cairo_surface_mark_dirty(aSurface);
-}
-
 TemporaryRef<SourceSurface>
 DrawTargetCairo::CreateSourceSurfaceFromData(unsigned char *aData,
                                              const IntSize &aSize,
                                              int32_t aStride,
                                              SurfaceFormat aFormat) const
 {
-  cairo_surface_t* surf = cairo_image_surface_create(GfxFormatToCairoFormat(aFormat),
-                                                     aSize.width,
-                                                     aSize.height);
-  // In certain scenarios, requesting larger than 8k image fails.  Bug 803568
-  // covers the details of how to run into it, but the full detailed
-  // investigation hasn't been done to determine the underlying cause.  We
-  // will just handle the failure to allocate the surface to avoid a crash.
-  if (cairo_surface_status(surf)) {
-    return nullptr;
-  }
-
-  CopyDataToCairoSurface(surf, aData, aSize, aStride, BytesPerPixel(aFormat));
+  cairo_surface_t* surf = CopyToImageSurface(aData, aSize, aStride, aFormat);
 
   RefPtr<SourceSurfaceCairo> source_surf = new SourceSurfaceCairo(surf, aSize, aFormat);
   cairo_surface_destroy(surf);
 
   return source_surf.forget();
 }
 
 #ifdef CAIRO_HAS_XLIB_SURFACE
--- a/gfx/2d/DrawTargetCairo.h
+++ b/gfx/2d/DrawTargetCairo.h
@@ -193,16 +193,17 @@ private: // methods
 
   // Call if there is any reason to disassociate the snapshot from this draw
   // target; for example, because we're going to be destroyed.
   void MarkSnapshotIndependent();
 
   // If the current operator is "source" then clear the destination before we
   // draw into it, to simulate the effect of an unbounded source operator.
   void ClearSurfaceForUnboundedSource(const CompositionOp &aOperator);
+
 private: // data
   cairo_t* mContext;
   cairo_surface_t* mSurface;
   IntSize mSize;
 
   uint8_t* mLockedBits;
 
   // The latest snapshot of this surface. This needs to be told when this
--- a/gfx/2d/SourceSurfaceD2D.cpp
+++ b/gfx/2d/SourceSurfaceD2D.cpp
@@ -171,20 +171,27 @@ DataSourceSurfaceD2D::DataSourceSurfaceD
                                                                byRef(renderTarget));
   if (FAILED(hr)) {
     gfxWarning() << "Failed to create render target. Code: " << hr;
     return;
   }
 
   renderTarget->BeginDraw();
   renderTarget->Clear(D2D1::ColorF(0, 0.0f));
-  renderTarget->DrawBitmap(aSourceSurface->mBitmap,
-                           D2D1::RectF(0, 0,
-                                       Float(mSize.width),
-                                       Float(mSize.height)));
+  if (aSourceSurface->GetFormat() != SurfaceFormat::A8) {
+    renderTarget->DrawBitmap(aSourceSurface->mBitmap,
+                             D2D1::RectF(0, 0,
+                             Float(mSize.width),
+                             Float(mSize.height)));
+  } else {
+    RefPtr<ID2D1SolidColorBrush> brush;
+    renderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), byRef(brush));
+    renderTarget->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED);
+    renderTarget->FillOpacityMask(aSourceSurface->mBitmap, brush, D2D1_OPACITY_MASK_CONTENT_GRAPHICS);
+  }
   hr = renderTarget->EndDraw();
   if (FAILED(hr)) {
     gfxWarning() << "Failed to draw bitmap. Code: " << hr;
     return;
   }
 
   desc.CPUAccessFlags = D3D10_CPU_ACCESS_READ | D3D10_CPU_ACCESS_WRITE;
   desc.Usage = D3D10_USAGE_STAGING;
--- a/gfx/layers/composite/TextureHost.cpp
+++ b/gfx/layers/composite/TextureHost.cpp
@@ -827,16 +827,19 @@ StreamTextureHost::~StreamTextureHost()
 bool
 StreamTextureHost::Lock()
 {
   if (!mCompositor) {
     return false;
   }
 
   gfx::SharedSurface* abstractSurf = mStream->SwapConsumer();
+  if (!abstractSurf) {
+    return false;
+  }
 
   bool compositorSupportsShSurfType = false;
   switch (mCompositor->GetBackendType()) {
     case LayersBackend::LAYERS_BASIC:
     case LayersBackend::LAYERS_D3D9:
     case LayersBackend::LAYERS_D3D10:
       switch (abstractSurf->Type()) {
         case gfx::SharedSurfaceType::Basic:
--- a/gfx/layers/ipc/ShadowLayerUtilsGralloc.cpp
+++ b/gfx/layers/ipc/ShadowLayerUtilsGralloc.cpp
@@ -49,18 +49,20 @@ ParamTraits<GrallocBufferRef>::Write(Mes
 
 bool
 ParamTraits<GrallocBufferRef>::Read(const Message* aMsg, void** aIter,
                                     paramType* aParam)
 {
   int owner;
   int index;
   if (!aMsg->ReadInt(aIter, &owner) ||
-      !aMsg->ReadInt32(aIter, &index))
+      !aMsg->ReadInt32(aIter, &index)) {
+    printf_stderr("ParamTraits<GrallocBufferRef>::Read() failed to read a message\n");
     return false;
+  }
   aParam->mOwner = owner;
   aParam->mKey = index;
   return true;
 }
 
 void
 ParamTraits<MagicGrallocBufferHandle>::Write(Message* aMsg,
                                              const paramType& aParam)
@@ -116,33 +118,35 @@ ParamTraits<MagicGrallocBufferHandle>::R
   int owner;
   int index;
 
   if (!aMsg->ReadInt(aIter, &owner) ||
       !aMsg->ReadInt32(aIter, &index) ||
       !aMsg->ReadSize(aIter, &nbytes) ||
       !aMsg->ReadSize(aIter, &nfds) ||
       !aMsg->ReadBytes(aIter, &data, nbytes)) {
+    printf_stderr("ParamTraits<MagicGrallocBufferHandle>::Read() failed to read a message\n");
     return false;
   }
 
   int fds[nfds];
   bool sameProcess = (XRE_GetProcessType() == GeckoProcessType_Default);
   for (size_t n = 0; n < nfds; ++n) {
     FileDescriptor fd;
     if (!aMsg->ReadFileDescriptor(aIter, &fd)) {
+      printf_stderr("ParamTraits<MagicGrallocBufferHandle>::Read() failed to read file descriptors\n");
       return false;
     }
     // If the GraphicBuffer was shared cross-process, SCM_RIGHTS does
-    // the right thing and dup's the fd.  If it's shared cross-thread,
-    // SCM_RIGHTS doesn't dup the fd.  That's surprising, but we just
-    // deal with it here.  NB: only the "default" (master) process can
-    // alloc gralloc buffers.
-    int dupFd = sameProcess && index < 0 ? dup(fd.fd) : fd.fd;
-    fds[n] = dupFd;
+    // the right thing and dup's the fd. If it's shared cross-thread,
+    // SCM_RIGHTS doesn't dup the fd. 
+    // But in shared cross-thread, dup fd is not necessary because we get
+    // a pointer to the GraphicBuffer directly from SharedBufferManagerParent
+    // and don't create a new GraphicBuffer around the fd.
+    fds[n] = fd.fd;
   }
 
   aResult->mRef.mOwner = owner;
   aResult->mRef.mKey = index;
   if (sameProcess)
     aResult->mGraphicBuffer = SharedBufferManagerParent::GetGraphicBuffer(aResult->mRef);
   else {
     aResult->mGraphicBuffer = SharedBufferManagerChild::GetSingleton()->GetGraphicBuffer(index);
@@ -162,16 +166,17 @@ ParamTraits<MagicGrallocBufferHandle>::R
       if (NO_ERROR == flattenable->unflatten(data, nbytes, fds, nfds)) {
         aResult->mGraphicBuffer = buffer;
       }
 #endif
     }
   }
 
   if (aResult->mGraphicBuffer == nullptr) {
+    printf_stderr("ParamTraits<MagicGrallocBufferHandle>::Read() failed to get gralloc buffer\n");
     return false;
   }
 
   return true;
 }
 
 } // namespace IPC
 
--- a/js/ipc/JavaScriptBase.h
+++ b/js/ipc/JavaScriptBase.h
@@ -62,35 +62,35 @@ class JavaScriptBase : public WrapperOwn
     bool AnswerHas(const ObjectId &objId, const nsString &id,
                    ReturnStatus *rs, bool *bp) {
         return Answer::AnswerHas(objId, id, rs, bp);
     }
     bool AnswerHasOwn(const ObjectId &objId, const nsString &id,
                       ReturnStatus *rs, bool *bp) {
         return Answer::AnswerHasOwn(objId, id, rs, bp);
     }
-    bool AnswerGet(const ObjectId &objId, const ObjectId &receiverId,
+    bool AnswerGet(const ObjectId &objId, const ObjectVariant &receiverVar,
                    const nsString &id,
                    ReturnStatus *rs, JSVariant *result) {
-        return Answer::AnswerGet(objId, receiverId, id, rs, result);
+        return Answer::AnswerGet(objId, receiverVar, id, rs, result);
     }
-    bool AnswerSet(const ObjectId &objId, const ObjectId &receiverId,
+    bool AnswerSet(const ObjectId &objId, const ObjectVariant &receiverVar,
                    const nsString &id, const bool &strict,
                    const JSVariant &value, ReturnStatus *rs, JSVariant *result) {
-        return Answer::AnswerSet(objId, receiverId, id, strict, value, rs, result);
+        return Answer::AnswerSet(objId, receiverVar, id, strict, value, rs, result);
     }
 
     bool AnswerIsExtensible(const ObjectId &objId, ReturnStatus *rs,
                             bool *result) {
         return Answer::AnswerIsExtensible(objId, rs, result);
     }
-    bool AnswerCall(const ObjectId &objId, const nsTArray<JSParam> &argv,
-                    ReturnStatus *rs, JSVariant *result,
-                    nsTArray<JSParam> *outparams) {
-        return Answer::AnswerCall(objId, argv, rs, result, outparams);
+    bool AnswerCallOrConstruct(const ObjectId &objId, const nsTArray<JSParam> &argv,
+                               const bool &construct, ReturnStatus *rs, JSVariant *result,
+                               nsTArray<JSParam> *outparams) {
+        return Answer::AnswerCallOrConstruct(objId, argv, construct, rs, result, outparams);
     }
     bool AnswerObjectClassIs(const ObjectId &objId, const uint32_t &classValue,
                              bool *result) {
         return Answer::AnswerObjectClassIs(objId, classValue, result);
     }
     bool AnswerClassName(const ObjectId &objId, nsString *result) {
         return Answer::AnswerClassName(objId, result);
     }
@@ -144,35 +144,35 @@ class JavaScriptBase : public WrapperOwn
     bool CallHas(const ObjectId &objId, const nsString &id,
                    ReturnStatus *rs, bool *bp) {
         return Base::CallHas(objId, id, rs, bp);
     }
     bool CallHasOwn(const ObjectId &objId, const nsString &id,
                     ReturnStatus *rs, bool *bp) {
         return Base::CallHasOwn(objId, id, rs, bp);
     }
-    bool CallGet(const ObjectId &objId, const ObjectId &receiverId,
+    bool CallGet(const ObjectId &objId, const ObjectVariant &receiverVar,
                  const nsString &id,
                  ReturnStatus *rs, JSVariant *result) {
-        return Base::CallGet(objId, receiverId, id, rs, result);
+        return Base::CallGet(objId, receiverVar, id, rs, result);
     }
-    bool CallSet(const ObjectId &objId, const ObjectId &receiverId,
+    bool CallSet(const ObjectId &objId, const ObjectVariant &receiverVar,
                  const nsString &id, const bool &strict,
                  const JSVariant &value, ReturnStatus *rs, JSVariant *result) {
-        return Base::CallSet(objId, receiverId, id, strict, value, rs, result);
+        return Base::CallSet(objId, receiverVar, id, strict, value, rs, result);
     }
 
     bool CallIsExtensible(const ObjectId &objId, ReturnStatus *rs,
                           bool *result) {
         return Base::CallIsExtensible(objId, rs, result);
     }
-    bool CallCall(const ObjectId &objId, const nsTArray<JSParam> &argv,
-                  ReturnStatus *rs, JSVariant *result,
-                  nsTArray<JSParam> *outparams) {
-        return Base::CallCall(objId, argv, rs, result, outparams);
+    bool CallCallOrConstruct(const ObjectId &objId, const nsTArray<JSParam> &argv,
+                             const bool &construct, ReturnStatus *rs, JSVariant *result,
+                             nsTArray<JSParam> *outparams) {
+        return Base::CallCallOrConstruct(objId, argv, construct, rs, result, outparams);
     }
     bool CallObjectClassIs(const ObjectId &objId, const uint32_t &classValue,
                            bool *result) {
         return Base::CallObjectClassIs(objId, classValue, result);
     }
     bool CallClassName(const ObjectId &objId, nsString *result) {
         return Base::CallClassName(objId, result);
     }
--- a/js/ipc/PJavaScript.ipdl
+++ b/js/ipc/PJavaScript.ipdl
@@ -27,21 +27,21 @@ both:
     rpc PreventExtensions(uint64_t objId) returns (ReturnStatus rs);
     rpc GetPropertyDescriptor(uint64_t objId, nsString id) returns (ReturnStatus rs, PPropertyDescriptor result);
     rpc GetOwnPropertyDescriptor(uint64_t objId, nsString id) returns (ReturnStatus rs, PPropertyDescriptor result);
     rpc DefineProperty(uint64_t objId, nsString id, PPropertyDescriptor descriptor) returns (ReturnStatus rs);
     rpc Delete(uint64_t objId, nsString id) returns (ReturnStatus rs, bool successful);
 
     rpc Has(uint64_t objId, nsString id) returns (ReturnStatus rs, bool has);
     rpc HasOwn(uint64_t objId, nsString id) returns (ReturnStatus rs, bool has);
-    rpc Get(uint64_t objId, uint64_t receiverId, nsString id) returns (ReturnStatus rs, JSVariant result);
-    rpc Set(uint64_t objId, uint64_t receiverId, nsString id, bool strict, JSVariant value) returns (ReturnStatus rs, JSVariant result);
+    rpc Get(uint64_t objId, ObjectVariant receiver, nsString id) returns (ReturnStatus rs, JSVariant result);
+    rpc Set(uint64_t objId, ObjectVariant receiver, nsString id, bool strict, JSVariant value) returns (ReturnStatus rs, JSVariant result);
 
     rpc IsExtensible(uint64_t objId) returns (ReturnStatus rs, bool result);
-    rpc Call(uint64_t objId, JSParam[] argv) returns (ReturnStatus rs, JSVariant result, JSParam[] outparams);
+    rpc CallOrConstruct(uint64_t objId, JSParam[] argv, bool construct) returns (ReturnStatus rs, JSVariant result, JSParam[] outparams);
     rpc ObjectClassIs(uint64_t objId, uint32_t classValue) returns (bool result);
     rpc ClassName(uint64_t objId) returns (nsString name);
 
     rpc GetPropertyNames(uint64_t objId, uint32_t flags) returns (ReturnStatus rs, nsString[] names);
     rpc InstanceOf(uint64_t objId, JSIID iid) returns (ReturnStatus rs, bool instanceof);
     rpc DOMInstanceOf(uint64_t objId, int prototypeID, int depth) returns (ReturnStatus rs, bool instanceof);
 
 parent:
--- a/js/ipc/WrapperAnswer.cpp
+++ b/js/ipc/WrapperAnswer.cpp
@@ -272,36 +272,36 @@ WrapperAnswer::AnswerHasOwn(const Object
     if (!JS_GetPropertyDescriptorById(cx, obj, internedId, &desc))
         return fail(cx, rs);
     *bp = (desc.object() == obj);
 
     return ok(rs);
 }
 
 bool
-WrapperAnswer::AnswerGet(const ObjectId &objId, const ObjectId &receiverId, const nsString &id,
+WrapperAnswer::AnswerGet(const ObjectId &objId, const ObjectVariant &receiverVar, const nsString &id,
 			 ReturnStatus *rs, JSVariant *result)
 {
     AutoSafeJSContext cx;
     JSAutoRequest request(cx);
 
     // The outparam will be written to the buffer, so it must be set even if
     // the parent won't read it.
     *result = UndefinedVariant();
 
     RootedObject obj(cx, findObjectById(cx, objId));
     if (!obj)
         return fail(cx, rs);
 
-    RootedObject receiver(cx, findObjectById(cx, receiverId));
+    JSAutoCompartment comp(cx, obj);
+
+    RootedObject receiver(cx, fromObjectVariant(cx, receiverVar));
     if (!receiver)
         return fail(cx, rs);
 
-    JSAutoCompartment comp(cx, obj);
-
     RootedId internedId(cx);
     if (!convertGeckoStringToId(cx, id, &internedId))
         return fail(cx, rs);
 
     JS::RootedValue val(cx);
     if (!JS_ForwardGetPropertyTo(cx, obj, internedId, receiver, &val))
         return fail(cx, rs);
 
@@ -309,37 +309,37 @@ WrapperAnswer::AnswerGet(const ObjectId 
         return fail(cx, rs);
 
     LOG("get %s.%s = %s", ReceiverObj(objId), id, OutVariant(*result));
 
     return ok(rs);
 }
 
 bool
-WrapperAnswer::AnswerSet(const ObjectId &objId, const ObjectId &receiverId, const nsString &id,
+WrapperAnswer::AnswerSet(const ObjectId &objId, const ObjectVariant &receiverVar, const nsString &id,
 			 const bool &strict, const JSVariant &value, ReturnStatus *rs,
 			 JSVariant *result)
 {
     AutoSafeJSContext cx;
     JSAutoRequest request(cx);
 
     // The outparam will be written to the buffer, so it must be set even if
     // the parent won't read it.
     *result = UndefinedVariant();
 
     RootedObject obj(cx, findObjectById(cx, objId));
     if (!obj)
         return fail(cx, rs);
 
-    RootedObject receiver(cx, findObjectById(cx, receiverId));
+    JSAutoCompartment comp(cx, obj);
+
+    RootedObject receiver(cx, fromObjectVariant(cx, receiverVar));
     if (!receiver)
         return fail(cx, rs);
 
-    JSAutoCompartment comp(cx, obj);
-
     LOG("set %s[%s] = %s", ReceiverObj(objId), id, InVariant(value));
 
     RootedId internedId(cx);
     if (!convertGeckoStringToId(cx, id, &internedId))
         return fail(cx, rs);
 
     MOZ_ASSERT(obj == receiver);
 
@@ -376,18 +376,22 @@ WrapperAnswer::AnswerIsExtensible(const 
     if (!JS_IsExtensible(cx, obj, &extensible))
         return fail(cx, rs);
 
     *result = !!extensible;
     return ok(rs);
 }
 
 bool
-WrapperAnswer::AnswerCall(const ObjectId &objId, const nsTArray<JSParam> &argv, ReturnStatus *rs,
-			  JSVariant *result, nsTArray<JSParam> *outparams)
+WrapperAnswer::AnswerCallOrConstruct(const ObjectId &objId,
+                                     const nsTArray<JSParam> &argv,
+                                     const bool &construct,
+                                     ReturnStatus *rs,
+                                     JSVariant *result,
+                                     nsTArray<JSParam> *outparams)
 {
     AutoSafeJSContext cx;
     JSAutoRequest request(cx);
 
     // The outparam will be written to the buffer, so it must be set even if
     // the parent won't read it.
     *result = UndefinedVariant();
 
@@ -429,17 +433,21 @@ WrapperAnswer::AnswerCall(const ObjectId
     }
 
     RootedValue rval(cx);
     {
         AutoSaveContextOptions asco(cx);
         ContextOptionsRef(cx).setDontReportUncaught(true);
 
         HandleValueArray args = HandleValueArray::subarray(vals, 2, vals.length() - 2);
-        bool success = JS::Call(cx, vals[1], vals[0], args, &rval);
+        bool success;
+        if (construct)
+            success = JS::Construct(cx, vals[0], args, &rval);
+        else
+            success = JS::Call(cx, vals[1], vals[0], args, &rval);
         if (!success)
             return fail(cx, rs);
     }
 
     if (!toVariant(cx, rval, result))
         return fail(cx, rs);
 
     // Prefill everything with a dummy jsval.
--- a/js/ipc/WrapperAnswer.h
+++ b/js/ipc/WrapperAnswer.h
@@ -31,28 +31,28 @@ class WrapperAnswer : public virtual Jav
                               ReturnStatus *rs);
     bool AnswerDelete(const ObjectId &objId, const nsString &id,
                       ReturnStatus *rs, bool *success);
 
     bool AnswerHas(const ObjectId &objId, const nsString &id,
                        ReturnStatus *rs, bool *bp);
     bool AnswerHasOwn(const ObjectId &objId, const nsString &id,
                           ReturnStatus *rs, bool *bp);
-    bool AnswerGet(const ObjectId &objId, const ObjectId &receiverId,
+    bool AnswerGet(const ObjectId &objId, const ObjectVariant &receiverVar,
                        const nsString &id,
                        ReturnStatus *rs, JSVariant *result);
-    bool AnswerSet(const ObjectId &objId, const ObjectId &receiverId,
+    bool AnswerSet(const ObjectId &objId, const ObjectVariant &receiverVar,
                    const nsString &id, const bool &strict,
                    const JSVariant &value, ReturnStatus *rs, JSVariant *result);
 
     bool AnswerIsExtensible(const ObjectId &objId, ReturnStatus *rs,
                             bool *result);
-    bool AnswerCall(const ObjectId &objId, const nsTArray<JSParam> &argv,
-                    ReturnStatus *rs, JSVariant *result,
-                    nsTArray<JSParam> *outparams);
+    bool AnswerCallOrConstruct(const ObjectId &objId, const nsTArray<JSParam> &argv,
+                               const bool &construct, ReturnStatus *rs, JSVariant *result,
+                               nsTArray<JSParam> *outparams);
     bool AnswerObjectClassIs(const ObjectId &objId, const uint32_t &classValue,
                              bool *result);
     bool AnswerClassName(const ObjectId &objId, nsString *result);
 
     bool AnswerGetPropertyNames(const ObjectId &objId, const uint32_t &flags,
                                 ReturnStatus *rs, nsTArray<nsString> *names);
     bool AnswerInstanceOf(const ObjectId &objId, const JSIID &iid,
                           ReturnStatus *rs, bool *instanceof);
--- a/js/ipc/WrapperOwner.cpp
+++ b/js/ipc/WrapperOwner.cpp
@@ -49,61 +49,63 @@ int sCPOWProxyHandler;
 
 class CPOWProxyHandler : public BaseProxyHandler
 {
   public:
     CPOWProxyHandler()
       : BaseProxyHandler(&sCPOWProxyHandler) {}
     virtual ~CPOWProxyHandler() {}
 
-    virtual bool finalizeInBackground(Value priv) MOZ_OVERRIDE {
+    virtual bool finalizeInBackground(Value priv) const MOZ_OVERRIDE {
         return false;
     }
 
-    virtual bool preventExtensions(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE;
+    virtual bool preventExtensions(JSContext *cx, HandleObject proxy) const MOZ_OVERRIDE;
     virtual bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id,
-                                       MutableHandle<JSPropertyDescriptor> desc) MOZ_OVERRIDE;
+                                       MutableHandle<JSPropertyDescriptor> desc) const MOZ_OVERRIDE;
     virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id,
-                                          MutableHandle<JSPropertyDescriptor> desc) MOZ_OVERRIDE;
+                                          MutableHandle<JSPropertyDescriptor> desc) const MOZ_OVERRIDE;
     virtual bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id,
-                                MutableHandle<JSPropertyDescriptor> desc) MOZ_OVERRIDE;
+                                MutableHandle<JSPropertyDescriptor> desc) const MOZ_OVERRIDE;
     virtual bool getOwnPropertyNames(JSContext *cx, HandleObject proxy,
-                                     AutoIdVector &props) MOZ_OVERRIDE;
-    virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) MOZ_OVERRIDE;
-    virtual bool enumerate(JSContext *cx, HandleObject proxy, AutoIdVector &props) MOZ_OVERRIDE;
+                                     AutoIdVector &props) const MOZ_OVERRIDE;
+    virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) const MOZ_OVERRIDE;
+    virtual bool enumerate(JSContext *cx, HandleObject proxy, AutoIdVector &props) const MOZ_OVERRIDE;
 
-    virtual bool has(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) MOZ_OVERRIDE;
-    virtual bool hasOwn(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) MOZ_OVERRIDE;
+    virtual bool has(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) const MOZ_OVERRIDE;
+    virtual bool hasOwn(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) const MOZ_OVERRIDE;
     virtual bool get(JSContext *cx, HandleObject proxy, HandleObject receiver,
-                     HandleId id, MutableHandleValue vp) MOZ_OVERRIDE;
+                     HandleId id, MutableHandleValue vp) const MOZ_OVERRIDE;
     virtual bool set(JSContext *cx, JS::HandleObject proxy, JS::HandleObject receiver,
-                     JS::HandleId id, bool strict, JS::MutableHandleValue vp) MOZ_OVERRIDE;
-    virtual bool keys(JSContext *cx, HandleObject proxy, AutoIdVector &props) MOZ_OVERRIDE;
+                     JS::HandleId id, bool strict, JS::MutableHandleValue vp) const MOZ_OVERRIDE;
+    virtual bool keys(JSContext *cx, HandleObject proxy, AutoIdVector &props) const MOZ_OVERRIDE;
 
-    virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) MOZ_OVERRIDE;
-    virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args) MOZ_OVERRIDE;
-    virtual bool objectClassIs(HandleObject obj, js::ESClassValue classValue, JSContext *cx) MOZ_OVERRIDE;
-    virtual const char* className(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE;
-    virtual void finalize(JSFreeOp *fop, JSObject *proxy) MOZ_OVERRIDE;
+    virtual bool isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) const MOZ_OVERRIDE;
+    virtual bool call(JSContext *cx, HandleObject proxy, const CallArgs &args) const MOZ_OVERRIDE;
+    virtual bool construct(JSContext *cx, HandleObject proxy, const CallArgs &args) const MOZ_OVERRIDE;
+    virtual bool objectClassIs(HandleObject obj, js::ESClassValue classValue,
+                               JSContext *cx) const MOZ_OVERRIDE;
+    virtual const char* className(JSContext *cx, HandleObject proxy) const MOZ_OVERRIDE;
+    virtual void finalize(JSFreeOp *fop, JSObject *proxy) const MOZ_OVERRIDE;
 
-    static CPOWProxyHandler singleton;
+    static const CPOWProxyHandler singleton;
 };
 
-CPOWProxyHandler CPOWProxyHandler::singleton;
+const CPOWProxyHandler CPOWProxyHandler::singleton;
 
 #define FORWARD(call, args)                                             \
     WrapperOwner *owner = OwnerOf(proxy);                               \
     if (!owner->active()) {                                             \
         JS_ReportError(cx, "cannot use a CPOW whose process is gone");  \
         return false;                                                   \
     }                                                                   \
     return owner->call args;
 
 bool
-CPOWProxyHandler::preventExtensions(JSContext *cx, HandleObject proxy)
+CPOWProxyHandler::preventExtensions(JSContext *cx, HandleObject proxy) const
 {
     FORWARD(preventExtensions, (cx, proxy));
 }
 
 bool
 WrapperOwner::preventExtensions(JSContext *cx, HandleObject proxy)
 {
     ObjectId objId = idOf(proxy);
@@ -114,17 +116,17 @@ WrapperOwner::preventExtensions(JSContex
 
     LOG_STACK();
 
     return ok(cx, status);
 }
 
 bool
 CPOWProxyHandler::getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id,
-                                        MutableHandle<JSPropertyDescriptor> desc)
+                                        MutableHandle<JSPropertyDescriptor> desc) const
 {
     FORWARD(getPropertyDescriptor, (cx, proxy, id, desc));
 }
 
 bool
 WrapperOwner::getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id,
 				    MutableHandle<JSPropertyDescriptor> desc)
 {
@@ -144,17 +146,17 @@ WrapperOwner::getPropertyDescriptor(JSCo
     if (!ok(cx, status))
         return false;
 
     return toDescriptor(cx, result, desc);
 }
 
 bool
 CPOWProxyHandler::getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id,
-                                           MutableHandle<JSPropertyDescriptor> desc)
+                                           MutableHandle<JSPropertyDescriptor> desc) const
 {
     FORWARD(getOwnPropertyDescriptor, (cx, proxy, id, desc));
 }
 
 bool
 WrapperOwner::getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id,
 				       MutableHandle<JSPropertyDescriptor> desc)
 {
@@ -174,17 +176,17 @@ WrapperOwner::getOwnPropertyDescriptor(J
     if (!ok(cx, status))
         return false;
 
     return toDescriptor(cx, result, desc);
 }
 
 bool
 CPOWProxyHandler::defineProperty(JSContext *cx, HandleObject proxy, HandleId id,
-                                 MutableHandle<JSPropertyDescriptor> desc)
+                                 MutableHandle<JSPropertyDescriptor> desc) const
 {
     FORWARD(defineProperty, (cx, proxy, id, desc));
 }
 
 bool
 WrapperOwner::defineProperty(JSContext *cx, HandleObject proxy, HandleId id,
 			     MutableHandle<JSPropertyDescriptor> desc)
 {
@@ -203,29 +205,30 @@ WrapperOwner::defineProperty(JSContext *
         return ipcfail(cx);
 
     LOG_STACK();
 
     return ok(cx, status);
 }
 
 bool
-CPOWProxyHandler::getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props)
+CPOWProxyHandler::getOwnPropertyNames(JSContext *cx, HandleObject proxy,
+                                      AutoIdVector &props) const
 {
     FORWARD(getOwnPropertyNames, (cx, proxy, props));
 }
 
 bool
 WrapperOwner::getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props)
 {
     return getPropertyNames(cx, proxy, JSITER_OWNONLY | JSITER_HIDDEN, props);
 }
 
 bool
-CPOWProxyHandler::delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp)
+CPOWProxyHandler::delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) const
 {
     FORWARD(delete_, (cx, proxy, id, bp));
 }
 
 bool
 WrapperOwner::delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp)
 {
     ObjectId objId = idOf(proxy);
@@ -239,29 +242,29 @@ WrapperOwner::delete_(JSContext *cx, Han
         return ipcfail(cx);
 
     LOG_STACK();
 
     return ok(cx, status);
 }
 
 bool
-CPOWProxyHandler::enumerate(JSContext *cx, HandleObject proxy, AutoIdVector &props)
+CPOWProxyHandler::enumerate(JSContext *cx, HandleObject proxy, AutoIdVector &props) const
 {
     FORWARD(enumerate, (cx, proxy, props));
 }
 
 bool
 WrapperOwner::enumerate(JSContext *cx, HandleObject proxy, AutoIdVector &props)
 {
     return getPropertyNames(cx, proxy, 0, props);
 }
 
 bool
-CPOWProxyHandler::has(JSContext *cx, HandleObject proxy, HandleId id, bool *bp)
+CPOWProxyHandler::has(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) const
 {
     FORWARD(has, (cx, proxy, id, bp));
 }
 
 bool
 WrapperOwner::has(JSContext *cx, HandleObject proxy, HandleId id, bool *bp)
 {
     ObjectId objId = idOf(proxy);
@@ -275,17 +278,17 @@ WrapperOwner::has(JSContext *cx, HandleO
         return ipcfail(cx);
 
     LOG_STACK();
 
     return ok(cx, status);
 }
 
 bool
-CPOWProxyHandler::hasOwn(JSContext *cx, HandleObject proxy, HandleId id, bool *bp)
+CPOWProxyHandler::hasOwn(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) const
 {
     FORWARD(hasOwn, (cx, proxy, id, bp));
 }
 
 bool
 WrapperOwner::hasOwn(JSContext *cx, HandleObject proxy, HandleId id, bool *bp)
 {
     ObjectId objId = idOf(proxy);
@@ -300,17 +303,17 @@ WrapperOwner::hasOwn(JSContext *cx, Hand
 
     LOG_STACK();
 
     return !!ok(cx, status);
 }
 
 bool
 CPOWProxyHandler::get(JSContext *cx, HandleObject proxy, HandleObject receiver,
-                      HandleId id, MutableHandleValue vp)
+                      HandleId id, MutableHandleValue vp) const
 {
     FORWARD(get, (cx, proxy, receiver, id, vp));
 }
 
 static bool
 CPOWToString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
@@ -329,17 +332,17 @@ CPOWToString(JSContext *cx, unsigned arg
 }
 
 bool
 WrapperOwner::toString(JSContext *cx, HandleObject cpow, JS::CallArgs &args)
 {
     // Ask the other side to call its toString method. Update the callee so that
     // it points to the CPOW and not to the synthesized CPOWToString function.
     args.setCallee(ObjectValue(*cpow));
-    if (!call(cx, cpow, args))
+    if (!callOrConstruct(cx, cpow, args, false))
         return false;
 
     if (!args.rval().isString())
         return true;
 
     RootedString cpowResult(cx, args.rval().toString());
     nsDependentJSString toStringResult;
     if (!toStringResult.init(cx, cpowResult))
@@ -364,25 +367,28 @@ WrapperOwner::toString(JSContext *cx, Ha
     return true;
 }
 
 bool
 WrapperOwner::get(JSContext *cx, HandleObject proxy, HandleObject receiver,
 		  HandleId id, MutableHandleValue vp)
 {
     ObjectId objId = idOf(proxy);
-    ObjectId receiverId = idOf(receiver);
+
+    ObjectVariant receiverVar;
+    if (!toObjectVariant(cx, receiver, &receiverVar))
+        return false;
 
     nsString idstr;
     if (!convertIdToGeckoString(cx, id, &idstr))
         return false;
 
     JSVariant val;
     ReturnStatus status;
-    if (!CallGet(objId, receiverId, idstr, &status, &val))
+    if (!CallGet(objId, receiverVar, idstr, &status, &val))
         return ipcfail(cx);
 
     LOG_STACK();
 
     if (!ok(cx, status))
         return false;
 
     if (!fromVariant(cx, val, vp))
@@ -401,63 +407,66 @@ WrapperOwner::get(JSContext *cx, HandleO
         vp.set(ObjectValue(*toStringObj));
     }
 
     return true;
 }
 
 bool
 CPOWProxyHandler::set(JSContext *cx, JS::HandleObject proxy, JS::HandleObject receiver,
-                      JS::HandleId id, bool strict, JS::MutableHandleValue vp)
+                      JS::HandleId id, bool strict, JS::MutableHandleValue vp) const
 {
     FORWARD(set, (cx, proxy, receiver, id, strict, vp));
 }
 
 bool
 WrapperOwner::set(JSContext *cx, JS::HandleObject proxy, JS::HandleObject receiver,
 		  JS::HandleId id, bool strict, JS::MutableHandleValue vp)
 {
     ObjectId objId = idOf(proxy);
-    ObjectId receiverId = idOf(receiver);
+
+    ObjectVariant receiverVar;
+    if (!toObjectVariant(cx, receiver, &receiverVar))
+        return false;
 
     nsString idstr;
     if (!convertIdToGeckoString(cx, id, &idstr))
         return false;
 
     JSVariant val;
     if (!toVariant(cx, vp, &val))
         return false;
 
     ReturnStatus status;
     JSVariant result;
-    if (!CallSet(objId, receiverId, idstr, strict, val, &status, &result))
+    if (!CallSet(objId, receiverVar, idstr, strict, val, &status, &result))
         return ipcfail(cx);
 
     LOG_STACK();
 
     if (!ok(cx, status))
         return false;
 
     return fromVariant(cx, result, vp);
 }
 
 bool
-CPOWProxyHandler::keys(JSContext *cx, HandleObject proxy, AutoIdVector &props)
+CPOWProxyHandler::keys(JSContext *cx, HandleObject proxy, AutoIdVector &props) const
 {
     FORWARD(keys, (cx, proxy, props));
 }
 
 bool
 WrapperOwner::keys(JSContext *cx, HandleObject proxy, AutoIdVector &props)
 {
     return getPropertyNames(cx, proxy, JSITER_OWNONLY, props);
 }
 
 bool
-CPOWProxyHandler::isExtensible(JSContext *cx, HandleObject proxy, bool *extensible)
+CPOWProxyHandler::isExtensible(JSContext *cx, HandleObject proxy, bool *extensible) const
 {
     FORWARD(isExtensible, (cx, proxy, extensible));
 }
 
 bool
 WrapperOwner::isExtensible(JSContext *cx, HandleObject proxy, bool *extensible)
 {
     ObjectId objId = idOf(proxy);
@@ -467,32 +476,44 @@ WrapperOwner::isExtensible(JSContext *cx
         return ipcfail(cx);
 
     LOG_STACK();
 
     return ok(cx, status);
 }
 
 bool
-CPOWProxyHandler::call(JSContext *cx, HandleObject proxy, const CallArgs &args)
+CPOWProxyHandler::call(JSContext *cx, HandleObject proxy, const CallArgs &args) const
 {
-    FORWARD(call, (cx, proxy, args));
+    FORWARD(callOrConstruct, (cx, proxy, args, false));
 }
 
 bool
-WrapperOwner::call(JSContext *cx, HandleObject proxy, const CallArgs &args)
+CPOWProxyHandler::construct(JSContext *cx, HandleObject proxy, const CallArgs &args) const
+{
+    FORWARD(callOrConstruct, (cx, proxy, args, true));
+}
+
+bool
+WrapperOwner::callOrConstruct(JSContext *cx, HandleObject proxy, const CallArgs &args,
+                              bool construct)
 {
     ObjectId objId = idOf(proxy);
 
     InfallibleTArray<JSParam> vals;
     AutoValueVector outobjects(cx);
 
     RootedValue v(cx);
     for (size_t i = 0; i < args.length() + 2; i++) {
-        v = args.base()[i];
+        // The |this| value for constructors is a magic value that we won't be
+        // able to convert, so skip it.
+        if (i == 1 && construct)
+            v = UndefinedValue();
+        else
+            v = args.base()[i];
         if (v.isObject()) {
             RootedObject obj(cx, &v.toObject());
             if (xpc::IsOutObject(cx, obj)) {
                 // Make sure it is not an in-out object.
                 bool found;
                 if (!JS_HasProperty(cx, obj, "value", &found))
                     return false;
                 if (found) {
@@ -510,17 +531,17 @@ WrapperOwner::call(JSContext *cx, Handle
         if (!toVariant(cx, v, &val))
             return false;
         vals.AppendElement(JSParam(val));
     }
 
     JSVariant result;
     ReturnStatus status;
     InfallibleTArray<JSParam> outparams;
-    if (!CallCall(objId, vals, &status, &result, &outparams))
+    if (!CallCallOrConstruct(objId, vals, construct, &status, &result, &outparams))
         return ipcfail(cx);
 
     LOG_STACK();
 
     if (!ok(cx, status))
         return false;
 
     if (outparams.Length() != outobjects.length())
@@ -545,17 +566,17 @@ WrapperOwner::call(JSContext *cx, Handle
     if (!fromVariant(cx, result, args.rval()))
         return false;
 
     return true;
 }
 
 
 bool
-CPOWProxyHandler::objectClassIs(HandleObject proxy, js::ESClassValue classValue, JSContext *cx)
+CPOWProxyHandler::objectClassIs(HandleObject proxy, js::ESClassValue classValue, JSContext *cx) const
 {
     FORWARD(objectClassIs, (cx, proxy, classValue));
 }
 
 bool
 WrapperOwner::objectClassIs(JSContext *cx, HandleObject proxy, js::ESClassValue classValue)
 {
     ObjectId objId = idOf(proxy);
@@ -567,17 +588,17 @@ WrapperOwner::objectClassIs(JSContext *c
         return false;
 
     LOG_STACK();
 
     return result;
 }
 
 const char *
-CPOWProxyHandler::className(JSContext *cx, HandleObject proxy)
+CPOWProxyHandler::className(JSContext *cx, HandleObject proxy) const
 {
     WrapperOwner *parent = OwnerOf(proxy);
     if (!parent->active())
         return "<dead CPOW>";
     return parent->className(cx, proxy);
 }
 
 const char *
@@ -590,17 +611,17 @@ WrapperOwner::className(JSContext *cx, H
         return "<error>";
 
     LOG_STACK();
 
     return ToNewCString(name);
 }
 
 void
-CPOWProxyHandler::finalize(JSFreeOp *fop, JSObject *proxy)
+CPOWProxyHandler::finalize(JSFreeOp *fop, JSObject *proxy) const
 {
     OwnerOf(proxy)->drop(proxy);
 }
 
 void
 WrapperOwner::drop(JSObject *obj)
 {
     ObjectId objId = idOf(obj);
--- a/js/ipc/WrapperOwner.h
+++ b/js/ipc/WrapperOwner.h
@@ -50,17 +50,18 @@ class WrapperOwner : public virtual Java
              JS::HandleId id, JS::MutableHandleValue vp);
     bool set(JSContext *cx, JS::HandleObject proxy, JS::HandleObject receiver,
              JS::HandleId id, bool strict, JS::MutableHandleValue vp);
     bool keys(JSContext *cx, JS::HandleObject proxy, JS::AutoIdVector &props);
     // We use "iterate" provided by the base class here.
 
     // SpiderMonkey Extensions.
     bool isExtensible(JSContext *cx, JS::HandleObject proxy, bool *extensible);
-    bool call(JSContext *cx, JS::HandleObject proxy, const JS::CallArgs &args);
+    bool callOrConstruct(JSContext *cx, JS::HandleObject proxy, const JS::CallArgs &args,
+                         bool construct);
     bool objectClassIs(JSContext *cx, JS::HandleObject obj, js::ESClassValue classValue);
     const char* className(JSContext *cx, JS::HandleObject proxy);
 
     nsresult instanceOf(JSObject *obj, const nsID *id, bool *bp);
 
     bool toString(JSContext *cx, JS::HandleObject callee, JS::CallArgs &args);
 
     /*
@@ -111,28 +112,28 @@ class WrapperOwner : public virtual Java
                                     ReturnStatus *rs) = 0;
     virtual bool CallDelete(const ObjectId &objId, const nsString &id,
                             ReturnStatus *rs, bool *success) = 0;
 
     virtual bool CallHas(const ObjectId &objId, const nsString &id,
                          ReturnStatus *rs, bool *bp) = 0;
     virtual bool CallHasOwn(const ObjectId &objId, const nsString &id,
                             ReturnStatus *rs, bool *bp) = 0;
-    virtual bool CallGet(const ObjectId &objId, const ObjectId &receiverId,
+    virtual bool CallGet(const ObjectId &objId, const ObjectVariant &receiverVar,
                          const nsString &id,
                          ReturnStatus *rs, JSVariant *result) = 0;
-    virtual bool CallSet(const ObjectId &objId, const ObjectId &receiverId,
+    virtual bool CallSet(const ObjectId &objId, const ObjectVariant &receiverVar,
                          const nsString &id, const bool &strict,
                          const JSVariant &value, ReturnStatus *rs, JSVariant *result) = 0;
 
     virtual bool CallIsExtensible(const ObjectId &objId, ReturnStatus *rs,
                                   bool *result) = 0;
-    virtual bool CallCall(const ObjectId &objId, const nsTArray<JSParam> &argv,
-                          ReturnStatus *rs, JSVariant *result,
-                          nsTArray<JSParam> *outparams) = 0;
+    virtual bool CallCallOrConstruct(const ObjectId &objId, const nsTArray<JSParam> &argv,
+                                     const bool &construct, ReturnStatus *rs, JSVariant *result,
+                                     nsTArray<JSParam> *outparams) = 0;
     virtual bool CallObjectClassIs(const ObjectId &objId, const uint32_t &classValue,
                                    bool *result) = 0;
     virtual bool CallClassName(const ObjectId &objId, nsString *result) = 0;
 
     virtual bool CallGetPropertyNames(const ObjectId &objId, const uint32_t &flags,
                                       ReturnStatus *rs, nsTArray<nsString> *names) = 0;
     virtual bool CallInstanceOf(const ObjectId &objId, const JSIID &iid,
                                 ReturnStatus *rs, bool *instanceof) = 0;
deleted file mode 100644
--- a/js/src/assembler/TestMain.cpp
+++ /dev/null
@@ -1,933 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-
-// A short test program with which to experiment with the assembler.
-
-//satisfies  CPU(X86_64)
-//#define WTF_CPU_X86_64
-
-// satisfies  ENABLE(ASSEMBLER)
-#define ENABLE_ASSEMBLER 1
-
-// satisfies  ENABLE(JIT)
-#define ENABLE_JIT 1
-
-#define USE_SYSTEM_MALLOC 1
-// leads to FORCE_SYSTEM_MALLOC in wtf/FastMalloc.cpp
-
-#include "assembler/jit/ExecutableAllocator.h"
-#include "assembler/assembler/LinkBuffer.h"
-#include "assembler/assembler/CodeLocation.h"
-#include "assembler/assembler/RepatchBuffer.h"
-
-#include "assembler/assembler/MacroAssembler.h"
-
-#include <stdio.h>
-
-/////////////////////////////////////////////////////////////////
-// Temporary scaffolding for selecting the arch
-#undef ARCH_x86
-#undef ARCH_amd64
-#undef ARCH_arm
-
-#if defined(__APPLE__) && defined(__i386__)
-#  define ARCH_x86 1
-#elif defined(__APPLE__) && defined(__x86_64__)
-#  define ARCH_amd64 1
-#elif defined(__linux__) && defined(__i386__)
-#  define ARCH_x86 1
-#elif defined(__linux__) && defined(__x86_64__)
-#  define ARCH_amd64 1
-#elif defined(__linux__) && defined(__arm__)
-#  define ARCH_arm 1
-#elif defined(_MSC_VER) && defined(_M_IX86)
-#  define ARCH_x86 1
-#endif
-/////////////////////////////////////////////////////////////////
-
-// just somewhere convenient to put a breakpoint, before
-// running gdb
-#if WTF_COMPILER_GCC
-__attribute__((noinline))
-#endif
-void pre_run ( void ) { }
-
-/////////////////////////////////////////////////////////////////
-//// test1 (simple straight line code)
-#if WTF_COMPILER_GCC
-
-void test1 ( void )
-{
-  printf("\n------------ Test 1 (straight line code) ------------\n\n" );
-
-  // Create new assembler
-  JSC::MacroAssembler* am = new JSC::MacroAssembler();
-
-#if defined(ARCH_amd64)
-  JSC::X86Registers::RegisterID areg = JSC::X86Registers::r15;
-  // dump some instructions into it
-  //    xor    %r15,%r15
-  //    add    $0x7b,%r15
-  //    add    $0x141,%r15
-  //    retq
-  am->xorPtr(areg,areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(123), areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(321), areg);
-  am->ret();
-#endif
-
-#if defined(ARCH_x86)
-  JSC::X86Registers::RegisterID areg = JSC::X86Registers::edi;
-  // dump some instructions into it
-  //    xor    %edi,%edi
-  //    add    $0x7b,%edi
-  //    add    $0x141,%edi
-  //    ret
-  am->xorPtr(areg,areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(123), areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(321), areg);
-  am->ret();
-#endif
-
-#if defined(ARCH_arm)
-  JSC::ARMRegisters::RegisterID areg = JSC::ARMRegisters::r8;
-  //    eors    r8, r8, r8
-  //    adds    r8, r8, #123    ; 0x7b
-  //    mov     r3, #256        ; 0x100
-  //    orr     r3, r3, #65     ; 0x41
-  //    adds    r8, r8, r3
-  //    mov     pc, lr
-  am->xorPtr(areg,areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(123), areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(321), areg);
-  am->ret();
-#endif
-
-  // prepare a link buffer, into which we can copy the completed insns
-  JSC::ExecutableAllocator* eal = new JSC::ExecutableAllocator();
-
-  // intermediate step .. get the pool suited for the size of code in 'am'
-  //WTF::PassRefPtr<JSC::ExecutablePool> ep = eal->poolForSize( am->size() );
-  JSC::ExecutablePool* ep = eal->poolForSize( am->size() );
-
-  // constructor for LinkBuffer asks ep to allocate r-x memory,
-  // then copies it there.
-  JSC::LinkBuffer patchBuffer(am, ep, JSC::METHOD_CODE);
-
-  // finalize
-  JSC::MacroAssemblerCodeRef cr = patchBuffer.finalizeCode();
-
-  // cr now holds a pointer to the final runnable code.
-  void* entry = cr.m_code.executableAddress();
-
-  printf("disas %p %p\n",
-         entry, (char*)entry + cr.m_size);
-  pre_run();
-
-  unsigned long result = 0x55555555;
-
-#if defined(ARCH_amd64)
-  // call the generated piece of code.  It puts its result in r15.
-  __asm__ __volatile__(
-     "callq *%1"           "\n\t"
-     "movq  %%r15, %0"     "\n"
-     :/*out*/   "=r"(result)
-     :/*in*/    "r"(entry)
-     :/*trash*/ "r15","cc"
-  );
-#endif
-#if defined(ARCH_x86)
-  // call the generated piece of code.  It puts its result in edi.
-  __asm__ __volatile__(
-     "calll *%1"           "\n\t"
-     "movl  %%edi, %0"     "\n"
-     :/*out*/   "=r"(result)
-     :/*in*/    "r"(entry)
-     :/*trash*/ "edi","cc"
-  );
-#endif
-#if defined(ARCH_arm)
-  // call the generated piece of code.  It puts its result in r8.
-  __asm__ __volatile__(
-     "blx   %1"            "\n\t"
-     "mov   %0, %%r8"      "\n"
-     :/*out*/   "=r"(result)
-     :/*in*/    "r"(entry)
-     :/*trash*/ "r8","cc"
-  );
-#endif
-
-  printf("\n");
-  printf("value computed is %lu (expected 444)\n", result);
-  printf("\n");
-
-  delete eal;
-  delete am;
-}
-
-#endif /* WTF_COMPILER_GCC */
-
-/////////////////////////////////////////////////////////////////
-//// test2 (a simple counting-down loop)
-#if WTF_COMPILER_GCC
-
-void test2 ( void )
-{
-  printf("\n------------ Test 2 (mini loop) ------------\n\n" );
-
-  // Create new assembler
-  JSC::MacroAssembler* am = new JSC::MacroAssembler();
-
-#if defined(ARCH_amd64)
-  JSC::X86Registers::RegisterID areg = JSC::X86Registers::r15;
-  //    xor    %r15,%r15
-  //    add    $0x7b,%r15
-  //    add    $0x141,%r15
-  //    sub    $0x1,%r15
-  //    mov    $0x0,%r11
-  //    cmp    %r11,%r15
-  //    jne    0x7ff6d3e6a00e
-  //    retq
-  // so r15 always winds up being zero
-  am->xorPtr(areg,areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(123), areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(321), areg);
-
-  JSC::MacroAssembler::Label loopHeadLabel(am);
-  am->subPtr(JSC::MacroAssembler::Imm32(1), areg);
-
-  JSC::MacroAssembler::Jump j
-     = am->branchPtr(JSC::MacroAssembler::NotEqual,
-                     areg, JSC::MacroAssembler::ImmPtr(0));
-  j.linkTo(loopHeadLabel, am);
-
-  am->ret();
-#endif
-
-#if defined(ARCH_x86)
-  JSC::X86Registers::RegisterID areg = JSC::X86Registers::edi;
-  //    xor    %edi,%edi
-  //    add    $0x7b,%edi
-  //    add    $0x141,%edi
-  //    sub    $0x1,%edi
-  //    test   %edi,%edi
-  //    jne    0xf7f9700b
-  //    ret
-  // so edi always winds up being zero
-  am->xorPtr(areg,areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(123), areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(321), areg);
-
-  JSC::MacroAssembler::Label loopHeadLabel(am);
-  am->subPtr(JSC::MacroAssembler::Imm32(1), areg);
-
-  JSC::MacroAssembler::Jump j
-     = am->branchPtr(JSC::MacroAssembler::NotEqual,
-                     areg, JSC::MacroAssembler::ImmPtr(0));
-  j.linkTo(loopHeadLabel, am);
-
-  am->ret();
-#endif
-
-#if defined(ARCH_arm)
-  JSC::ARMRegisters::RegisterID areg = JSC::ARMRegisters::r8;
-  //    eors    r8, r8, r8
-  //    adds    r8, r8, #123    ; 0x7b
-  //    mov     r3, #256        ; 0x100
-  //    orr     r3, r3, #65     ; 0x41
-  //    adds    r8, r8, r3
-  //    subs    r8, r8, #1      ; 0x1
-  //    ldr     r3, [pc, #8]    ; 0x40026028
-  //    cmp     r8, r3
-  //    bne     0x40026014
-  //    mov     pc, lr
-  //    andeq   r0, r0, r0         // DATA (0)
-  //    andeq   r0, r0, r4, lsl r0 // DATA (?? what's this for?)
-  // so r8 always winds up being zero
-  am->xorPtr(areg,areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(123), areg);
-  am->addPtr(JSC::MacroAssembler::Imm32(321), areg);
-
-  JSC::MacroAssembler::Label loopHeadLabel(am);
-  am->subPtr(JSC::MacroAssembler::Imm32(1), areg);
-
-  JSC::MacroAssembler::Jump j
-     = am->branchPtr(JSC::MacroAssembler::NotEqual,
-                     areg, JSC::MacroAssembler::ImmPtr(0));
-  j.linkTo(loopHeadLabel, am);
-
-  am->ret();
-#endif
-
-  // prepare a link buffer, into which we can copy the completed insns
-  JSC::ExecutableAllocator* eal = new JSC::ExecutableAllocator();
-
-  // intermediate step .. get the pool suited for the size of code in 'am'
-  //WTF::PassRefPtr<JSC::ExecutablePool> ep = eal->poolForSize( am->size() );
-  JSC::ExecutablePool* ep = eal->poolForSize( am->size() );
-
-  // constructor for LinkBuffer asks ep to allocate r-x memory,
-  // then copies it there.
-  JSC::LinkBuffer patchBuffer(am, ep, JSC::METHOD_CODE);
-
-  // finalize
-  JSC::MacroAssemblerCodeRef cr = patchBuffer.finalizeCode();
-
-  // cr now holds a pointer to the final runnable code.
-  void* entry = cr.m_code.executableAddress();
-
-  printf("disas %p %p\n",
-         entry, (char*)entry + cr.m_size);
-  pre_run();
-
-  unsigned long result = 0x55555555;
-
-#if defined(ARCH_amd64)
-  // call the generated piece of code.  It puts its result in r15.
-  __asm__ __volatile__(
-     "callq *%1"           "\n\t"
-     "movq  %%r15, %0"     "\n"
-     :/*out*/   "=r"(result)
-     :/*in*/    "r"(entry)
-     :/*trash*/ "r15","cc"
-  );
-#endif
-#if defined(ARCH_x86)
-  // call the generated piece of code.  It puts its result in edi.
-  __asm__ __volatile__(
-     "calll *%1"           "\n\t"
-     "movl  %%edi, %0"     "\n"
-     :/*out*/   "=r"(result)
-     :/*in*/    "r"(entry)
-     :/*trash*/ "edi","cc"
-  );
-#endif
-#if defined(ARCH_arm)
-  // call the generated piece of code.  It puts its result in r8.
-  __asm__ __volatile__(
-     "blx   %1"            "\n\t"
-     "mov   %0, %%r8"      "\n"
-     :/*out*/   "=r"(result)
-     :/*in*/    "r"(entry)
-     :/*trash*/ "r8","cc"
-  );
-#endif
-
-  printf("\n");
-  printf("value computed is %lu (expected 0)\n", result);
-  printf("\n");
-
-  delete eal;
-  delete am;
-}
-
-#endif /* WTF_COMPILER_GCC */
-
-/////////////////////////////////////////////////////////////////
-//// test3 (if-then-else)
-#if WTF_COMPILER_GCC
-
-void test3 ( void )
-{
-  printf("\n------------ Test 3 (if-then-else) ------------\n\n" );
-
-  // Create new assembler
-  JSC::MacroAssembler* am = new JSC::MacroAssembler();
-
-#if defined(ARCH_amd64)
-  JSC::X86Registers::RegisterID areg = JSC::X86Registers::r15;
-  //    mov    $0x64,%r15d
-  //    mov    $0x0,%r11
-  //    cmp    %r11,%r15
-  //    jne    0x7ff6d3e6a024
-  //    mov    $0x40,%r15d
-  //    jmpq   0x7ff6d3e6a02a
-  //    mov    $0x4,%r15d
-  //    retq
-  // so r15 ends up being 4
-
-  // put a value in reg
-  am->move(JSC::MacroAssembler::Imm32(100), areg);
-
-  // test, and conditionally jump to 'else' branch
-  JSC::MacroAssembler::Jump jToElse
-    = am->branchPtr(JSC::MacroAssembler::NotEqual,
-                    areg, JSC::MacroAssembler::ImmPtr(0));
-
-  // 'then' branch
-  am->move(JSC::MacroAssembler::Imm32(64), areg);
-  JSC::MacroAssembler::Jump jToAfter
-    = am->jump();
-
-  // 'else' branch
-  JSC::MacroAssembler::Label elseLbl(am);
-  am->move(JSC::MacroAssembler::Imm32(4), areg);
-
-  // after
-  JSC::MacroAssembler::Label afterLbl(am);
-
-  am->ret();
-#endif
-
-#if defined(ARCH_x86)
-  JSC::X86Registers::RegisterID areg = JSC::X86Registers::edi;
-  //    mov    $0x64,%edi
-  //    test   %edi,%edi
-  //    jne    0xf7f22017
-  //    mov    $0x40,%edi
-  //    jmp    0xf7f2201c
-  //    mov    $0x4,%edi
-  //    ret
-  // so edi ends up being 4
-
-  // put a value in reg
-  am->move(JSC::MacroAssembler::Imm32(100), areg);
-
-  // test, and conditionally jump to 'else' branch
-  JSC::MacroAssembler::Jump jToElse
-    = am->branchPtr(JSC::MacroAssembler::NotEqual,
-                    areg, JSC::MacroAssembler::ImmPtr(0));
-
-  // 'then' branch
-  am->move(JSC::MacroAssembler::Imm32(64), areg);
-  JSC::MacroAssembler::Jump jToAfter
-    = am->jump();
-
-  // 'else' branch
-  JSC::MacroAssembler::Label elseLbl(am);
-  am->move(JSC::MacroAssembler::Imm32(4), areg);
-
-  // after
-  JSC::MacroAssembler::Label afterLbl(am);
-
-  am->ret();
-#endif
-
-#if defined(ARCH_arm)
-  JSC::ARMRegisters::RegisterID areg = JSC::ARMRegisters::r8;
-  //    mov     r8, #100        ; 0x64
-  //    ldr     r3, [pc, #20]   ; 0x40026020
-  //    cmp     r8, r3
-  //    bne     0x40026018
-  //    mov     r8, #64 ; 0x40
-  //    b       0x4002601c
-  //    mov     r8, #4  ; 0x4
-  //    mov     pc, lr
-  //    andeq   r0, r0, r0           // DATA
-  //    andeq   r0, r0, r8, lsl r0   // DATA
-  //    andeq   r0, r0, r12, lsl r0  // DATA
-  //    ldr     r3, [r3, -r3]        // DATA
-  // so r8 ends up being 4
-
-  // put a value in reg
-  am->move(JSC::MacroAssembler::Imm32(100), areg);
-
-  // test, and conditionally jump to 'else' branch
-  JSC::MacroAssembler::Jump jToElse
-    = am->branchPtr(JSC::MacroAssembler::NotEqual,
-                    areg, JSC::MacroAssembler::ImmPtr(0));
-
-  // 'then' branch
-  am->move(JSC::MacroAssembler::Imm32(64), areg);
-  JSC::MacroAssembler::Jump jToAfter
-    = am->jump();
-
-  // 'else' branch
-  JSC::MacroAssembler::Label elseLbl(am);
-  am->move(JSC::MacroAssembler::Imm32(4), areg);
-
-  // after
-  JSC::MacroAssembler::Label afterLbl(am);
-
-  am->ret();
-#endif
-
-  // set branch targets appropriately
-  jToElse.linkTo(elseLbl, am);
-  jToAfter.linkTo(afterLbl, am);
-
-  // prepare a link buffer, into which we can copy the completed insns
-  JSC::ExecutableAllocator* eal = new JSC::ExecutableAllocator();
-
-  // intermediate step .. get the pool suited for the size of code in 'am'
-  //WTF::PassRefPtr<JSC::ExecutablePool> ep = eal->poolForSize( am->size() );
-  JSC::ExecutablePool* ep = eal->poolForSize( am->size() );
-
-  // constructor for LinkBuffer asks ep to allocate r-x memory,
-  // then copies it there.
-  JSC::LinkBuffer patchBuffer(am, ep, JSC::METHOD_CODE);
-
-  // finalize
-  JSC::MacroAssemblerCodeRef cr = patchBuffer.finalizeCode();
-
-  // cr now holds a pointer to the final runnable code.
-  void* entry = cr.m_code.executableAddress();
-
-  printf("disas %p %p\n",
-         entry, (char*)entry + cr.m_size);
-  pre_run();
-
-  unsigned long result = 0x55555555;
-
-#if defined(ARCH_amd64)
-  // call the generated piece of code.  It puts its result in r15.
-  __asm__ __volatile__(
-     "callq *%1"           "\n\t"
-     "movq  %%r15, %0"     "\n"
-     :/*out*/   "=r"(result)
-     :/*in*/    "r"(entry)
-     :/*trash*/ "r15","cc"
-  );
-#endif
-#if defined(ARCH_x86)
-  // call the generated piece of code.  It puts its result in edi.
-  __asm__ __volatile__(
-     "calll *%1"           "\n\t"
-     "movl  %%edi, %0"     "\n"
-     :/*out*/   "=r"(result)
-     :/*in*/    "r"(entry)
-     :/*trash*/ "edi","cc"
-  );
-#endif
-#if defined(ARCH_arm)
-  // call the generated piece of code.  It puts its result in r8.
-  __asm__ __volatile__(
-     "blx   %1"            "\n\t"
-     "mov   %0, %%r8"      "\n"
-     :/*out*/   "=r"(result)
-     :/*in*/    "r"(entry)
-     :/*trash*/ "r8","cc"
-  );
-#endif
-
-  printf("\n");
-  printf("value computed is %lu (expected 4)\n", result);
-  printf("\n");
-
-  delete eal;
-  delete am;
-}
-
-#endif /* WTF_COMPILER_GCC */
-
-/////////////////////////////////////////////////////////////////
-//// test4 (callable function)
-
-void test4 ( void )
-{
-  printf("\n------------ Test 4 (callable fn) ------------\n\n" );
-
-  // Create new assembler
-  JSC::MacroAssembler* am = new JSC::MacroAssembler();
-
-#if defined(ARCH_amd64)
-  // ADD FN PROLOGUE/EPILOGUE so as to make a mini-function
-  //    push   %rbp
-  //    mov    %rsp,%rbp
-  //    push   %rbx
-  //    push   %r12
-  //    push   %r13
-  //    push   %r14
-  //    push   %r15
-  //    xor    %rax,%rax
-  //    add    $0x7b,%rax
-  //    add    $0x141,%rax
-  //    pop    %r15
-  //    pop    %r14
-  //    pop    %r13
-  //    pop    %r12
-  //    pop    %rbx
-  //    mov    %rbp,%rsp
-  //    pop    %rbp
-  //    retq
-  // callable as a normal function, returns 444
-
-  JSC::X86Registers::RegisterID rreg = JSC::X86Registers::eax;
-  am->push(JSC::X86Registers::ebp);
-  am->move(JSC::X86Registers::esp, JSC::X86Registers::ebp);
-  am->push(JSC::X86Registers::ebx);
-  am->push(JSC::X86Registers::r12);
-  am->push(JSC::X86Registers::r13);
-  am->push(JSC::X86Registers::r14);
-  am->push(JSC::X86Registers::r15);
-
-  am->xorPtr(rreg,rreg);
-  am->addPtr(JSC::MacroAssembler::Imm32(123), rreg);
-  am->addPtr(JSC::MacroAssembler::Imm32(321), rreg);
-
-  am->pop(JSC::X86Registers::r15);
-  am->pop(JSC::X86Registers::r14);
-  am->pop(JSC::X86Registers::r13);
-  am->pop(JSC::X86Registers::r12);
-  am->pop(JSC::X86Registers::ebx);
-  am->move(JSC::X86Registers::ebp, JSC::X86Registers::esp);
-  am->pop(JSC::X86Registers::ebp);
-  am->ret();
-#endif
-
-#if defined(ARCH_x86)
-  // ADD FN PROLOGUE/EPILOGUE so as to make a mini-function
-  //    push   %ebp
-  //    mov    %esp,%ebp
-  //    push   %ebx
-  //    push   %esi
-  //    push   %edi
-  //    xor    %eax,%eax
-  //    add    $0x7b,%eax
-  //    add    $0x141,%eax
-  //    pop    %edi
-  //    pop    %esi
-  //    pop    %ebx
-  //    mov    %ebp,%esp
-  //    pop    %ebp
-  //    ret
-  // callable as a normal function, returns 444
-
-  JSC::X86Registers::RegisterID rreg = JSC::X86Registers::eax;
-
-  am->push(JSC::X86Registers::ebp);
-  am->move(JSC::X86Registers::esp, JSC::X86Registers::ebp);
-  am->push(JSC::X86Registers::ebx);
-  am->push(JSC::X86Registers::esi);
-  am->push(JSC::X86Registers::edi);
-
-  am->xorPtr(rreg,rreg);
-  am->addPtr(JSC::MacroAssembler::Imm32(123), rreg);
-  am->addPtr(JSC::MacroAssembler::Imm32(321), rreg);
-
-  am->pop(JSC::X86Registers::edi);
-  am->pop(JSC::X86Registers::esi);
-  am->pop(JSC::X86Registers::ebx);
-  am->move(JSC::X86Registers::ebp, JSC::X86Registers::esp);
-  am->pop(JSC::X86Registers::ebp);
-  am->ret();
-#endif
-
-#if defined(ARCH_arm)
-  // ADD FN PROLOGUE/EPILOGUE so as to make a mini-function
-  //    push    {r4}            ; (str r4, [sp, #-4]!)
-  //    push    {r5}            ; (str r5, [sp, #-4]!)
-  //    push    {r6}            ; (str r6, [sp, #-4]!)
-  //    push    {r7}            ; (str r7, [sp, #-4]!)
-  //    push    {r8}            ; (str r8, [sp, #-4]!)
-  //    push    {r9}            ; (str r9, [sp, #-4]!)
-  //    push    {r10}           ; (str r10, [sp, #-4]!)
-  //    push    {r11}           ; (str r11, [sp, #-4]!)
-  //    eors    r0, r0, r0
-  //    adds    r0, r0, #123    ; 0x7b
-  //    mov     r3, #256        ; 0x100
-  //    orr     r3, r3, #65     ; 0x41
-  //    adds    r0, r0, r3
-  //    pop     {r11}           ; (ldr r11, [sp], #4)
-  //    pop     {r10}           ; (ldr r10, [sp], #4)
-  //    pop     {r9}            ; (ldr r9, [sp], #4)
-  //    pop     {r8}            ; (ldr r8, [sp], #4)
-  //    pop     {r7}            ; (ldr r7, [sp], #4)
-  //    pop     {r6}            ; (ldr r6, [sp], #4)
-  //    pop     {r5}            ; (ldr r5, [sp], #4)
-  //    pop     {r4}            ; (ldr r4, [sp], #4)
-  //    mov     pc, lr
-  // callable as a normal function, returns 444
-
-  JSC::ARMRegisters::RegisterID rreg = JSC::ARMRegisters::r0;
-
-  am->push(JSC::ARMRegisters::r4);
-  am->push(JSC::ARMRegisters::r5);
-  am->push(JSC::ARMRegisters::r6);
-  am->push(JSC::ARMRegisters::r7);
-  am->push(JSC::ARMRegisters::r8);
-  am->push(JSC::ARMRegisters::r9);
-  am->push(JSC::ARMRegisters::r10);
-  am->push(JSC::ARMRegisters::r11);
-
-  am->xorPtr(rreg,rreg);
-  am->addPtr(JSC::MacroAssembler::Imm32(123), rreg);
-  am->addPtr(JSC::MacroAssembler::Imm32(321), rreg);
-
-  am->pop(JSC::ARMRegisters::r11);
-  am->pop(JSC::ARMRegisters::r10);
-  am->pop(JSC::ARMRegisters::r9);
-  am->pop(JSC::ARMRegisters::r8);
-  am->pop(JSC::ARMRegisters::r7);
-  am->pop(JSC::ARMRegisters::r6);
-  am->pop(JSC::ARMRegisters::r5);
-  am->pop(JSC::ARMRegisters::r4);
-
-  am->ret();
-#endif
-
-  // prepare a link buffer, into which we can copy the completed insns
-  JSC::ExecutableAllocator* eal = new JSC::ExecutableAllocator();
-
-  // intermediate step .. get the pool suited for the size of code in 'am'
-  //WTF::PassRefPtr<JSC::ExecutablePool> ep = eal->poolForSize( am->size() );
-  JSC::ExecutablePool* ep = eal->poolForSize( am->size() );
-
-  // constructor for LinkBuffer asks ep to allocate r-x memory,
-  // then copies it there.
-  JSC::LinkBuffer patchBuffer(am, ep, JSC::METHOD_CODE);
-
-  // now fix up any branches/calls
-  //JSC::FunctionPtr target = JSC::FunctionPtr::FunctionPtr( &cube );
-
-  // finalize
-  JSC::MacroAssemblerCodeRef cr = patchBuffer.finalizeCode();
-
-  // cr now holds a pointer to the final runnable code.
-  void* entry = cr.m_code.executableAddress();
-
-  printf("disas %p %p\n",
-         entry, (char*)entry + cr.m_size);
-  pre_run();
-
-  // call the function
-  unsigned long (*fn)(void) = (unsigned long (*)())entry;
-  unsigned long result = fn();
-
-  printf("\n");
-  printf("value computed is %lu (expected 444)\n", result);
-  printf("\n");
-
-  delete eal;
-  delete am;
-}
-
-
-/////////////////////////////////////////////////////////////////
-//// test5 (call in, out, repatch)
-
-// a function which we will call from the JIT generated code
-unsigned long cube   ( unsigned long x ) { return x * x * x; }
-unsigned long square ( unsigned long x ) { return x * x; }
-
-void test5 ( void )
-{
-  printf("\n--------- Test 5 (call in, out, repatch) ---------\n\n" );
-
-  // Create new assembler
-  JSC::MacroAssembler* am = new JSC::MacroAssembler();
-  JSC::MacroAssembler::Call cl;
-  ptrdiff_t offset_of_call_insn;
-
-#if defined(ARCH_amd64)
-  // ADD FN PROLOGUE/EPILOGUE so as to make a mini-function
-  // and then call a non-JIT-generated helper from within
-  // this code
-  //    push   %rbp
-  //    mov    %rsp,%rbp
-  //    push   %rbx
-  //    push   %r12
-  //    push   %r13
-  //    push   %r14
-  //    push   %r15
-  //    mov    $0x9,%edi
-  //    mov    $0x40187e,%r11
-  //    callq  *%r11
-  //    pop    %r15
-  //    pop    %r14
-  //    pop    %r13
-  //    pop    %r12
-  //    pop    %rbx
-  //    mov    %rbp,%rsp
-  //    pop    %rbp
-  //    retq
-  JSC::MacroAssembler::Label startOfFnLbl(am);
-  am->push(JSC::X86Registers::ebp);
-  am->move(JSC::X86Registers::esp, JSC::X86Registers::ebp);
-  am->push(JSC::X86Registers::ebx);
-  am->push(JSC::X86Registers::r12);
-  am->push(JSC::X86Registers::r13);
-  am->push(JSC::X86Registers::r14);
-  am->push(JSC::X86Registers::r15);
-
-  // let's compute cube(9).  Move $9 to the first arg reg.
-  am->move(JSC::MacroAssembler::Imm32(9), JSC::X86Registers::edi);
-  cl = am->JSC::MacroAssembler::call();
-
-  // result is now in %rax.  Leave it ther and just return.
-
-  am->pop(JSC::X86Registers::r15);
-  am->pop(JSC::X86Registers::r14);
-  am->pop(JSC::X86Registers::r13);
-  am->pop(JSC::X86Registers::r12);
-  am->pop(JSC::X86Registers::ebx);
-  am->move(JSC::X86Registers::ebp, JSC::X86Registers::esp);
-  am->pop(JSC::X86Registers::ebp);
-  am->ret();
-
-  offset_of_call_insn
-     = am->JSC::MacroAssembler::differenceBetween(startOfFnLbl, cl);
-  if (0) printf("XXXXXXXX offset = %lu\n", offset_of_call_insn);
-#endif
-
-#if defined(ARCH_x86)
-  // ADD FN PROLOGUE/EPILOGUE so as to make a mini-function
-  // and then call a non-JIT-generated helper from within
-  // this code
-  //    push   %ebp
-  //    mov    %esp,%ebp
-  //    push   %ebx
-  //    push   %esi
-  //    push   %edi
-  //    push   $0x9
-  //    call   0x80490e9 <_Z4cubem>
-  //    add    $0x4,%esp
-  //    pop    %edi
-  //    pop    %esi
-  //    pop    %ebx
-  //    mov    %ebp,%esp
-  //    pop    %ebp
-  //    ret
-  JSC::MacroAssembler::Label startOfFnLbl(am);
-  am->push(JSC::X86Registers::ebp);
-  am->move(JSC::X86Registers::esp, JSC::X86Registers::ebp);
-  am->push(JSC::X86Registers::ebx);
-  am->push(JSC::X86Registers::esi);
-  am->push(JSC::X86Registers::edi);
-
-  // let's compute cube(9).  Push $9 on the stack.
-  am->push(JSC::MacroAssembler::Imm32(9));
-  cl = am->JSC::MacroAssembler::call();
-  am->addPtr(JSC::MacroAssembler::Imm32(4), JSC::X86Registers::esp);
-  // result is now in %eax.  Leave it there and just return.
-
-  am->pop(JSC::X86Registers::edi);
-  am->pop(JSC::X86Registers::esi);
-  am->pop(JSC::X86Registers::ebx);
-  am->move(JSC::X86Registers::ebp, JSC::X86Registers::esp);
-  am->pop(JSC::X86Registers::ebp);
-  am->ret();
-
-  offset_of_call_insn
-     = am->JSC::MacroAssembler::differenceBetween(startOfFnLbl, cl);
-  if (0) printf("XXXXXXXX offset = %lu\n",
-                (unsigned long)offset_of_call_insn);
-#endif
-
-#if defined(ARCH_arm)
-  // ADD FN PROLOGUE/EPILOGUE so as to make a mini-function
-  //    push    {r4}            ; (str r4, [sp, #-4]!)
-  //    push    {r5}            ; (str r5, [sp, #-4]!)
-  //    push    {r6}            ; (str r6, [sp, #-4]!)
-  //    push    {r7}            ; (str r7, [sp, #-4]!)
-  //    push    {r8}            ; (str r8, [sp, #-4]!)
-  //    push    {r9}            ; (str r9, [sp, #-4]!)
-  //    push    {r10}           ; (str r10, [sp, #-4]!)
-  //    push    {r11}           ; (str r11, [sp, #-4]!)
-  //    eors    r0, r0, r0
-  //    adds    r0, r0, #123    ; 0x7b
-  //    mov     r3, #256        ; 0x100
-  //    orr     r3, r3, #65     ; 0x41
-  //    adds    r0, r0, r3
-  //    pop     {r11}           ; (ldr r11, [sp], #4)
-  //    pop     {r10}           ; (ldr r10, [sp], #4)
-  //    pop     {r9}            ; (ldr r9, [sp], #4)
-  //    pop     {r8}            ; (ldr r8, [sp], #4)
-  //    pop     {r7}            ; (ldr r7, [sp], #4)
-  //    pop     {r6}            ; (ldr r6, [sp], #4)
-  //    pop     {r5}            ; (ldr r5, [sp], #4)
-  //    pop     {r4}            ; (ldr r4, [sp], #4)
-  //    mov     pc, lr
-  // callable as a normal function, returns 444
-  JSC::MacroAssembler::Label startOfFnLbl(am);
-  am->push(JSC::ARMRegisters::r4);
-  am->push(JSC::ARMRegisters::r5);
-  am->push(JSC::ARMRegisters::r6);
-  am->push(JSC::ARMRegisters::r7);
-  am->push(JSC::ARMRegisters::r8);
-  am->push(JSC::ARMRegisters::r9);
-  am->push(JSC::ARMRegisters::r10);
-  am->push(JSC::ARMRegisters::r11);
-  am->push(JSC::ARMRegisters::lr);
-
-  // let's compute cube(9).  Get $9 into r0.
-  am->move(JSC::MacroAssembler::Imm32(9), JSC::ARMRegisters::r0);
-  cl = am->JSC::MacroAssembler::call();
-  // result is now in r0.  Leave it there and just return.
-
-  am->pop(JSC::ARMRegisters::lr);
-  am->pop(JSC::ARMRegisters::r11);
-  am->pop(JSC::ARMRegisters::r10);
-  am->pop(JSC::ARMRegisters::r9);
-  am->pop(JSC::ARMRegisters::r8);
-  am->pop(JSC::ARMRegisters::r7);
-  am->pop(JSC::ARMRegisters::r6);
-  am->pop(JSC::ARMRegisters::r5);
-  am->pop(JSC::ARMRegisters::r4);
-  am->ret();
-
-  offset_of_call_insn
-     = am->JSC::MacroAssembler::differenceBetween(startOfFnLbl, cl);
-  if (0) printf("XXXXXXXX offset = %lu\n",
-                (unsigned long)offset_of_call_insn);
-#endif
-
-  // prepare a link buffer, into which we can copy the completed insns
-  JSC::ExecutableAllocator* eal = new JSC::ExecutableAllocator();
-
-  // intermediate step .. get the pool suited for the size of code in 'am'
-  //WTF::PassRefPtr<JSC::ExecutablePool> ep = eal->poolForSize( am->size() );
-  JSC::ExecutablePool* ep = eal->poolForSize( am->size() );
-
-  // constructor for LinkBuffer asks ep to allocate r-x memory,
-  // then copies it there.
-  JSC::LinkBuffer patchBuffer(am, ep, JSC::METHOD_CODE);
-
-  // now fix up any branches/calls
-  JSC::FunctionPtr target = JSC::FunctionPtr::FunctionPtr( &cube );
-  patchBuffer.link(cl, target);
-
-  JSC::MacroAssemblerCodeRef cr = patchBuffer.finalizeCode();
-
-  // cr now holds a pointer to the final runnable code.
-  void* entry = cr.m_code.executableAddress();
-
-  printf("disas %p %p\n",
-         entry, (char*)entry + cr.m_size);
-
-
-  pre_run();
-
-  printf("\n");
-
-  unsigned long (*fn)() = (unsigned long(*)())entry;
-  unsigned long result = fn();
-
-  printf("value computed is %lu (expected 729)\n", result);
-  printf("\n");
-
-  // now repatch the call in the JITted code to go elsewhere
-  JSC::JITCode jc = JSC::JITCode::JITCode(entry, cr.m_size);
-  JSC::CodeBlock cb = JSC::CodeBlock::CodeBlock(jc);
-
-  // the address of the call insn, that we want to prod
-  JSC::MacroAssemblerCodePtr cp
-     = JSC::MacroAssemblerCodePtr( ((char*)entry) + offset_of_call_insn );
-
-  JSC::RepatchBuffer repatchBuffer(&cb);
-  repatchBuffer.relink( JSC::CodeLocationCall(cp),
-                        JSC::FunctionPtr::FunctionPtr( &square ));
-
-  result = fn();
-  printf("value computed is %lu (expected 81)\n", result);
-  printf("\n\n");
-
-  delete eal;
-  delete am;
-}
-
-/////////////////////////////////////////////////////////////////
-
-int main ( void )
-{
-#if WTF_COMPILER_GCC
-  test1();
-  test2();
-  test3();
-#endif
-  test4();
-  test5();
-  return 0;
-}
deleted file mode 100644
--- a/js/src/assembler/assembler/ARMAssembler.cpp
+++ /dev/null
@@ -1,669 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- * vim: set ts=8 sts=4 et sw=4 tw=99:
- *
- * ***** BEGIN LICENSE BLOCK *****
- * Copyright (C) 2009 University of Szeged
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include "assembler/wtf/Platform.h"
-
-#if ENABLE_ASSEMBLER && WTF_CPU_ARM_TRADITIONAL
-
-#include "assembler/assembler/ARMAssembler.h"
-
-namespace JSC {
-
-// Patching helpers
-
-void ARMAssembler::patchConstantPoolLoad(void* loadAddr, void* constPoolAddr)
-{
-    ARMWord *ldr = reinterpret_cast<ARMWord*>(loadAddr);
-    ARMWord diff = reinterpret_cast<ARMWord*>(constPoolAddr) - ldr;
-    ARMWord index = (*ldr & 0xfff) >> 1;
-
-    ASSERT(diff >= 1);
-    if (diff >= 2 || index > 0) {
-        diff = (diff + index - 2) * sizeof(ARMWord);
-        ASSERT(diff <= 0xfff);
-        *ldr = (*ldr & ~0xfff) | diff;
-    } else
-        *ldr = (*ldr & ~(0xfff | ARMAssembler::DT_UP)) | sizeof(ARMWord);
-}
-
-// Handle immediates
-
-ARMWord ARMAssembler::getOp2(ARMWord imm)
-{
-    int rol;
-
-    if (imm <= 0xff)
-        return OP2_IMM | imm;
-
-    if ((imm & 0xff000000) == 0) {
-        imm <<= 8;
-        rol = 8;
-    }
-    else {
-        imm = (imm << 24) | (imm >> 8);
-        rol = 0;
-    }
-
-    if ((imm & 0xff000000) == 0) {
-        imm <<= 8;
-        rol += 4;
-    }
-
-    if ((imm & 0xf0000000) == 0) {
-        imm <<= 4;
-        rol += 2;
-    }
-
-    if ((imm & 0xc0000000) == 0) {
-        imm <<= 2;
-        rol += 1;
-    }
-
-    if ((imm & 0x00ffffff) == 0)
-        return OP2_IMM | (imm >> 24) | (rol << 8);
-
-    return INVALID_IMM;
-}
-
-ARMWord ARMAssembler::getOp2RegScale(RegisterID reg, ARMWord scale)
-{
-    // The field that this method constructs looks like this:
-    // [11:7]   Shift immediate.
-    // [ 6:5]   Shift type. Only LSL ("00") is used here.
-    // [ 4:4]   0.
-    // [ 3:0]   The register to shift.
-
-    ARMWord shift;  // Shift field. This is log2(scale).
-    ARMWord lz;     // Leading zeroes.
-
-    // Calculate shift=log2(scale).
-#if WTF_ARM_ARCH_AT_LEAST_5
-    asm (
-    "   clz     %[lz], %[scale]\n"
-    : [lz]      "=r"  (lz)
-    : [scale]   "r"   (scale)
-    : // No clobbers.
-    );
-#else
-    lz = 0; // Accumulate leading zeroes.
-    for (ARMWord s = 16; s > 0; s /= 2) {
-        ARMWord mask = 0xffffffff << (32-lz-s);
-        if ((scale & mask) == 0) {
-            lz += s;
-        }
-    }
-#endif
-    if (lz >= 32) {
-        return INVALID_IMM;
-    }
-    shift = 31-lz;
-    // Check that scale was a power of 2.
-    if ((1u<<shift) != scale) {
-        return INVALID_IMM;
-    }
-
-    return (shift << 7) | (reg);
-}
-
-int ARMAssembler::genInt(int reg, ARMWord imm, bool positive)
-{
-    // Step1: Search a non-immediate part
-    ARMWord mask;
-    ARMWord imm1;
-    ARMWord imm2;
-    int rol;
-
-    mask = 0xff000000;
-    rol = 8;
-    while(1) {
-        if ((imm & mask) == 0) {
-            imm = (imm << rol) | (imm >> (32 - rol));
-            rol = 4 + (rol >> 1);
-            break;
-        }
-        rol += 2;
-        mask >>= 2;
-        if (mask & 0x3) {
-            // rol 8
-            imm = (imm << 8) | (imm >> 24);
-            mask = 0xff00;
-            rol = 24;
-            while (1) {
-                if ((imm & mask) == 0) {
-                    imm = (imm << rol) | (imm >> (32 - rol));
-                    rol = (rol >> 1) - 8;
-                    break;
-                }
-                rol += 2;
-                mask >>= 2;
-                if (mask & 0x3)
-                    return 0;
-            }
-            break;
-        }
-    }
-
-    ASSERT((imm & 0xff) == 0);
-
-    if ((imm & 0xff000000) == 0) {
-        imm1 = OP2_IMM | ((imm >> 16) & 0xff) | (((rol + 4) & 0xf) << 8);
-        imm2 = OP2_IMM | ((imm >> 8) & 0xff) | (((rol + 8) & 0xf) << 8);
-    } else if (imm & 0xc0000000) {
-        imm1 = OP2_IMM | ((imm >> 24) & 0xff) | ((rol & 0xf) << 8);
-        imm <<= 8;
-        rol += 4;
-
-        if ((imm & 0xff000000) == 0) {
-            imm <<= 8;
-            rol += 4;
-        }
-
-        if ((imm & 0xf0000000) == 0) {
-            imm <<= 4;
-            rol += 2;
-        }
-
-        if ((imm & 0xc0000000) == 0) {
-            imm <<= 2;
-            rol += 1;
-        }
-
-        if ((imm & 0x00ffffff) == 0)
-            imm2 = OP2_IMM | (imm >> 24) | ((rol & 0xf) << 8);
-        else
-            return 0;
-    } else {
-        if ((imm & 0xf0000000) == 0) {
-            imm <<= 4;
-            rol += 2;
-        }
-
-        if ((imm & 0xc0000000) == 0) {
-            imm <<= 2;
-            rol += 1;
-        }
-
-        imm1 = OP2_IMM | ((imm >> 24) & 0xff) | ((rol & 0xf) << 8);
-        imm <<= 8;
-        rol += 4;
-
-        if ((imm & 0xf0000000) == 0) {
-            imm <<= 4;
-            rol += 2;
-        }
-
-        if ((imm & 0xc0000000) == 0) {
-            imm <<= 2;
-            rol += 1;
-        }
-
-        if ((imm & 0x00ffffff) == 0)
-            imm2 = OP2_IMM | (imm >> 24) | ((rol & 0xf) << 8);
-        else
-            return 0;
-    }
-
-    if (positive) {
-        mov_r(reg, imm1);
-        orr_r(reg, reg, imm2);
-    } else {
-        mvn_r(reg, imm1);
-        bic_r(reg, reg, imm2);
-    }
-
-    return 1;
-}
-
-#ifdef __GNUC__
-// If the result of this function isn't used, the caller should probably be
-// using movImm.
-__attribute__((warn_unused_result))
-#endif
-ARMWord ARMAssembler::getImm(ARMWord imm, int tmpReg, bool invert)
-{
-    ARMWord tmp;
-
-    // Do it by 1 instruction
-    tmp = getOp2(imm);
-    if (tmp != INVALID_IMM)
-        return tmp;
-
-    tmp = getOp2(~imm);
-    if (tmp != INVALID_IMM) {
-        if (invert)
-            return tmp | OP2_INV_IMM;
-        mvn_r(tmpReg, tmp);
-        return tmpReg;
-    }
-
-    return encodeComplexImm(imm, tmpReg);
-}
-
-void ARMAssembler::moveImm(ARMWord imm, int dest)
-{
-    ARMWord tmp;
-
-    // Do it by 1 instruction
-    tmp = getOp2(imm);
-    if (tmp != INVALID_IMM) {
-        mov_r(dest, tmp);
-        return;
-    }
-
-    tmp = getOp2(~imm);
-    if (tmp != INVALID_IMM) {
-        mvn_r(dest, tmp);
-        return;
-    }
-
-    encodeComplexImm(imm, dest);
-}
-
-ARMWord ARMAssembler::encodeComplexImm(ARMWord imm, int dest)
-{
-#if WTF_ARM_ARCH_VERSION >= 7
-    ARMWord tmp = getImm16Op2(imm);
-    if (tmp != INVALID_IMM) {
-        movw_r(dest, tmp);
-        return dest;
-    }
-    movw_r(dest, getImm16Op2(imm & 0xffff));
-    movt_r(dest, getImm16Op2(imm >> 16));
-    return dest;
-#else
-    // Do it by 2 instruction
-    if (genInt(dest, imm, true))
-        return dest;
-    if (genInt(dest, ~imm, false))
-        return dest;
-
-    ldr_imm(dest, imm);
-    return dest;
-#endif
-}
-
-// Memory load/store helpers
-// TODO: this does not take advantage of all of ARMv7's instruction encodings, it should.
-void ARMAssembler::dataTransferN(bool isLoad, bool isSigned, int size, RegisterID rt, RegisterID base, int32_t offset)
-{
-    bool posOffset = true;
-
-    // There may be more elegant ways of handling this, but this one works.
-    if (offset == int32_t(0x80000000)) {
-        // For even bigger offsets, load the entire offset into a register, then do an
-        // indexed load using the base register and the index register.
-        moveImm(offset, ARMRegisters::S0);
-        mem_reg_off(isLoad, isSigned, size, posOffset, rt, base, ARMRegisters::S0);
-        return;
-    }
-    if (offset < 0) {
-        offset = - offset;
-        posOffset = false;
-    }
-
-    // max_ldr is also a mask.
-    int max_ldr = 0xfff;
-    int ldr_bits = 12;
-    if (size == 16 || (size == 8 && isSigned)) {
-        max_ldr = 0xff;
-        ldr_bits = 8;
-    }
-
-    if (offset <= max_ldr) {
-        // LDR rd, [rb, #+offset]
-        mem_imm_off(isLoad, isSigned, size, posOffset, rt, base, offset);
-    } else if (offset <= ((max_ldr << 8) | 0xff)) {
-        // Add upper bits of offset to the base, and store the result into the temp register.
-        if (posOffset) {
-            add_r(ARMRegisters::S0, base, OP2_IMM | (offset >> ldr_bits) | getOp2RotLSL(ldr_bits));
-        } else {
-            sub_r(ARMRegisters::S0, base, OP2_IMM | (offset >> ldr_bits) | getOp2RotLSL(ldr_bits));
-        }
-        // Load using the lower bits of the offset, using max_ldr as a mask.
-        mem_imm_off(isLoad, isSigned, size, posOffset, rt,
-                    ARMRegisters::S0, (offset & max_ldr));
-    } else {
-        // For even bigger offsets, load the entire offset into a register, then do an
-        // indexed load using the base register and the index register.
-        moveImm(offset, ARMRegisters::S0);
-        mem_reg_off(isLoad, isSigned, size, posOffset, rt, base, ARMRegisters::S0);
-    }
-}
-
-void ARMAssembler::dataTransfer32(bool isLoad, RegisterID srcDst, RegisterID base, int32_t offset)
-{
-    if (offset >= 0) {
-        if (offset <= 0xfff) {
-            // LDR rd, [rb, +offset]
-            dtr_u(isLoad, srcDst, base, offset);
-        } else if (offset <= 0xfffff) {
-            // Add upper bits of offset to the base, and store the result into the temp register.
-            add_r(ARMRegisters::S0, base, OP2_IMM | (offset >> 12) | getOp2RotLSL(12));
-            // Load using the lower bits of the register.
-            dtr_u(isLoad, srcDst, ARMRegisters::S0, (offset & 0xfff));
-        } else {
-            // For even bigger offsets, load the entire offset into a register, then do an
-            // indexed load using the base register and the index register.
-            moveImm(offset, ARMRegisters::S0);
-            dtr_ur(isLoad, srcDst, base, ARMRegisters::S0);
-        }
-    } else {
-        // Negative offsets.
-        if (offset >= -0xfff) {
-            dtr_d(isLoad, srcDst, base, -offset);
-        } else if (offset >= -0xfffff) {
-            sub_r(ARMRegisters::S0, base, OP2_IMM | (-offset >> 12) | getOp2RotLSL(12));
-            dtr_d(isLoad, srcDst, ARMRegisters::S0, (-offset & 0xfff));
-        } else {
-            moveImm(offset, ARMRegisters::S0);
-            dtr_ur(isLoad, srcDst, base, ARMRegisters::S0);
-        }
-    }
-}
-/* this is large, ugly and obsolete.  dataTransferN is superior.*/
-void ARMAssembler::dataTransfer8(bool isLoad, RegisterID srcDst, RegisterID base, int32_t offset, bool isSigned)
-{
-    if (offset >= 0) {
-        if (offset <= 0xfff) {
-            if (isSigned)
-                mem_imm_off(isLoad, true, 8, true, srcDst, base, offset);
-            else
-                dtrb_u(isLoad, srcDst, base, offset);
-        } else if (offset <= 0xfffff) {
-            add_r(ARMRegisters::S0, base, OP2_IMM | (offset >> 12) | getOp2RotLSL(12));
-            if (isSigned)
-                mem_imm_off(isLoad, true, 8, true, srcDst, ARMRegisters::S0, (offset & 0xfff));
-            else
-                dtrb_u(isLoad, srcDst, ARMRegisters::S0, (offset & 0xfff));
-        } else {
-            moveImm(offset, ARMRegisters::S0);
-            if (isSigned)
-                mem_reg_off(isLoad, true, 8, true, srcDst, base, ARMRegisters::S0);
-            else
-                dtrb_ur(isLoad, srcDst, base, ARMRegisters::S0);
-        }
-    } else {
-        if (offset >= -0xfff) {
-            if (isSigned)
-                mem_imm_off(isLoad, true, 8, false, srcDst, base, -offset);
-            else
-                dtrb_d(isLoad, srcDst, base, -offset);
-        } else if (offset >= -0xfffff) {
-            sub_r(ARMRegisters::S0, base, OP2_IMM | (-offset >> 12) | getOp2RotLSL(12));
-            if (isSigned)
-                mem_imm_off(isLoad, true, 8, false, srcDst, ARMRegisters::S0, (-offset & 0xfff));
-            else
-                dtrb_d(isLoad, srcDst, ARMRegisters::S0, (-offset & 0xfff));
-
-        } else {
-            moveImm(offset, ARMRegisters::S0);
-            if (isSigned)
-                mem_reg_off(isLoad, true, 8, true, srcDst, base, ARMRegisters::S0);
-            else
-                dtrb_ur(isLoad, srcDst, base, ARMRegisters::S0);
-
-        }
-    }
-}
-
-// rather X86-like, implements dest <- [base, index * shift + offset]
-void ARMAssembler::baseIndexTransfer32(bool isLoad, RegisterID srcDst, RegisterID base, RegisterID index, int scale, int32_t offset)
-{
-    ARMWord op2;
-
-    ASSERT(scale >= 0 && scale <= 3);
-    op2 = lsl(index, scale);
-
-    if (offset >= 0 && offset <= 0xfff) {
-        add_r(ARMRegisters::S0, base, op2);
-        dtr_u(isLoad, srcDst, ARMRegisters::S0, offset);
-        return;
-    }
-    if (offset <= 0 && offset >= -0xfff) {
-        add_r(ARMRegisters::S0, base, op2);
-        dtr_d(isLoad, srcDst, ARMRegisters::S0, -offset);
-        return;
-    }
-
-    ldr_un_imm(ARMRegisters::S0, offset);
-    add_r(ARMRegisters::S0, ARMRegisters::S0, op2);
-    dtr_ur(isLoad, srcDst, base, ARMRegisters::S0);
-}
-
-void ARMAssembler::baseIndexTransferN(bool isLoad, bool isSigned, int size, RegisterID srcDst, RegisterID base, RegisterID index, int scale, int32_t offset)
-{
-    ARMWord op2;
-
-    ASSERT(scale >= 0 && scale <= 3);
-    op2 = lsl(index, scale);
-
-    if (offset >= -0xfff && offset <= 0xfff) {
-        add_r(ARMRegisters::S0, base, op2);
-        bool posOffset = true;
-        if (offset < 0) {
-            posOffset = false;
-            offset = -offset;
-        }
-        mem_imm_off(isLoad, isSigned, size, posOffset, srcDst, ARMRegisters::S0, offset);
-        return;
-    }
-    ldr_un_imm(ARMRegisters::S0, offset);
-    add_r(ARMRegisters::S0, ARMRegisters::S0, op2);
-    mem_reg_off(isLoad, isSigned, size, true, srcDst, base, ARMRegisters::S0);
-}
-
-void ARMAssembler::doubleTransfer(bool isLoad, FPRegisterID srcDst, RegisterID base, int32_t offset)
-{
-    // VFP cannot directly access memory that is not four-byte-aligned, so
-    // special-case support will be required for such cases. However, we don't
-    // currently use any unaligned floating-point memory accesses and probably
-    // never will, so for now just assert that the offset is aligned.
-    //
-    // Note that we cannot assert that the base register is aligned, but in
-    // that case, an alignment fault will be raised at run-time.
-    ASSERT((offset & 0x3) == 0);
-
-    // Try to use a single load/store instruction, or at least a simple address
-    // calculation.
-    if (offset >= 0) {
-        if (offset <= 0x3ff) {
-            fmem_imm_off(isLoad, true, true, srcDst, base, offset >> 2);
-            return;
-        }
-        if (offset <= 0x3ffff) {
-            add_r(ARMRegisters::S0, base, OP2_IMM | (offset >> 10) | getOp2RotLSL(10));
-            fmem_imm_off(isLoad, true, true, srcDst, ARMRegisters::S0, (offset >> 2) & 0xff);
-            return;
-        }
-    } else {
-        if (offset >= -0x3ff) {
-            fmem_imm_off(isLoad, true, false, srcDst, base, -offset >> 2);
-            return;
-        }
-        if (offset >= -0x3ffff) {
-            sub_r(ARMRegisters::S0, base, OP2_IMM | (-offset >> 10) | getOp2RotLSL(10));
-            fmem_imm_off(isLoad, true, false, srcDst, ARMRegisters::S0, (-offset >> 2) & 0xff);
-            return;
-        }
-    }
-
-    // Slow case for long-range accesses.
-    ldr_un_imm(ARMRegisters::S0, offset);
-    add_r(ARMRegisters::S0, ARMRegisters::S0, base);
-    fmem_imm_off(isLoad, true, true, srcDst, ARMRegisters::S0, 0);
-}
-
-void ARMAssembler::doubleTransfer(bool isLoad, FPRegisterID srcDst, RegisterID base, int32_t offset, RegisterID index, int32_t scale)
-{
-    // This variant accesses memory at base+offset+(index*scale). VLDR and VSTR
-    // don't have such an addressing mode, so this access will require some
-    // arithmetic instructions.
-
-    // This method does not support accesses that are not four-byte-aligned.
-    ASSERT((offset & 0x3) == 0);
-
-    // Catch the trivial case, where scale is 0.
-    if (scale == 0) {
-        doubleTransfer(isLoad, srcDst, base, offset);
-        return;
-    }
-
-    // Calculate the address, excluding the non-scaled offset. This is
-    // efficient for scale factors that are powers of two.
-    ARMWord op2_index = getOp2RegScale(index, scale);
-    if (op2_index == INVALID_IMM) {
-        // Use MUL to calculate scale factors that are not powers of two.
-        moveImm(scale, ARMRegisters::S0);
-        mul_r(ARMRegisters::S0, index, ARMRegisters::S0);
-        op2_index = ARMRegisters::S0;
-    }
-
-    add_r(ARMRegisters::S0, base, op2_index);
-    doubleTransfer(isLoad, srcDst, ARMRegisters::S0, offset);
-}
-
-void ARMAssembler::floatTransfer(bool isLoad, FPRegisterID srcDst, RegisterID base, int32_t offset)
-{
-    // Assert that the access is aligned, as in doubleTransfer.
-    ASSERT((offset & 0x3) == 0);
-
-    // Try to use a single load/store instruction, or at least a simple address
-    // calculation.
-    if (offset >= 0) {
-        if (offset <= 0x3ff) {
-            fmem_imm_off(isLoad, false, true, srcDst, base, offset >> 2);
-            return;
-        }
-        if (offset <= 0x3ffff) {
-            add_r(ARMRegisters::S0, base, OP2_IMM | (offset >> 10) | getOp2RotLSL(10));
-            fmem_imm_off(isLoad, false, true, srcDst, ARMRegisters::S0, (offset >> 2) & 0xff);
-            return;
-        }
-    } else {
-        if (offset >= -0x3ff) {
-            fmem_imm_off(isLoad, false, false, srcDst, base, -offset >> 2);
-            return;
-        }
-        if (offset >= -0x3ffff) {
-            sub_r(ARMRegisters::S0, base, OP2_IMM | (-offset >> 10) | getOp2RotLSL(10));
-            fmem_imm_off(isLoad, false, false, srcDst, ARMRegisters::S0, (-offset >> 2) & 0xff);
-            return;
-        }
-    }
-
-    // Slow case for long-range accesses.
-    ldr_un_imm(ARMRegisters::S0, offset);
-    add_r(ARMRegisters::S0, ARMRegisters::S0, base);
-    fmem_imm_off(isLoad, false, true, srcDst, ARMRegisters::S0, 0);
-}
-
-void ARMAssembler::baseIndexFloatTransfer(bool isLoad, bool isDouble, FPRegisterID srcDst, RegisterID base, RegisterID index, int scale, int32_t offset)
-{
-    ARMWord op2;
-
-    ASSERT(scale >= 0 && scale <= 3);
-    op2 = lsl(index, scale);
-    // vldr/vstr have a more restricted range than your standard ldr.
-    // they get 8 bits that are implicitly shifted left by 2.
-    if (offset >= -(0xff<<2) && offset <= (0xff<<2)) {
-        add_r(ARMRegisters::S0, base, op2);
-        bool posOffset = true;
-        if (offset < 0) {
-            posOffset = false;
-            offset = -offset;
-        }
-        fmem_imm_off(isLoad, isDouble, posOffset, srcDst, ARMRegisters::S0, offset >> 2);
-        return;
-    }
-
-    ldr_un_imm(ARMRegisters::S0, offset);
-    // vldr/vstr do not allow register-indexed operations, so we get to do this *manually*.
-    add_r(ARMRegisters::S0, ARMRegisters::S0, op2);
-    add_r(ARMRegisters::S0, ARMRegisters::S0, base);
-
-    fmem_imm_off(isLoad, isDouble, true, srcDst, ARMRegisters::S0, 0);
-}
-
-// Fix up the offsets and literal-pool loads in buffer. The buffer should
-// already contain the code from m_buffer.
-inline void ARMAssembler::fixUpOffsets(void * buffer)
-{
-    char * data = reinterpret_cast<char *>(buffer);
-    for (Jumps::Iterator iter = m_jumps.begin(); iter != m_jumps.end(); ++iter) {
-        // The last bit is set if the constant must be placed on constant pool.
-        int pos = (*iter) & (~0x1);
-        ARMWord* ldrAddr = reinterpret_cast<ARMWord*>(data + pos);
-        ARMWord* addr = getLdrImmAddress(ldrAddr);
-        if (*addr != InvalidBranchTarget) {
-// The following is disabled for JM because we patch some branches after
-// calling fixUpOffset, and the branch patcher doesn't know how to handle 'B'
-// instructions.
-#if 0
-            if (!(*iter & 1)) {
-                int diff = reinterpret_cast<ARMWord*>(data + *addr) - (ldrAddr + DefaultPrefetching);
-
-                if ((diff <= BOFFSET_MAX && diff >= BOFFSET_MIN)) {
-                    *ldrAddr = B | getConditionalField(*ldrAddr) | (diff & BRANCH_MASK);
-                    continue;
-                }
-            }
-#endif
-            *addr = reinterpret_cast<ARMWord>(data + *addr);
-        }
-    }
-}
-
-void* ARMAssembler::executableAllocAndCopy(ExecutableAllocator* allocator, ExecutablePool **poolp, CodeKind kind)
-{
-    // 64-bit alignment is required for next constant pool and JIT code as well
-    m_buffer.flushWithoutBarrier(true);
-    if (m_buffer.uncheckedSize() & 0x7)
-        bkpt(0);
-
-    void * data = m_buffer.executableAllocAndCopy(allocator, poolp, kind);
-    if (data)
-        fixUpOffsets(data);
-    return data;
-}
-
-// This just dumps the code into the specified buffer, fixing up absolute
-// offsets and literal pool loads as it goes. The buffer is assumed to be large
-// enough to hold the code, and any pre-existing literal pool is assumed to
-// have been flushed.
-void ARMAssembler::executableCopy(void * buffer)
-{
-    ASSERT(m_buffer.sizeOfConstantPool() == 0);
-    memcpy(buffer, m_buffer.data(), m_buffer.size());
-    fixUpOffsets(buffer);
-}
-
-} // namespace JSC
-
-#endif // ENABLE(ASSEMBLER) && CPU(ARM_TRADITIONAL)
deleted file mode 100644
--- a/js/src/assembler/assembler/ARMAssembler.h
+++ /dev/null
@@ -1,1713 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- * vim: set ts=8 sts=4 et sw=4 tw=99:
- *
- * ***** BEGIN LICENSE BLOCK *****
- * Copyright (C) 2009, 2010 University of Szeged
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#ifndef assembler_assembler_ARMAssembler_h
-#define assembler_assembler_ARMAssembler_h
-
-#include "assembler/wtf/Platform.h"
-
-// Some debug code uses s(n)printf for instruction logging.
-#include <stdio.h>
-
-#if ENABLE_ASSEMBLER && WTF_CPU_ARM_TRADITIONAL
-
-#include "assembler/assembler/AssemblerBufferWithConstantPool.h"
-#include "assembler/wtf/Assertions.h"
-
-// TODO: We don't print the condition code in our spew lines. Doing this
-// is awkward whilst maintaining a consistent field width.
-namespace js {
-    namespace jit {
-        class Assembler;
-    }
-}
-
-namespace JSC {
-
-    typedef uint32_t ARMWord;
-
-    namespace ARMRegisters {
-        typedef enum {
-            r0 = 0,
-            r1,
-            r2,
-            r3,
-            S0 = r3,
-            r4,
-            r5,
-            r6,
-            r7,
-            r8,
-            S1 = r8,
-            r9,
-            r10,
-            r11,
-            r12,
-            ip = r12,
-            r13,
-            sp = r13,
-            r14,
-            lr = r14,
-            r15,
-            pc = r15,
-            invalid_reg
-        } RegisterID;
-
-        typedef enum {
-            d0,
-            d1,
-            d2,
-            d3,
-            SD0 = d3,
-            d4,
-            d5,
-            d6,
-            d7,
-            d8,
-            d9,
-            d10,
-            d11,
-            d12,
-            d13,
-            d14,
-            d15,
-            d16,
-            d17,
-            d18,
-            d19,
-            d20,
-            d21,
-            d22,
-            d23,
-            d24,
-            d25,
-            d26,
-            d27,
-            d28,
-            d29,
-            d30,
-            d31,
-            invalid_freg
-        } FPRegisterID;
-
-        inline FPRegisterID floatShadow(FPRegisterID s)
-        {
-            return (FPRegisterID)(s*2);
-        }
-        inline FPRegisterID doubleShadow(FPRegisterID d)
-        {
-            return (FPRegisterID)(d / 2);
-        }
-    } // namespace ARMRegisters
-    class ARMAssembler : public GenericAssembler {
-    public:
-
-        typedef ARMRegisters::RegisterID RegisterID;
-        typedef ARMRegisters::FPRegisterID FPRegisterID;
-        typedef AssemblerBufferWithConstantPool<2048, 4, 4, ARMAssembler> ARMBuffer;
-        typedef SegmentedVector<int, 64> Jumps;
-
-        unsigned char *buffer() const { return m_buffer.buffer(); }
-        bool oom() const { return m_buffer.oom(); }
-
-        // ARM conditional constants
-        typedef enum {
-            EQ = 0x00000000, // Zero
-            NE = 0x10000000, // Non-zero
-            CS = 0x20000000,
-            CC = 0x30000000,
-            MI = 0x40000000,
-            PL = 0x50000000,
-            VS = 0x60000000,
-            VC = 0x70000000,
-            HI = 0x80000000,
-            LS = 0x90000000,
-            GE = 0xa0000000,
-            LT = 0xb0000000,
-            GT = 0xc0000000,
-            LE = 0xd0000000,
-            AL = 0xe0000000
-        } Condition;
-
-        // ARM instruction constants
-        enum {
-            AND = (0x0 << 21),
-            EOR = (0x1 << 21),
-            SUB = (0x2 << 21),
-            RSB = (0x3 << 21),
-            ADD = (0x4 << 21),
-            ADC = (0x5 << 21),
-            SBC = (0x6 << 21),
-            RSC = (0x7 << 21),
-            TST = (0x8 << 21),
-            TEQ = (0x9 << 21),
-            CMP = (0xa << 21),
-            CMN = (0xb << 21),
-            ORR = (0xc << 21),
-            MOV = (0xd << 21),
-            BIC = (0xe << 21),
-            MVN = (0xf << 21),
-            MUL = 0x00000090,
-            MULL = 0x00c00090,
-            FCPYD = 0x0eb00b40,
-            FADDD = 0x0e300b00,
-            FNEGD = 0x0eb10b40,
-            FABSD = 0x0eb00bc0,
-            FDIVD = 0x0e800b00,
-            FSUBD = 0x0e300b40,
-            FMULD = 0x0e200b00,
-            FCMPD = 0x0eb40b40,
-            FSQRTD = 0x0eb10bc0,
-            DTR = 0x05000000,
-            LDRH = 0x00100090,
-            STRH = 0x00000090,
-            DTRH = 0x00000090,
-            STMDB = 0x09200000,
-            LDMIA = 0x08b00000,
-            B = 0x0a000000,
-            BL = 0x0b000000
-#if WTF_ARM_ARCH_VERSION >= 5 || defined(__ARM_ARCH_4T__)
-           ,BX = 0x012fff10
-#endif
-#if WTF_ARM_ARCH_VERSION >= 5
-           ,CLZ = 0x016f0f10,
-            BKPT = 0xe1200070,
-            BLX = 0x012fff30
-#endif
-#if WTF_ARM_ARCH_VERSION >= 7
-           ,MOVW = 0x03000000,
-            MOVT = 0x03400000
-#endif
-        };
-
-        enum {
-            OP2_IMM = (1 << 25),
-            OP2_IMMh = (1 << 22),
-            OP2_INV_IMM = (1 << 26),
-            SET_CC = (1 << 20),
-            OP2_OFSREG = (1 << 25),
-            DT_UP = (1 << 23),
-            DT_BYTE = (1 << 22),
-            DT_WB = (1 << 21),
-            // This flag is inlcuded in LDR and STR
-            DT_PRE = (1 << 24),
-            // This flag makes switches the instruction between {ld,st}r{,s}h and {ld,st}rsb
-            HDT_UH = (1 << 5),
-            // if this bit is on, we do a register offset, if it is off, we do an immediate offest.
-            HDT_IMM = (1 << 22),
-            // Differentiates half word load/store between signed and unsigned (also enables signed byte loads.)
-            HDT_S = (1 << 6),
-            DT_LOAD = (1 << 20)
-        };
-
-        // Masks of ARM instructions
-        enum {
-            BRANCH_MASK = 0x00ffffff,
-            NONARM = 0xf0000000,
-            SDT_MASK = 0x0c000000,
-            SDT_OFFSET_MASK = 0xfff
-        };
-
-        enum {
-            BOFFSET_MIN = -0x00800000,
-            BOFFSET_MAX = 0x007fffff,
-            SDT = 0x04000000
-        };
-
-        enum {
-            padForAlign8  = (int)0x00,
-            padForAlign16 = (int)0x0000,
-            padForAlign32 = (int)0xe12fff7f  // 'bkpt 0xffff'
-        };
-
-        typedef enum {
-            LSL = 0,
-            LSR = 1,
-            ASR = 2,
-            ROR = 3
-        } Shift;
-
-        static const ARMWord INVALID_IMM = 0xf0000000;
-        static const ARMWord InvalidBranchTarget = 0xffffffff;
-        static const int DefaultPrefetching = 2;
-
-        class JmpSrc {
-            friend class ARMAssembler;
-            friend class js::jit::Assembler;
-        public:
-            JmpSrc()
-                : m_offset(-1)
-            {
-            }
-            int offset() {return m_offset;}
-
-            bool isSet() const {
-                return m_offset != -1;
-            }
-
-        private:
-            JmpSrc(int offset)
-                : m_offset(offset)
-            {
-            }
-
-            int m_offset;
-        };
-
-        class JmpDst {
-            friend class ARMAssembler;
-            friend class js::jit::Assembler;
-        public:
-            JmpDst()
-                : m_offset(-1)
-                , m_used(false)
-            {
-            }
-
-            bool isUsed() const { return m_used; }
-            void used() { m_used = true; }
-            bool isValid() const { return m_offset != -1; }
-        private:
-            JmpDst(int offset)
-                : m_offset(offset)
-                , m_used(false)
-            {
-                ASSERT(m_offset == offset);
-            }
-
-            int m_offset : 31;
-            bool m_used : 1;
-        };
-
-        // Instruction formating
-
-        void emitInst(ARMWord op, int rd, int rn, ARMWord op2)
-        {
-            ASSERT ( ((op2 & ~OP2_IMM) <= 0xfff) || (((op2 & ~OP2_IMMh) <= 0xfff)) );
-            m_buffer.putInt(op | RN(rn) | RD(rd) | op2);
-        }
-
-        // Work out the pre-shifted constant necessary to encode the specified
-        // logical shift left for op2 immediates. Only even shifts can be
-        // applied.
-        //
-        // Input validity is asserted in debug builds.
-        ARMWord getOp2RotLSL(int lsl)
-        {
-            ASSERT((lsl >= 0) && (lsl <= 24));
-            ASSERT(!(lsl % 2));
-
-            return (-(lsl/2) & 0xf) << 8;
-        }
-
-        void and_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("and", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | AND, rd, rn, op2);
-        }
-
-        void ands_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("ands", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | AND | SET_CC, rd, rn, op2);
-        }
-
-        void eor_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("eor", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | EOR, rd, rn, op2);
-        }
-
-        void eors_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("eors", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | EOR | SET_CC, rd, rn, op2);
-        }
-
-        void sub_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("sub", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | SUB, rd, rn, op2);
-        }
-
-        void subs_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("subs", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | SUB | SET_CC, rd, rn, op2);
-        }
-
-        void rsb_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("rsb", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | RSB, rd, rn, op2);
-        }
-
-        void rsbs_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("rsbs", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | RSB | SET_CC, rd, rn, op2);
-        }
-
-        void add_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("add", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | ADD, rd, rn, op2);
-        }
-
-        void adds_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("adds", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | ADD | SET_CC, rd, rn, op2);
-        }
-
-        void adc_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("adc", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | ADC, rd, rn, op2);
-        }
-
-        void adcs_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("adcs", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | ADC | SET_CC, rd, rn, op2);
-        }
-
-        void sbc_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("sbc", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | SBC, rd, rn, op2);
-        }
-
-        void sbcs_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("sbcs", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | SBC | SET_CC, rd, rn, op2);
-        }
-
-        void rsc_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("rsc", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | RSC, rd, rn, op2);
-        }
-
-        void rscs_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("rscs", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | RSC | SET_CC, rd, rn, op2);
-        }
-
-        void tst_r(int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("tst", cc, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | TST | SET_CC, 0, rn, op2);
-        }
-
-        void teq_r(int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("teq", cc, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | TEQ | SET_CC, 0, rn, op2);
-        }
-
-        void cmp_r(int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("cmp", cc, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | CMP | SET_CC, 0, rn, op2);
-        }
-
-        void cmn_r(int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("cmn", cc, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | CMN | SET_CC, 0, rn, op2);
-        }
-
-        void orr_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("orr", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | ORR, rd, rn, op2);
-        }
-
-        void orrs_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("orrs", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | ORR | SET_CC, rd, rn, op2);
-        }
-
-        void mov_r(int rd, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("mov", cc, rd, op2);
-            emitInst(static_cast<ARMWord>(cc) | MOV, rd, ARMRegisters::r0, op2);
-        }
-
-#if WTF_ARM_ARCH_VERSION >= 7
-        void movw_r(int rd, ARMWord op2, Condition cc = AL)
-        {
-            ASSERT((op2 | 0xf0fff) == 0xf0fff);
-            spew("%-15s %s, 0x%04x", "movw", nameGpReg(rd), (op2 & 0xfff) | ((op2 >> 4) & 0xf000));
-            m_buffer.putInt(static_cast<ARMWord>(cc) | MOVW | RD(rd) | op2);
-        }
-
-        void movt_r(int rd, ARMWord op2, Condition cc = AL)
-        {
-            ASSERT((op2 | 0xf0fff) == 0xf0fff);
-            spew("%-15s %s, 0x%04x", "movt", nameGpReg(rd), (op2 & 0xfff) | ((op2 >> 4) & 0xf000));
-            m_buffer.putInt(static_cast<ARMWord>(cc) | MOVT | RD(rd) | op2);
-        }
-#endif
-
-        void movs_r(int rd, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("movs", cc, rd, op2);
-            emitInst(static_cast<ARMWord>(cc) | MOV | SET_CC, rd, ARMRegisters::r0, op2);
-        }
-
-        void bic_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("bic", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | BIC, rd, rn, op2);
-        }
-
-        void bics_r(int rd, int rn, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("bics", cc, rd, rn, op2);
-            emitInst(static_cast<ARMWord>(cc) | BIC | SET_CC, rd, rn, op2);
-        }
-
-        void mvn_r(int rd, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("mvn", cc, rd, op2);
-            emitInst(static_cast<ARMWord>(cc) | MVN, rd, ARMRegisters::r0, op2);
-        }
-
-        void mvns_r(int rd, ARMWord op2, Condition cc = AL)
-        {
-            spewInsWithOp2("mvns", cc, rd, op2);
-            emitInst(static_cast<ARMWord>(cc) | MVN | SET_CC, rd, ARMRegisters::r0, op2);
-        }
-
-        void mul_r(int rd, int rn, int rm, Condition cc = AL)
-        {
-            spewInsWithOp2("mul", cc, rd, rn, static_cast<ARMWord>(rm));
-            m_buffer.putInt(static_cast<ARMWord>(cc) | MUL | RN(rd) | RS(rn) | RM(rm));
-        }
-
-        void muls_r(int rd, int rn, int rm, Condition cc = AL)
-        {
-            spewInsWithOp2("muls", cc, rd, rn, static_cast<ARMWord>(rm));
-            m_buffer.putInt(static_cast<ARMWord>(cc) | MUL | SET_CC | RN(rd) | RS(rn) | RM(rm));
-        }
-
-        void mull_r(int rdhi, int rdlo, int rn, int rm, Condition cc = AL)
-        {
-            spew("%-15s %s, %s, %s, %s", "mull", nameGpReg(rdlo), nameGpReg(rdhi), nameGpReg(rn), nameGpReg(rm));
-            m_buffer.putInt(static_cast<ARMWord>(cc) | MULL | RN(rdhi) | RD(rdlo) | RS(rn) | RM(rm));
-        }
-
-        // pc relative loads (useful for loading from pools).
-        void ldr_imm(int rd, ARMWord imm, Condition cc = AL)
-        {
-#if defined(JS_METHODJIT_SPEW)
-            char mnemonic[16];
-            snprintf(mnemonic, 16, "ldr%s", nameCC(cc));
-            spew("%-15s %s, =0x%x @ (%d) (reusable pool entry)", mnemonic, nameGpReg(rd), imm, static_cast<int32_t>(imm));
-#endif
-            m_buffer.putIntWithConstantInt(static_cast<ARMWord>(cc) | DTR | DT_LOAD | DT_UP | RN(ARMRegisters::pc) | RD(rd), imm, true);
-        }
-
-        void ldr_un_imm(int rd, ARMWord imm, Condition cc = AL)
-        {
-#if defined(JS_METHODJIT_SPEW)
-            char mnemonic[16];
-            snprintf(mnemonic, 16, "ldr%s", nameCC(cc));
-            spew("%-15s %s, =0x%x @ (%d)", mnemonic, nameGpReg(rd), imm, static_cast<int32_t>(imm));
-#endif
-            m_buffer.putIntWithConstantInt(static_cast<ARMWord>(cc) | DTR | DT_LOAD | DT_UP | RN(ARMRegisters::pc) | RD(rd), imm);
-        }
-
-        void mem_imm_off(bool isLoad, bool isSigned, int size, bool posOffset,
-                         int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            ASSERT(size == 8 || size == 16 || size == 32);
-            char const * mnemonic_act = (isLoad) ? ("ld") : ("st");
-            char const * mnemonic_sign = (isSigned) ? ("s") : ("");
-
-            char const * mnemonic_size = NULL;
-            switch (size / 8) {
-            case 1:
-                mnemonic_size = "b";
-                break;
-            case 2:
-                mnemonic_size = "h";
-                break;
-            case 4:
-                mnemonic_size = "";
-                break;
-            }
-            char const * off_sign = (posOffset) ? ("+") : ("-");
-            spew("%sr%s%s %s, [%s, #%s%u]",
-                 mnemonic_act, mnemonic_sign, mnemonic_size,
-                 nameGpReg(rd), nameGpReg(rb), off_sign, offset);
-            if (size == 32 || (size == 8 && !isSigned)) {
-                /* All (the one) 32 bit ops and the unsigned 8 bit ops use the original encoding.*/
-                emitInst(static_cast<ARMWord>(cc) | DTR |
-                         (isLoad ? DT_LOAD : 0) |
-                         (size == 8 ? DT_BYTE : 0) |
-                         (posOffset ? DT_UP : 0), rd, rb, offset);
-            } else {
-                /* All 16 bit ops and 8 bit unsigned use the newer encoding.*/
-                emitInst(static_cast<ARMWord>(cc) | DTRH | HDT_IMM | DT_PRE |
-                         (isLoad ? DT_LOAD : 0) |
-                         (size == 16 ? HDT_UH : 0) |
-                         (isSigned ? HDT_S : 0) |
-                         (posOffset ? DT_UP : 0), rd, rb, offset);
-            }
-        }
-
-        void mem_reg_off(bool isLoad, bool isSigned, int size, bool posOffset, int rd, int rb, int rm, Condition cc = AL)
-        {
-            char const * mnemonic_act = (isLoad) ? ("ld") : ("st");
-            char const * mnemonic_sign = (isSigned) ? ("s") : ("");
-
-            char const * mnemonic_size = NULL;
-            switch (size / 8) {
-            case 1:
-                mnemonic_size = "b";
-                break;
-            case 2:
-                mnemonic_size = "h";
-                break;
-            case 4:
-                mnemonic_size = "";
-                break;
-            }
-            char const * off_sign = (posOffset) ? ("+") : ("-");
-            spew("%sr%s%s %s, [%s, #%s%s]", mnemonic_act, mnemonic_sign, mnemonic_size,
-                 nameGpReg(rd), nameGpReg(rb), off_sign, nameGpReg(rm));
-            if (size == 32 || (size == 8 && !isSigned)) {
-                /* All (the one) 32 bit ops and the signed 8 bit ops use the original encoding.*/
-                emitInst(static_cast<ARMWord>(cc) | DTR |
-                         (isLoad ? DT_LOAD : 0) |
-                         (size == 8 ? DT_BYTE : 0) |
-                         (posOffset ? DT_UP : 0) |
-                         OP2_OFSREG, rd, rb, rm);
-            } else {
-                /* All 16 bit ops and 8 bit unsigned use the newer encoding.*/
-                emitInst(static_cast<ARMWord>(cc) | DTRH | DT_PRE |
-                         (isLoad ? DT_LOAD : 0) |
-                         (size == 16 ? HDT_UH : 0) |
-                         (isSigned ? HDT_S : 0) |
-                         (posOffset ? DT_UP : 0), rd, rb, rm);
-            }
-        }
-
-        // Data transfers like this:
-        //  LDR rd, [rb, +offset]
-        //  STR rd, [rb, +offset]
-        void dtr_u(bool isLoad, int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            char const * mnemonic = (isLoad) ? ("ldr") : ("str");
-            spew("%-15s %s, [%s, #+%u]",
-                 mnemonic, nameGpReg(rd), nameGpReg(rb), offset);
-            emitInst(static_cast<ARMWord>(cc) | DTR | (isLoad ? DT_LOAD : 0) | DT_UP, rd, rb, offset);
-        }
-
-        // Data transfers like this:
-        //  LDR rd, [rb, +rm]
-        //  STR rd, [rb, +rm]
-        void dtr_ur(bool isLoad, int rd, int rb, int rm, Condition cc = AL)
-        {
-            char const * mnemonic = (isLoad) ? ("ldr") : ("str");
-            spew("%-15s %s, [%s, +%s]",
-                 mnemonic, nameGpReg(rd), nameGpReg(rb), nameGpReg(rm));
-            emitInst(static_cast<ARMWord>(cc) | DTR | (isLoad ? DT_LOAD : 0) | DT_UP | OP2_OFSREG, rd, rb, rm);
-        }
-
-        // Data transfers like this:
-        //  LDR rd, [rb, -offset]
-        //  STR rd, [rb, -offset]
-        void dtr_d(bool isLoad, int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            char const * mnemonic = (isLoad) ? ("ldr") : ("str");
-            spew("%-15s %s, [%s, #-%u]",
-                 mnemonic, nameGpReg(rd), nameGpReg(rb), offset);
-            emitInst(static_cast<ARMWord>(cc) | DTR | (isLoad ? DT_LOAD : 0), rd, rb, offset);
-        }
-
-        // Data transfers like this:
-        //  LDR rd, [rb, -rm]
-        //  STR rd, [rb, -rm]
-        void dtr_dr(bool isLoad, int rd, int rb, int rm, Condition cc = AL)
-        {
-            char const * mnemonic = (isLoad) ? ("ldr") : ("str");
-            spew("%-15s %s, [%s, -%s]",
-                 mnemonic, nameGpReg(rd), nameGpReg(rb), nameGpReg(rm));
-            emitInst(static_cast<ARMWord>(cc) | DTR | (isLoad ? DT_LOAD : 0) | OP2_OFSREG, rd, rb, rm);
-        }
-
-        // Data transfers like this:
-        //  LDRB rd, [rb, +offset]
-        //  STRB rd, [rb, +offset]
-        void dtrb_u(bool isLoad, int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            char const * mnemonic = (isLoad) ? ("ldrb") : ("strb");
-            spew("%-15s %s, [%s, #+%u]",
-                 mnemonic, nameGpReg(rd), nameGpReg(rb), offset);
-            emitInst(static_cast<ARMWord>(cc) | DTR | DT_BYTE | (isLoad ? DT_LOAD : 0) | DT_UP, rd, rb, offset);
-        }
-
-        // Data transfers like this:
-        //  LDRSB rd, [rb, +offset]
-        //  STRSB rd, [rb, +offset]
-        void dtrsb_u(bool isLoad, int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            char const * mnemonic = (isLoad) ? ("ldrsb") : ("strb");
-            spew("%-15s %s, [%s, #+%u]",
-                 mnemonic, nameGpReg(rd), nameGpReg(rb), offset);
-            emitInst(static_cast<ARMWord>(cc) | DTRH | HDT_S | (isLoad ? DT_LOAD : 0) | DT_UP, rd, rb, offset);
-        }
-
-        // Data transfers like this:
-        //  LDRB rd, [rb, +rm]
-        //  STRB rd, [rb, +rm]
-        void dtrb_ur(bool isLoad, int rd, int rb, int rm, Condition cc = AL)
-        {
-            char const * mnemonic = (isLoad) ? ("ldrb") : ("strb");
-            spew("%-15s %s, [%s, +%s]",
-                 mnemonic, nameGpReg(rd), nameGpReg(rb), nameGpReg(rm));
-            emitInst(static_cast<ARMWord>(cc) | DTR | DT_BYTE | (isLoad ? DT_LOAD : 0) | DT_UP | OP2_OFSREG, rd, rb, rm);
-        }
-
-        // Data transfers like this:
-        //  LDRB rd, [rb, #-offset]
-        //  STRB rd, [rb, #-offset]
-        void dtrb_d(bool isLoad, int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            char const * mnemonic = (isLoad) ? ("ldrb") : ("strb");
-            spew("%-15s %s, [%s, #-%u]",
-                 mnemonic, nameGpReg(rd), nameGpReg(rb), offset);
-            emitInst(static_cast<ARMWord>(cc) | DTR | DT_BYTE | (isLoad ? DT_LOAD : 0), rd, rb, offset);
-        }
-
-        // Data transfers like this:
-        //  LDRSB rd, [rb, #-offset]
-        //  STRSB rd, [rb, #-offset]
-        void dtrsb_d(bool isLoad, int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            ASSERT(isLoad); /*can only do signed byte loads, not stores*/
-            char const * mnemonic = (isLoad) ? ("ldrsb") : ("strb");
-            spew("%-15s %s, [%s, #-%u]",
-                 mnemonic, nameGpReg(rd), nameGpReg(rb), offset);
-            emitInst(static_cast<ARMWord>(cc) | DTRH | HDT_S | (isLoad ? DT_LOAD : 0), rd, rb, offset);
-        }
-
-        // Data transfers like this:
-        //  LDRB rd, [rb, -rm]
-        //  STRB rd, [rb, -rm]
-        void dtrb_dr(bool isLoad, int rd, int rb, int rm, Condition cc = AL)
-        {
-            char const * mnemonic = (isLoad) ? ("ldrb") : ("strb");
-            spew("%-15s %s, [%s, -%s]",
-                 mnemonic, nameGpReg(rd), nameGpReg(rb), nameGpReg(rm));
-            emitInst(static_cast<ARMWord>(cc) | DTR | DT_BYTE | (isLoad ? DT_LOAD : 0) | OP2_OFSREG, rd, rb, rm);
-        }
-
-        void ldrh_r(int rd, int rb, int rm, Condition cc = AL)
-        {
-            spew("%-15s %s, [%s, +%s]",
-                 "ldrh", nameGpReg(rd), nameGpReg(rb), nameGpReg(rm));
-            emitInst(static_cast<ARMWord>(cc) | LDRH | HDT_UH | DT_UP | DT_PRE, rd, rb, rm);
-        }
-
-        void ldrh_d(int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            spew("%-15s %s, [%s, #-%u]",
-                 "ldrh", nameGpReg(rd), nameGpReg(rb), offset);
-            emitInst(static_cast<ARMWord>(cc) | LDRH | HDT_UH | DT_PRE, rd, rb, offset);
-        }
-
-        void ldrh_u(int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            spew("%-15s %s, [%s, #+%u]",
-                 "ldrh", nameGpReg(rd), nameGpReg(rb), offset);
-            emitInst(static_cast<ARMWord>(cc) | LDRH | HDT_UH | DT_UP | DT_PRE, rd, rb, offset);
-        }
-
-        void ldrsh_d(int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            spew("%-15s %s, [%s, #-%u]",
-                 "ldrsh", nameGpReg(rd), nameGpReg(rb), offset);
-            emitInst(static_cast<ARMWord>(cc) | LDRH | HDT_UH | HDT_S | DT_PRE, rd, rb, offset);
-       }
-
-        void ldrsh_u(int rd, int rb, ARMWord offset, Condition cc = AL)
-        {
-            spew("%-15s %s, [%s, #+%u]",
-                 "ldrsh", nameGpReg(rd), nameGpReg(rb), offset);
-            emitInst(static_cast<ARMWord>(cc) | LDRH | HDT_UH | HDT_S | DT_UP | DT_PRE, rd, rb, offset);
-        }
-
-        void strh_r(int rb, int rm, int rd, Condition cc = AL)
-        {
-            spew("%-15s %s, [%s, +%s]",
-                 "strh", nameGpReg(rd), nameGpReg(rb), nameGpReg(rm));
-            emitInst(static_cast<ARMWord>(cc) | STRH | HDT_UH | DT_UP | DT_PRE, rd, rb, rm);
-        }
-
-        void push_r(int reg, Condition cc = AL)
-        {
-            spew("%-15s {%s}",
-                 "push", nameGpReg(reg));
-            ASSERT(ARMWord(reg) <= 0xf);
-            m_buffer.putInt(cc | DTR | DT_WB | RN(ARMRegisters::sp) | RD(reg) | 0x4);
-        }
-
-        void pop_r(int reg, Condition cc = AL)
-        {
-            spew("%-15s {%s}",
-                 "pop", nameGpReg(reg));
-            ASSERT(ARMWord(reg) <= 0xf);
-            m_buffer.putInt(cc | (DTR ^ DT_PRE) | DT_LOAD | DT_UP | RN(ARMRegisters::sp) | RD(reg) | 0x4);
-        }
-
-        inline void poke_r(int reg, Condition cc = AL)
-        {
-            dtr_d(false, ARMRegisters::sp, 0, reg, cc);
-        }
-
-        inline void peek_r(int reg, Condition cc = AL)
-        {
-            dtr_u(true, reg, ARMRegisters::sp, 0, cc);
-        }
-
-
-
-#if WTF_ARM_ARCH_VERSION >= 5
-        void clz_r(int rd, int rm, Condition cc = AL)
-        {
-            spewInsWithOp2("clz", cc, rd, static_cast<ARMWord>(rm));
-            m_buffer.putInt(static_cast<ARMWord>(cc) | CLZ | RD(rd) | RM(rm));
-        }
-#endif
-
-        void bkpt(ARMWord value)
-        {
-#if WTF_ARM_ARCH_VERSION >= 5
-            spew("%-15s #0x%04x", "bkpt", value);
-            m_buffer.putInt(BKPT | ((value & 0xfff0) << 4) | (value & 0xf));
-#else
-            // Cannot access to Zero memory address
-            dtr_dr(true, ARMRegisters::S0, ARMRegisters::S0, ARMRegisters::S0);
-#endif
-        }
-
-        void bx(int rm, Condition cc = AL)
-        {
-#if WTF_ARM_ARCH_VERSION >= 5 || defined(__ARM_ARCH_4T__)
-            spew("bx%-13s %s", nameCC(cc), nameGpReg(rm));
-            emitInst(static_cast<ARMWord>(cc) | BX, 0, 0, RM(rm));
-#else
-            mov_r(ARMRegisters::pc, RM(rm), cc);
-#endif
-        }
-
-        JmpSrc blx(int rm, Condition cc = AL)
-        {
-#if WTF_CPU_ARM && WTF_ARM_ARCH_VERSION >= 5
-            int s = m_buffer.uncheckedSize();
-            spew("blx%-12s %s", nameCC(cc), nameGpReg(rm));
-            emitInst(static_cast<ARMWord>(cc) | BLX, 0, 0, RM(rm));
-#else
-            ASSERT(rm != 14);
-            ensureSpace(2 * sizeof(ARMWord), 0);
-            mov_r(ARMRegisters::lr, ARMRegisters::pc, cc);
-            int s = m_buffer.uncheckedSize();
-            bx(rm, cc);
-#endif
-            return JmpSrc(s);
-        }
-
-        static ARMWord lsl(int reg, ARMWord value)
-        {
-            ASSERT(reg <= ARMRegisters::pc);
-            ASSERT(value <= 0x1f);
-            return reg | (value << 7) | (LSL << 5);
-        }
-
-        static ARMWord lsr(int reg, ARMWord value)
-        {
-            ASSERT(reg <= ARMRegisters::pc);
-            ASSERT(value <= 0x1f);
-            return reg | (value << 7) | (LSR << 5);
-        }
-
-        static ARMWord asr(int reg, ARMWord value)
-        {
-            ASSERT(reg <= ARMRegisters::pc);
-            ASSERT(value <= 0x1f);
-            return reg | (value << 7) | (ASR << 5);
-        }
-
-        static ARMWord lsl_r(int reg, int shiftReg)
-        {
-            ASSERT(reg <= ARMRegisters::pc);
-            ASSERT(shiftReg <= ARMRegisters::pc);
-            return reg | (shiftReg << 8) | (LSL << 5) | 0x10;
-        }
-
-        static ARMWord lsr_r(int reg, int shiftReg)
-        {
-            ASSERT(reg <= ARMRegisters::pc);
-            ASSERT(shiftReg <= ARMRegisters::pc);
-            return reg | (shiftReg << 8) | (LSR << 5) | 0x10;
-        }
-
-        static ARMWord asr_r(int reg, int shiftReg)
-        {
-            ASSERT(reg <= ARMRegisters::pc);
-            ASSERT(shiftReg <= ARMRegisters::pc);
-            return reg | (shiftReg << 8) | (ASR << 5) | 0x10;
-        }
-
-        // General helpers
-
-        void forceFlushConstantPool()
-        {
-            m_buffer.flushWithoutBarrier(true);
-        }
-
-        size_t size() const
-        {
-            return m_buffer.uncheckedSize();
-        }
-
-        size_t allocSize() const
-        {
-            return m_buffer.allocSize();
-        }
-
-        void ensureSpace(int insnSpace, int constSpace)
-        {
-            m_buffer.ensureSpace(insnSpace, constSpace);
-        }
-
-        void ensureSpace(int space)
-        {
-            m_buffer.ensureSpace(space);
-        }
-
-        int sizeOfConstantPool()
-        {
-            return m_buffer.sizeOfConstantPool();
-        }
-
-        int flushCount()
-        {
-            return m_buffer.flushCount();
-        }
-
-        JmpDst label()
-        {
-            JmpDst label(m_buffer.size());
-            spew("#label     ((%d))", label.m_offset);
-            return label;
-        }
-
-        JmpDst align(int alignment)
-        {
-            while (!m_buffer.isAligned(alignment))
-                mov_r(ARMRegisters::r0, ARMRegisters::r0);
-
-            return label();
-        }
-
-        JmpSrc loadBranchTarget(int rd, Condition cc = AL, int useConstantPool = 0)
-        {
-            // The 'useConstantPool' flag really just indicates where we have
-            // to use the constant pool, for repatching. We might still use it,
-            // so ensure there's space for a pool constant irrespective of
-            // 'useConstantPool'.
-            ensureSpace(sizeof(ARMWord), sizeof(ARMWord));
-            int s = m_buffer.uncheckedSize();
-            ldr_un_imm(rd, InvalidBranchTarget, cc);
-            m_jumps.append(s | (useConstantPool & 0x1));
-            return JmpSrc(s);
-        }
-
-        JmpSrc jmp(Condition cc = AL, int useConstantPool = 0)
-        {
-            return loadBranchTarget(ARMRegisters::pc, cc, useConstantPool);
-        }
-
-        void* executableAllocAndCopy(ExecutableAllocator* allocator, ExecutablePool **poolp, CodeKind kind);
-        void executableCopy(void* buffer);
-        void fixUpOffsets(void* buffer);
-
-        // Patching helpers
-
-        static ARMWord* getLdrImmAddress(ARMWord* insn)
-        {
-#if WTF_CPU_ARM && WTF_ARM_ARCH_VERSION >= 5
-            // Check for call
-            if ((*insn & 0x0f7f0000) != 0x051f0000) {
-                // Must be BLX
-                ASSERT((*insn & 0x012fff30) == 0x012fff30);
-                insn--;
-            }
-#endif
-            // Must be an ldr ..., [pc +/- imm]
-            ASSERT((*insn & 0x0f7f0000) == 0x051f0000);
-
-            ARMWord addr = reinterpret_cast<ARMWord>(insn) + DefaultPrefetching * sizeof(ARMWord);
-            if (*insn & DT_UP)
-                return reinterpret_cast<ARMWord*>(addr + (*insn & SDT_OFFSET_MASK));
-            return reinterpret_cast<ARMWord*>(addr - (*insn & SDT_OFFSET_MASK));
-        }
-
-        static ARMWord* getLdrImmAddressOnPool(ARMWord* insn, uint32_t* constPool)
-        {
-            // Must be an ldr ..., [pc +/- imm]
-            ASSERT((*insn & 0x0f7f0000) == 0x051f0000);
-
-            if (*insn & 0x1)
-                return reinterpret_cast<ARMWord*>(constPool + ((*insn & SDT_OFFSET_MASK) >> 1));
-            return getLdrImmAddress(insn);
-        }
-
-        static void patchPointerInternal(intptr_t from, void* to)
-        {
-            ARMWord* insn = reinterpret_cast<ARMWord*>(from);
-            ARMWord* addr = getLdrImmAddress(insn);
-            *addr = reinterpret_cast<ARMWord>(to);
-        }
-
-        static ARMWord patchConstantPoolLoad(ARMWord load, ARMWord value)
-        {
-            value = (value << 1) + 1;
-            ASSERT(!(value & ~0xfff));
-            return (load & ~0xfff) | value;
-        }
-
-        static void patchConstantPoolLoad(void* loadAddr, void* constPoolAddr);
-
-        // Patch pointers
-
-        static void linkPointer(void* code, JmpDst from, void* to)
-        {
-            staticSpew("##linkPointer     ((%p + %#x)) points to ((%p))",
-                       code, from.m_offset, to);
-
-            patchPointerInternal(reinterpret_cast<intptr_t>(code) + from.m_offset, to);
-        }
-
-        static void repatchInt32(void* from, int32_t to)
-        {
-            staticSpew("##repatchInt32    ((%p)) holds ((%#x))",
-                       from, to);
-
-            patchPointerInternal(reinterpret_cast<intptr_t>(from), reinterpret_cast<void*>(to));
-        }
-
-        static void repatchPointer(void* from, void* to)
-        {
-            staticSpew("##repatchPointer  ((%p)) points to ((%p))",
-                       from, to);
-
-            patchPointerInternal(reinterpret_cast<intptr_t>(from), to);
-        }
-
-        static void repatchLoadPtrToLEA(void* from)
-        {
-            // On arm, this is a patch from LDR to ADD. It is restricted conversion,
-            // from special case to special case, altough enough for its purpose
-            ARMWord* insn = reinterpret_cast<ARMWord*>(from);
-            ASSERT((*insn & 0x0ff00f00) == 0x05900000);
-
-            *insn = (*insn & 0xf00ff0ff) | 0x02800000;
-            ExecutableAllocator::cacheFlush(insn, sizeof(ARMWord));
-        }
-
-        static void repatchLEAToLoadPtr(void* from)
-        {
-	    // Like repatchLoadPtrToLEA, this is specialized for our purpose.
-            ARMWord* insn = reinterpret_cast<ARMWord*>(from);
-	    if ((*insn & 0x0ff00f00) == 0x05900000)
-		return; // Valid ldr instruction
-            ASSERT((*insn & 0x0ff00000) == 0x02800000); // Valid add instruction
-            ASSERT((*insn & 0x00000f00) == 0x00000000); // Simple-to-handle immediates (no rotate)
-
-            *insn = (*insn &  0xf00ff0ff) | 0x05900000;
-            ExecutableAllocator::cacheFlush(insn, sizeof(ARMWord));
-        }
-
-        // Linkers
-
-        void linkJump(JmpSrc from, JmpDst to)
-        {
-            ARMWord  code = reinterpret_cast<ARMWord>(m_buffer.data());
-            ARMWord* insn = reinterpret_cast<ARMWord*>(code + from.m_offset);
-            ARMWord* addr = getLdrImmAddressOnPool(insn, m_buffer.poolAddress());
-
-            spew("##linkJump         ((%#x)) jumps to ((%#x))",
-                 from.m_offset, to.m_offset);
-
-            *addr = to.m_offset;
-        }
-
-        static void linkJump(void* code, JmpSrc from, void* to)
-        {
-            staticSpew("##linkJump        ((%p + %#x)) jumps to ((%p))",
-                       code, from.m_offset, to);
-
-            patchPointerInternal(reinterpret_cast<intptr_t>(code) + from.m_offset, to);
-        }
-
-        static void relinkJump(void* from, void* to)
-        {
-            staticSpew("##relinkJump      ((%p)) jumps to ((%p))",
-                       from, to);
-
-            patchPointerInternal(reinterpret_cast<intptr_t>(from), to);
-        }
-
-        static bool canRelinkJump(void* from, void* to)
-        {
-            return true;
-        }
-
-        static void linkCall(void* code, JmpSrc from, void* to)
-        {
-            staticSpew("##linkCall        ((%p + %#x)) jumps to ((%p))",
-                       code, from.m_offset, to);
-
-            patchPointerInternal(reinterpret_cast<intptr_t>(code) + from.m_offset, to);
-        }
-
-        static void relinkCall(void* from, void* to)
-        {
-            staticSpew("##relinkCall      ((%p)) jumps to ((%p))",
-                       from, to);
-
-            patchPointerInternal(reinterpret_cast<intptr_t>(from), to);
-        }
-
-        // Address operations
-
-        static void* getRelocatedAddress(void* code, JmpSrc jump)
-        {
-            return reinterpret_cast<void*>(reinterpret_cast<ARMWord*>(code) + jump.m_offset / sizeof(ARMWord));
-        }
-
-        static void* getRelocatedAddress(void* code, JmpDst label)
-        {
-            return reinterpret_cast<void*>(reinterpret_cast<ARMWord*>(code) + label.m_offset / sizeof(ARMWord));
-        }
-
-        // Address differences
-
-        static int getDifferenceBetweenLabels(JmpDst from, JmpSrc to)
-        {
-            return to.m_offset - from.m_offset;
-        }
-
-        static int getDifferenceBetweenLabels(JmpDst from, JmpDst to)
-        {
-            return to.m_offset - from.m_offset;
-        }
-
-        static unsigned getCallReturnOffset(JmpSrc call)
-        {
-            return call.m_offset + sizeof(ARMWord);
-        }
-
-        // Handle immediates
-
-        static ARMWord getOp2Byte(ARMWord imm)
-        {
-            ASSERT(imm <= 0xff);
-            return OP2_IMMh | (imm & 0x0f) | ((imm & 0xf0) << 4) ;
-        }
-
-        static ARMWord getOp2(ARMWord imm);
-
-        // Get an operand-2 field for immediate-shifted-registers in arithmetic
-        // instructions.
-        static ARMWord getOp2RegScale(RegisterID reg, ARMWord scale);
-
-#if WTF_ARM_ARCH_VERSION >= 7
-        static ARMWord getImm16Op2(ARMWord imm)
-        {
-            if (imm <= 0xffff)
-                return (imm & 0xf000) << 4 | (imm & 0xfff);
-            return INVALID_IMM;
-        }
-#endif
-        ARMWord getImm(ARMWord imm, int tmpReg, bool invert = false);
-        void moveImm(ARMWord imm, int dest);
-        ARMWord encodeComplexImm(ARMWord imm, int dest);
-
-        ARMWord getOffsetForHalfwordDataTransfer(ARMWord imm, int tmpReg)
-        {
-            // Encode immediate data in the instruction if it is possible
-            if (imm <= 0xff)
-                return getOp2Byte(imm);
-            // Otherwise, store the data in a temporary register
-            return encodeComplexImm(imm, tmpReg);
-        }
-
-        // Memory load/store helpers
-        void dataTransferN(bool isLoad, bool isSigned, int size, RegisterID srcDst, RegisterID base, int32_t offset);
-
-        void dataTransfer32(bool isLoad, RegisterID srcDst, RegisterID base, int32_t offset);
-        void dataTransfer8(bool isLoad, RegisterID srcDst, RegisterID base, int32_t offset, bool isSigned);
-        void baseIndexTransferN(bool isLoad, bool isSigned, int size, RegisterID srcDst, RegisterID base, RegisterID index, int scale, int32_t offset);
-        void baseIndexTransfer32(bool isLoad, RegisterID srcDst, RegisterID base, RegisterID index, int scale, int32_t offset);
-        void doubleTransfer(bool isLoad, FPRegisterID srcDst, RegisterID base, int32_t offset);
-        void doubleTransfer(bool isLoad, FPRegisterID srcDst, RegisterID base, int32_t offset, RegisterID index, int32_t scale);
-
-        void floatTransfer(bool isLoad, FPRegisterID srcDst, RegisterID base, int32_t offset);
-        /**/
-        void baseIndexFloatTransfer(bool isLoad, bool isDouble, FPRegisterID srcDst, RegisterID base, RegisterID index, int scale, int32_t offset);
-
-        // Constant pool hnadlers
-
-        static ARMWord placeConstantPoolBarrier(int offset)
-        {
-            offset = (offset - sizeof(ARMWord)) >> 2;
-            ASSERT((offset <= BOFFSET_MAX && offset >= BOFFSET_MIN));
-            return AL | B | (offset & BRANCH_MASK);
-        }
-
-        // pretty-printing functions
-        static char const * nameGpReg(int reg)
-        {
-            ASSERT(reg <= 16);
-            ASSERT(reg >= 0);
-            static char const * const names[] = {
-                "r0", "r1", "r2", "r3",
-                "r4", "r5", "r6", "r7",
-                "r8", "r9", "r10", "r11",
-                "ip", "sp", "lr", "pc"
-            };
-            return names[reg];
-        }
-
-        static char const * nameFpRegD(int reg)
-        {
-            ASSERT(reg <= 31);
-            ASSERT(reg >= 0);
-            static char const * const names[] = {
-                 "d0",   "d1",   "d2",   "d3",
-                 "d4",   "d5",   "d6",   "d7",
-                 "d8",   "d9",  "d10",  "d11",
-                "d12",  "d13",  "d14",  "d15",
-                "d16",  "d17",  "d18",  "d19",
-                "d20",  "d21",  "d22",  "d23",
-                "d24",  "d25",  "d26",  "d27",
-                "d28",  "d29",  "d30",  "d31"
-            };
-            return names[reg];
-        }
-        static char const * nameFpRegS(int reg)
-        {
-            ASSERT(reg <= 31);
-            ASSERT(reg >= 0);
-            static char const * const names[] = {
-                 "s0",   "s1",   "s2",   "s3",
-                 "s4",   "s5",   "s6",   "s7",
-                 "s8",   "s9",  "s10",  "s11",
-                "s12",  "s13",  "s14",  "s15",
-                "s16",  "s17",  "s18",  "s19",
-                "s20",  "s21",  "s22",  "s23",
-                "s24",  "s25",  "s26",  "s27",
-                "s28",  "s29",  "s30",  "s31"
-            };
-            return names[reg];
-        }
-
-        static char const * nameCC(Condition cc)
-        {
-            ASSERT(cc <= AL);
-            ASSERT((cc & 0x0fffffff) == 0);
-
-            uint32_t    ccIndex = cc >> 28;
-            static char const * const names[] = {
-                "eq", "ne",
-                "cs", "cc",
-                "mi", "pl",
-                "vs", "vc",
-                "hi", "ls",
-                "ge", "lt",
-                "gt", "le",
-                "  "        // AL is the default, so don't show it.
-            };
-            return names[ccIndex];
-        }
-
-    private:
-        // Decodes operand 2 immediate values (for debug output and assertions).
-        inline uint32_t decOp2Imm(uint32_t op2)
-        {
-            ASSERT((op2 & ~0xfff) == 0);
-
-            uint32_t    imm8 = op2 & 0xff;
-            uint32_t    rot = ((op2 >> 7) & 0x1e);
-
-            // 'rot' is a right-rotate count.
-
-            uint32_t    imm = (imm8 >> rot);
-            if (rot > 0) {
-                imm |= (imm8 << (32-rot));
-            }
-
-            return imm;
-        }
-
-        // Format the operand 2 argument for debug spew. The operand can be
-        // either an immediate or a register specifier.
-        void fmtOp2(char * out, ARMWord op2)
-        {
-            static char const * const shifts[4] = {"LSL", "LSR", "ASR", "ROR"};
-
-            if ((op2 & OP2_IMM) || (op2 & OP2_IMMh)) {
-                // Immediate values.
-
-                uint32_t    imm = decOp2Imm(op2 & ~(OP2_IMM | OP2_IMMh));
-                sprintf(out, "#0x%x @ (%d)", imm, static_cast<int32_t>(imm));
-            } else {
-                // Register values.
-
-                char const *    rm = nameGpReg(op2 & 0xf);
-                Shift           type = static_cast<Shift>((op2 >> 5) & 0x3);
-
-                // Bit 4 specifies barrel-shifter parameters in operand 2.
-                if (op2 & (1<<4)) {
-                    // Register-shifted register.
-                    // Example: "r0, LSL r6"
-                    char const *    rs = nameGpReg((op2 >> 8) & 0xf);
-                    sprintf(out, "%s, %s %s", rm, shifts[type], rs);
-                } else {
-                    // Immediate-shifted register.
-                    // Example: "r0, ASR #31"
-                    uint32_t        imm = (op2 >> 7) & 0x1f;
-
-                    // Deal with special encodings.
-                    if ((type == LSL) && (imm == 0)) {
-                        // "LSL #0" doesn't shift at all (and is the default).
-                        sprintf(out, "%s", rm);
-                        return;
-                    }
-
-                    if ((type == ROR) && (imm == 0)) {
-                        // "ROR #0" is a special case ("RRX").
-                        sprintf(out, "%s, RRX", rm);
-                        return;
-                    }
-
-                    if (((type == LSR) || (type == ASR)) && (imm == 0)) {
-                        // Both LSR and ASR have a range of 1-32, with 32
-                        // encoded as 0.
-                        imm = 32;
-                    }
-
-                    // Print the result.
-
-                    sprintf(out, "%s, %s #%u", rm, shifts[type], imm);
-                }
-            }
-        }
-
-        void spewInsWithOp2(char const * ins, Condition cc, int rd, int rn, ARMWord op2)
-        {
-#if defined(JS_METHODJIT_SPEW)
-            char    mnemonic[16];
-            snprintf(mnemonic, 16, "%s%s", ins, nameCC(cc));
-
-            char    op2_fmt[48];
-            fmtOp2(op2_fmt, op2);
-
-            spew("%-15s %s, %s, %s", mnemonic, nameGpReg(rd), nameGpReg(rn), op2_fmt);
-#endif
-        }
-
-        void spewInsWithOp2(char const * ins, Condition cc, int r, ARMWord op2)
-        {
-#if defined(JS_METHODJIT_SPEW)
-            char    mnemonic[16];
-            snprintf(mnemonic, 16, "%s%s", ins, nameCC(cc));
-
-            char    op2_fmt[48];
-            fmtOp2(op2_fmt, op2);
-
-            spew("%-15s %s, %s", mnemonic, nameGpReg(r), op2_fmt);
-#endif
-        }
-
-        ARMWord RM(int reg)
-        {
-            ASSERT(reg <= ARMRegisters::pc);
-            return reg;
-        }
-
-        ARMWord RS(int reg)
-        {
-            ASSERT(reg <= ARMRegisters::pc);
-            return reg << 8;
-        }
-
-        ARMWord RD(int reg)
-        {
-            ASSERT(reg <= ARMRegisters::pc);
-            return reg << 12;
-        }
-
-        ARMWord RN(int reg)
-        {
-            ASSERT(reg <= ARMRegisters::pc);
-            return reg << 16;
-        }
-
-        ARMWord DD(int reg)
-        {
-            ASSERT(reg <= ARMRegisters::d31);
-            // Endoded as bits [22,15:12].
-            return ((reg << 12) | (reg << 18)) & 0x0040f000;
-        }
-
-        ARMWord DN(int reg)
-        {
-            ASSERT(reg <= ARMRegisters::d31);
-            // Endoded as bits [7,19:16].
-            return ((reg << 16) | (reg << 3)) & 0x000f0080;
-        }
-
-        ARMWord DM(int reg)
-        {
-            ASSERT(reg <= ARMRegisters::d31);
-            // Encoded as bits [5,3:0].
-            return ((reg << 1) & 0x20) | (reg & 0xf);
-        }
-
-        ARMWord SD(int reg)
-        {
-            ASSERT(reg <= ARMRegisters::d31);
-            // Endoded as bits [15:12,22].
-            return ((reg << 11) | (reg << 22)) & 0x0040f000;
-        }
-
-        ARMWord SM(int reg)
-        {
-            ASSERT(reg <= ARMRegisters::d31);
-            // Encoded as bits [5,3:0].
-            return ((reg << 5) & 0x20) | ((reg >> 1) & 0xf);
-        }
-        ARMWord SN(int reg)
-        {
-            ASSERT(reg <= ARMRegisters::d31);
-            // Encoded as bits [19:16,7].
-            return ((reg << 15) & 0xf0000) | ((reg & 1) << 7);
-        }
-        static ARMWord getConditionalField(ARMWord i)
-        {
-            return i & 0xf0000000;
-        }
-
-        int genInt(int reg, ARMWord imm, bool positive);
-
-        ARMBuffer m_buffer;
-        Jumps m_jumps;
-    public:
-        // VFP instruction constants
-        enum {
-            VFP_DATA  = 0x0E000A00,